aboutsummaryrefslogtreecommitdiff
path: root/src/db.rs
blob: 053142abe888f1a31cd436c3d2bf9a6f376b330b (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use serde::{Serialize, Deserialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::PathBuf;
use std::{fs::File, io::Write};

use crate::uid::{self, UID};

#[derive(Serialize, Deserialize)]
pub struct Config {
    dbsave: PathBuf,
    realm: String,
}
impl Config {
    pub fn new() -> Config {
        Config { dbsave: "db.json".into(), realm: "localhost".into() }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum Color {
    White,
    Red,
    Blue,
    Green,
    Yellow,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Token {
    color: Color,
    amount: usize,
}
impl Token {
    pub fn new(color: Color, amount: usize) -> Token {
        Token { color, amount }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
    name: String,
    hashed_password: String,
    id: UID,
    sessions: HashMap<String, String>,
    tokovec: Vec<Token>,
}
impl User {
    pub fn new(name: String, password: String, id: UID) -> User {
        let base_tokens = vec![
            Token::new(Color::White, 2),
            Token::new(Color::Red, 2),
            Token::new(Color::Blue, 2),
            Token::new(Color::Green, 2),
            Token::new(Color::Yellow, 2),
        ];

        let hashed_password = User::hash(&password);

        User { name, hashed_password, id, tokovec: base_tokens, sessions: HashMap::new() }
    }

    fn update_name(&mut self, new_name: String) {
        self.name = new_name;
    }

    fn update_password(&mut self, old_password: &String, new_password: &String) -> Result<(), String> {
        if self.same_password(old_password) {
            self.hashed_password = User::hash(&new_password);
            return Ok(());
        } else {
            return Err("Old Password is Incorrect".into())
        }
    }

    fn same_password(&self, password: &String) -> bool {
        User::hash(password) == self.hashed_password
    }

    fn hash(t: &String) -> String {
        let hashed = Sha256::digest(&t);
        let hashed = base16ct::lower::encode_string(&hashed);

        hashed
    }

    fn new_session(&mut self, client: String) -> String {
        let hash: [u8; 32] = rand::random();
        let hash = User::hash(&hash.iter().map(|v| {format!("{}", v)}).collect());
        self.sessions.insert(hash.clone(), client);
        hash
    }

    fn rm_session(&mut self, session: &String) -> Result<(), String> {
        match self.sessions.remove(session) {
            Some(_) => Ok(()),
            None => Err("Could not find sessoin".into()),
        }
    }

    fn clear_sessions(&mut self, session: &String) {
        if self.authenticate(session) {
            self.sessions.clear()
        }
    }

    fn get_sessions(&self, session: &String) -> Result<Vec<(String, String)>, String> {
        if self.authenticate(session) {
            let v = self.sessions.iter().map(|(k, v)| {
                (k.clone(), v.clone())
            }).collect();
            Ok(v)
        } else {
            Err("Not Authenticated".into())
        }
    }

    fn login(&mut self, password: &String, clientid: &String) -> Result<String, String> {
        if self.hashed_password == User::hash(password) {
            Ok(self.new_session(clientid.clone()))
        } else {
            Err("Could not login".into())
        }
    }

    fn authenticate(&self, session: &String) -> bool {
        match self.sessions.get(session) {
            // Session authenticated/found
            Some(_) => true,
            // Session not found
            None => false,
        }

    }

    fn logout(&mut self, session: &String) -> Result<(), String> {
        if self.authenticate(session) {
            self.rm_session(session)
        } else {
            Err("Not Authenticated".into())
        }
    }

    pub fn get_name(&self) -> String {
        self.name.clone()
    }
    pub fn get_tokovec(&self) -> Vec<Token> {
        self.tokovec.clone()
    }
    pub fn get_id(&self) -> UID {
        self.id
    }
}

#[derive(Serialize, Deserialize)]
pub struct DB {
    pub uid_generator: uid::Generator,
    users: Vec<User>,
    config: Config,
}
impl DB {
    async fn save(&self) -> Result<(), String> {
        let mut f = match File::create(&self.config.dbsave) {
            Ok(n) => n,
            Err(n) => {
                match n.kind() {
                    std::io::ErrorKind::PermissionDenied => panic!("{:?}: Permission Denied", &self.config.dbsave),
                    n => return Err(n.to_string()),
                }
            },
        };
        let s = match serde_json::to_string(self) {
            Ok(n) => n,
            Err(n) => return Err(n.to_string()),
        };
        match f.write(s.as_bytes()) {
            Ok(_) => return Ok(()),
            Err(n) => return Err(n.to_string()),
        };
    }
    pub fn load(c: Config) -> Self {
        match File::open(&c.dbsave) {
            Ok(n) => {
                match serde_json::from_reader(n) {
                    Ok(n) => n,
                    Err(n) => panic!("{}", n),
                }
            },
            Err(n) => match n.kind() {
                std::io::ErrorKind::PermissionDenied => panic!("{:?}: Permission Denied", &c.dbsave),
                _ => DB::new(c),
            },
        }
    }
    pub fn new(config: Config) -> Self {
        DB { uid_generator: uid::Generator::new(), users: vec![], config }
    }

    pub fn get_user(&self, id: UID) -> Result<&User, String> {
        for u in self.users.iter() {
            if u.id == id {
                return Ok(u)
            }
        }

        Err("User Not Found".into())
    }

    pub async fn update_user_password(&mut self, id: UID, session: &String, old_password: &String, new_password: &String) -> Result<(), String> {
        self.get_user_authenticated(id, session).await?;
        let user = self.get_mut_user(id).await?;
        user.update_password(old_password, new_password)?;

        self.save().await?;

        Ok(())
    }

    pub async fn update_user_name(&mut self, id: UID, session: &String, name: &String) -> Result<(), String> {
        self.get_user_authenticated(id, session).await?;
        let user = self.get_mut_user(id).await?;
        user.update_name(name.clone());

        self.save().await?;

        Ok(())
    }

    pub async fn get_user_authenticated(&self, id: UID, session: &String) -> Result<&User, String> {
        match self.get_user(id) {
            Ok(u) => {
                if u.authenticate(session) {
                    Ok(u)
                } else {
                    Err("Not Authenticated".into())
                }
            },
            Err(n) => Err(n)
        }
    }
    pub async fn get_mut_user(&mut self, id: UID) -> Result<&mut User, String> {
        for u in self.users.iter_mut() {
            if u.id == id {
                return Ok(u)
            }
        }

        Err("User Not Found".into())
    }

    pub async fn get_user_by_name(&self, name: &str) -> Result<Vec<User>, String> {
        let mut vec = vec![];
        for u in self.users.clone() {
            if u.name == name {
                vec.push(u)
            }
        }

        if vec.len() == 0 {
            Err("User(s) Not Found".into())
        } else {
            return Ok(vec)
        }

    }

    pub async fn get_all_users(&self) -> Result<Vec<User>, String> {
        if self.users.len() == 0 {
            Err("No Users".into())
        } else {
            Ok(self.users.clone())
        }
    }

    pub async fn new_user(&mut self, name: String, password: String, id: UID) -> Result<User, String> {
        let user = User::new(name, password, id);
        self.users.push(user.clone());
        match self.save().await {
            Ok(_) => Ok(user),
            Err(n) => Err(n),
        }
        
    }

    pub async fn login(&mut self, id: UID, password: &String, clientid: &String) -> Result<String, String> {
        let r = match self.get_mut_user(id).await {
            Ok(n) => {
                n.login(password, clientid)
            },
            Err(n) => Err(n)
        };

        let _ = self.save().await;
        r
    }
    pub async fn logout(&mut self, id: UID, session: &String) -> Result<(), String> {
        let r = match self.get_mut_user(id).await {
            Ok(n) => {
                n.logout(session)
            },
            Err(n) => Err(n)
        };
        
        let _ = self.save().await;
        r
    }
    pub async fn logout_all(&mut self, id: UID, session: &String) -> Result<String, String> {
        let r = match self.get_mut_user(id).await {
            Ok(n) => {
                n.clear_sessions(session);
                Ok("Logged out of everything".into())
            },
            Err(n) => Err(n)
        };
        
        let _ = self.save().await;
        r
    }

    pub async fn get_sessions(&self, id: UID, session: &String) -> Result<Vec<(String, String)>, String> {
        let r = match self.get_user(id) {
            Ok(n) => {
                n.get_sessions(session)
            },
            Err(n) => Err(n)
        };
        
        let _ = self.save().await;
        r
    }

    pub async fn delete_user(&mut self, id: UID, session: &String, password: &String) -> Result<String, String> {
        let u = self.get_user(id)?;
        if u.same_password(password) {
            self.users = self.users.clone().into_iter().filter(|u| !u.authenticate(session) && id != u.id).collect();
            self.uid_generator.delete_uid(id);
    
            // Validate
            let r = match self.get_user(id) {
                Ok(_) => Err("Could not delete".into()),
                Err(_) => {
                    Ok("Deleted".into())
                },
            };
    
            let _ = self.save().await;
            r
        } else {
            return Err("Password does not match".into())
        }
    }

    pub async fn transfer(&mut self, from: UID, to: UID, session: &String, color: Color, amount: usize) -> Result<(), String> {
        let mut subtracted = false;
        
        let from = self.get_mut_user(from).await?;
        // If authenticated
        if from.authenticate(session) {
            for v in from.tokovec.iter_mut() {
                // Get the token of the right color
                if v.color == color {
                    // If amount is greater or equal to amount being sent
                    // and if the amount does not overflow past 0
                    if v.amount >= amount && v.amount.checked_sub(amount) != None {
                        // Remove from account
                        v.amount -= amount;
                        subtracted = true;
                    }
                }
            }
        }

        let to = self.get_mut_user(to).await?;
        if subtracted {
            for v in to.tokovec.iter_mut() {
                if v.color == color {
                    v.amount += amount
                }
            }

            let _ = self.save().await;
            Ok(())
        } else {
            Err("Could not complete transaction".into())
        }

    }
}