aboutsummaryrefslogtreecommitdiff
path: root/src/users.rs
blob: 0c93b83ec1dae2b32c4541e7152cb8fe80a99eca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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())
    }
}