//! A users abstraction module use crate::{ wire::{LobbyErr, User, UserId}, Id, }; use async_std::sync::{Arc, RwLock}; use std::{ collections::BTreeMap, sync::atomic::{AtomicUsize, Ordering}, }; pub struct MetaUser { pub id: UserId, pub name: String, pub pw: String, pub auth: User, } pub struct UserStore { max: AtomicUsize, users: RwLock>>, } impl UserStore { /// Currently resuming a userstore isn't possible pub fn new() -> Self { UserStore { max: 0.into(), users: Default::default(), } } /// Get the metadata user for a login user pub async fn get(&self, user: &User) -> Result, LobbyErr> { match self.users.read().await.get(&user.id) { Some(ref u) => Ok(Arc::clone(u)), None => Err(LobbyErr::OtherError), } } pub async fn add>>( &self, name: String, pw: S, registered: bool, ) -> (UserId, User) { let id = self.max.fetch_add(1, Ordering::Relaxed); let token = Id::random(); let pw = pw.into().unwrap_or("".into()); let auth = User { id, token, registered, }; self.users.write().await.insert( id, MetaUser { id, name, pw, auth: auth.clone(), } .into(), ); (id, auth.clone()) } }