My personal project and infrastructure archive
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
nomicon/games/rstnode/rst-core/src/users.rs

69 lines
1.5 KiB

//! 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())
}
}