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.
70 lines
1.5 KiB
70 lines
1.5 KiB
4 years ago
|
//! A users abstraction module
|
||
|
|
||
|
use crate::{
|
||
4 years ago
|
wire::{LobbyErr, User, UserId},
|
||
4 years ago
|
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(),
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
/// 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),
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
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())
|
||
|
}
|
||
|
}
|