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
|
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)]
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 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("Not Found".into())
}
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("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("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<(), String> {
let user = User::new(name, password, id);
self.users.push(user);
self.save().await
}
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) -> Result<String, String> {
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
}
}
|