diff options
Diffstat (limited to 'games/rstnode/src/users.rs')
-rw-r--r-- | games/rstnode/src/users.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/games/rstnode/src/users.rs b/games/rstnode/src/users.rs new file mode 100644 index 000000000000..0c93b83ec1da --- /dev/null +++ b/games/rstnode/src/users.rs @@ -0,0 +1,69 @@ +//! 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<BTreeMap<UserId, Arc<MetaUser>>>, +} + +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<Arc<MetaUser>, LobbyErr> { + match self.users.read().await.get(&user.id) { + Some(ref u) => Ok(Arc::clone(u)), + None => Err(LobbyErr::OtherError), + } + } + + pub async fn add<S: Into<Option<String>>>( + &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()) + } +} |