-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathuser_accounts.rs
More file actions
632 lines (561 loc) · 24.8 KB
/
user_accounts.rs
File metadata and controls
632 lines (561 loc) · 24.8 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// Copyright (c) 2023 Open Community Project Association https://ocpa.ch
// This software is published under the AGPLv3 license.
//! User Account Module
//!
//! In qaul each user is defined by the following things
//!
//! * user ID (hash of the public key)
//! * Public / private key
//! * user name (optional)
use crate::router;
use crate::rpc::Rpc;
use crate::storage::configuration;
use crate::storage::configuration::Configuration;
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use base64::Engine;
use libp2p::{
identity::{ed25519, Keypair, PublicKey},
PeerId,
};
use prost::Message;
use state::InitCell;
use std::sync::RwLock;
/// Import protobuf message definition
pub use qaul_proto::qaul_rpc_user_accounts as proto;
/// mutable state of users table
static USERACCOUNTS: InitCell<RwLock<UserAccounts>> = InitCell::new();
#[derive(Clone)]
pub struct UserAccount {
pub id: PeerId,
pub keys: Keypair,
pub name: String,
pub password_hash: Option<String>,
pub password_salt: Option<String>,
}
pub struct UserAccounts {
pub users: Vec<UserAccount>,
}
impl UserAccounts {
/// Create a new UserAccounts instance from configuration (instance-based)
///
/// This is the new API for creating UserAccounts without global state.
pub fn create_from_config(config: &Configuration) -> Self {
let mut accounts = UserAccounts { users: Vec::new() };
for user in &config.user_accounts {
let mut basedecode = base64::engine::general_purpose::STANDARD
.decode(&user.keys)
.unwrap();
let ed25519_keys = ed25519::Keypair::try_from_bytes(&mut basedecode).unwrap();
let keys = Keypair::from(ed25519_keys);
let id = PeerId::from(keys.public());
// check if saved ID and the id from the keypair are equal
if id.to_string() == user.id {
log::trace!("user id's of '{}' match {}", user.name, user.id);
} else {
log::error!("------------------------------------");
log::error!("ERROR: user id's of '{}' are not equal", user.name);
log::error!("{} {}", id.to_string(), user.id);
log::error!("------------------------------------");
}
// push to user accounts table
accounts.users.push(UserAccount {
name: user.name.clone(),
id,
keys: keys.clone(),
password_hash: user.password_hash.clone(),
password_salt: user.password_salt.clone(),
});
}
accounts
}
/// Initialize from global configuration (global state - for backward compatibility)
///
/// Note: This uses global state. For new code, prefer using `create_from_config()`.
pub fn init() {
let config = Configuration::get();
let accounts = Self::create_from_config(&config);
// save users to state
USERACCOUNTS.set(RwLock::new(accounts));
}
/// create a new user account with username and an optional password
pub fn create(name: String, password: Option<String>) -> UserAccount {
// create user
let keys_ed25519 = Keypair::generate_ed25519();
let keys_config = base64::engine::general_purpose::STANDARD
.encode(keys_ed25519.clone().try_into_ed25519().unwrap().to_bytes());
/*
{
// questions:
// - what did we save before? private key? keypair?
// - answer: keypair!: ed25519::Keypair
// get the binary ed25519 keypair
let ed25519_binary_keypair =
keys_ed25519.clone().try_into_ed25519().unwrap().to_bytes();
// test the key encoding
log::info!("==============================");
log::info!("Test Key Saveing Configuration");
log::info!("------------------------------");
log::info!("keys_config: {}", keys_config.clone());
// convert the string into a keypair again
let mut binary2 = base64::engine::general_purpose::STANDARD
.decode(&keys_config)
.unwrap();
// binary comparison of the keypairs
log::info!("binary keypair before encoding:");
log::info!("{:?}", ed25519_binary_keypair);
log::info!("binary keypair after encoding: ");
log::info!("{:?}", binary2);
log::info!("------------------------------");
// reconvert into a Keypair structure
let ed_kp2 = ed25519::Keypair::try_from_bytes(&mut binary2).unwrap();
let _kp2 = Keypair::from(ed_kp2);
log::info!("==============================");
}
*/
let id = PeerId::from(keys_ed25519.public());
let (password_hash, password_salt) = Self::hash_password(password);
let user = UserAccount {
id,
keys: keys_ed25519.clone(),
name: name.clone(),
password_hash: password_hash.clone(),
password_salt: password_salt.clone(),
};
// save it to state
let mut users = USERACCOUNTS.get().write().unwrap();
users.users.push(user.clone());
// save it to config
{
let mut config = Configuration::get_mut();
config.user_accounts.push(configuration::UserAccount {
name: name.clone(),
id: id.to_string(),
keys: keys_config,
password_hash: password_hash.clone(),
password_salt: password_salt.clone(),
session_token: None,
storage: configuration::StorageOptions::default(),
});
}
Configuration::save();
let mut initial_user = router::users::User {
id,
key: keys_ed25519.public(),
name: name.clone(),
verified: false,
blocked: false,
bio: String::new(),
avatar: Vec::new(),
version: 1,
updated_at: crate::utilities::timestamp::Timestamp::get_timestamp(),
signed_profile_bytes: Vec::new(),
signed_profile_signature: Vec::new(),
};
let signed = router::users::Users::create_signed_profile(&initial_user, &keys_ed25519);
initial_user.signed_profile_bytes = signed.profile;
initial_user.signed_profile_signature = signed.signature;
crate::router::users::Users::add(initial_user);
// add user to routing table / connections table
crate::router::connections::ConnectionTable::add_local_user(id);
// display id
log::trace!("created user account '{}' {:?}", name, id);
user
}
/// set or update the password for existing user
pub fn set_password(user_id: PeerId, password: Option<String>) -> Result<(), String> {
let (password_hash, password_salt) = Self::hash_password(password);
// update the configuration
{
let mut config = Configuration::get_mut();
if let Some(user_config) = config
.user_accounts
.iter_mut()
.find(|u| u.id == user_id.to_string())
{
user_config.password_hash = password_hash.clone();
user_config.password_salt = password_salt.clone();
}
}
Configuration::save();
{
let mut users = USERACCOUNTS.get().write().unwrap();
if let Some(user) = users.users.iter_mut().find(|u| u.id == user_id) {
user.password_hash = password_hash;
user.password_salt = password_salt;
}
}
Ok(())
}
/// verify password for user
pub fn verify_password(user_id: PeerId, password: String) -> Result<bool, String> {
let users = USERACCOUNTS.get().read().unwrap();
let user = users
.users
.iter()
.find(|u| u.id == user_id)
.ok_or("User not found")?;
match &user.password_hash {
Some(hash) => {
let argon2 = Argon2::default();
let parsed_hash = PasswordHash::new(hash)
.map_err(|e| format!("Invalid stored hash format {}", e))?;
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
Ok(()) => Ok(true),
Err(_) => Ok(false),
}
}
// no password is set, so always allow
None => Ok(true),
}
}
/// check if a user has password set
pub fn has_password(user_id: PeerId) -> bool {
let users = USERACCOUNTS.get().read().unwrap();
users
.users
.iter()
.find(|u| u.id == user_id)
.map_or(false, |user| user.password_hash.is_some())
}
/// get user account by id
pub fn get_by_id(account_id: PeerId) -> Option<UserAccount> {
// get state
let accounts = USERACCOUNTS.get().read().unwrap();
// search for ID in accounts
let mut account_result = None;
for item in &accounts.users {
if item.id == account_id {
account_result = Some(item.clone());
break;
}
}
account_result
}
/// Return the number of registered user accounts on this node.
#[allow(dead_code)]
pub fn len() -> usize {
let users = USERACCOUNTS.get().read().unwrap();
users.users.len()
}
/// Return the default user.
/// The first registered user account is returned.
pub fn get_default_user() -> Option<UserAccount> {
// get state
let users = USERACCOUNTS.get().read().unwrap();
// check if a user exists
if users.users.len() == 0 {
return None;
}
// get user account
let user = users.users.first().unwrap();
// Some(UserAccount {
// id: user.id.clone(),
// keys: user.keys.clone(),
// name: user.name.clone(),
// });
Some(user.clone())
}
/// to fill the routing table get all users
pub fn get_user_info() -> Vec<router::users::User> {
let mut user_info = Vec::new();
let users = USERACCOUNTS.get().read().unwrap();
for user in &users.users {
user_info.push(router::users::User {
id: user.id,
key: user.keys.public(),
name: user.name.clone(),
verified: false,
blocked: false,
bio: String::new(),
avatar: Vec::new(),
version: 0,
updated_at: 0,
signed_profile_bytes: Vec::new(),
signed_profile_signature: Vec::new(),
});
}
user_info
}
pub fn get_all_users() -> Vec<UserAccount> {
let accounts = USERACCOUNTS.get().read().unwrap();
accounts.users.clone()
}
/// checks if user account exists
///
/// returns true if a user account with the given ID exists
#[allow(dead_code)]
pub fn is_account(user_id: PeerId) -> bool {
// get user accounts state
let users = USERACCOUNTS.get().read().unwrap();
// loop through user accounts and compare
for user in &users.users {
if user.id == user_id {
return true;
}
}
false
}
/// Process incoming RPC request messages for user accounts
pub fn rpc(data: Vec<u8>, user_id: Vec<u8>, request_id: String) {
match proto::UserAccounts::decode(&data[..]) {
Ok(user_accounts) => {
match user_accounts.message {
Some(proto::user_accounts::Message::GetDefaultUserAccount(_)) => {
// create message
let proto_message;
match Self::get_default_user() {
Some(user_account) => {
// get RPC key values
let (key_type, key_base58) =
Self::get_protobuf_public_key(user_account.keys.public());
// pack user into protobuf message
proto_message = proto::UserAccounts {
message: Some(
proto::user_accounts::Message::DefaultUserAccount(
proto::DefaultUserAccount {
user_account_exists: true,
my_user_account: Some(proto::MyUserAccount {
name: user_account.name,
id: user_account.id.to_bytes(),
id_base58: user_account.id.to_base58(),
key: user_account
.keys
.public()
.encode_protobuf(),
key_type,
key_base58,
has_password: user_account
.password_hash
.is_some(),
}),
},
),
),
};
}
None => {
// there is no default user so send this information
proto_message = proto::UserAccounts {
message: Some(
proto::user_accounts::Message::DefaultUserAccount(
proto::DefaultUserAccount {
user_account_exists: false,
my_user_account: None,
},
),
),
};
}
}
// encode message
let mut buf = Vec::with_capacity(proto_message.encoded_len());
proto_message
.encode(&mut buf)
.expect("Vec<u8> provides capacity as needed");
// send message
Rpc::send_message(
buf,
crate::rpc::proto::Modules::Useraccounts.into(),
request_id,
Vec::new(),
);
}
Some(proto::user_accounts::Message::CreateUserAccount(create_user_account)) => {
// create user account
let user_account =
Self::create(create_user_account.name, create_user_account.password);
// get RPC key values
let (key_type, key_base58) =
Self::get_protobuf_public_key(user_account.keys.public());
// return new user account with password status
let proto_message = proto::UserAccounts {
message: Some(proto::user_accounts::Message::MyUserAccount(
proto::MyUserAccount {
name: user_account.name,
id: user_account.id.to_bytes(),
id_base58: user_account.id.to_base58(),
key: user_account.keys.public().encode_protobuf(),
key_type,
key_base58,
has_password: user_account.password_hash.is_some(),
},
)),
};
// encode message
let mut buf = Vec::with_capacity(proto_message.encoded_len());
proto_message
.encode(&mut buf)
.expect("Vec<u8> provides capacity as needed");
// send message
Rpc::send_message(
buf,
crate::rpc::proto::Modules::Useraccounts.into(),
request_id,
Vec::new(),
);
}
// handle password change requests
Some(proto::user_accounts::Message::SetPasswordRequest(set_password_req)) => {
// get user ID from outer RPC message
let user_peer_id = match PeerId::from_bytes(&user_id) {
Ok(id) => id,
Err(_) => {
Self::send_password_response(
false,
"Invalid user Id".to_string(),
request_id,
);
return;
}
};
// attempt to set password and send response
match Self::set_password(user_peer_id, set_password_req.password) {
Ok(()) => Self::send_password_response(
true,
"Password updated successfully".to_string(),
request_id,
),
Err(error) => {
Self::send_password_response(false, error, request_id);
}
}
}
Some(proto::user_accounts::Message::UpdateProfileRequest(update_req)) => {
let user_peer_id = match PeerId::from_bytes(&user_id) {
Ok(id) => id,
Err(_) => {
Self::send_update_profile_response(false, "invalid user id".to_string(), 0, request_id);
return;
}
};
let account = match Self::get_by_id(user_peer_id) {
Some(a) => a,
None => {
Self::send_update_profile_response(false, "user account not found".to_string(), 0, request_id);
return;
}
};
let id_bytes = user_peer_id.to_bytes();
let q8id = id_bytes[6..14].to_vec();
let updated_user = match router::users::Users::get_user_snapshot(&q8id) {
Some(user) => {
let new_name = if update_req.name.is_empty() { user.name.clone() } else { update_req.name.clone() };
let new_bio = if update_req.bio.is_empty() { user.bio.clone() } else { update_req.bio.clone() };
let new_avatar = if update_req.avatar.is_empty() { user.avatar.clone() } else { update_req.avatar.clone() };
let new_version = user.version + 1;
let new_updated_at = crate::utilities::timestamp::Timestamp::get_timestamp();
router::users::User {
id: user.id,
key: user.key,
name: new_name,
verified: user.verified,
blocked: user.blocked,
bio: new_bio,
avatar: new_avatar,
version: new_version,
updated_at: new_updated_at,
signed_profile_bytes: Vec::new(),
signed_profile_signature: Vec::new(),
}
}
None => {
Self::send_update_profile_response(false, "user not found in users table".to_string(), 0, request_id);
return;
}
};
let signed = router::users::Users::create_signed_profile(&updated_user, &account.keys);
let new_version = updated_user.version;
let mut user_to_store = updated_user;
user_to_store.signed_profile_bytes = signed.profile;
user_to_store.signed_profile_signature = signed.signature;
router::users::Users::add(user_to_store);
Self::send_update_profile_response(true, String::new(), new_version, request_id);
}
_ => {}
}
}
Err(error) => {
log::error!("{:?}", error);
}
}
}
/// send update profile response to client
fn send_update_profile_response(success: bool, error_message: String, new_version: u64, request_id: String) {
let proto_message = proto::UserAccounts {
message: Some(proto::user_accounts::Message::UpdateProfileResponse(
proto::UpdateProfileResponse {
success,
error_message,
new_version,
},
)),
};
let mut buf = Vec::with_capacity(proto_message.encoded_len());
proto_message.encode(&mut buf).expect("Vec<u8> provides capacity as needed");
Rpc::send_message(
buf,
crate::rpc::proto::Modules::Useraccounts.into(),
request_id,
Vec::new(),
);
}
/// send password operation response ot client
fn send_password_response(success: bool, message: String, request_id: String) {
let proto_message = proto::UserAccounts {
message: Some(proto::user_accounts::Message::SetPasswordResponse(
proto::SetPasswordResponse {
success,
error_message: message,
},
)),
};
let mut buf = Vec::with_capacity(proto_message.encoded_len());
proto_message.encode(&mut buf).unwrap();
Rpc::send_message(
buf,
crate::rpc::proto::Modules::Useraccounts.into(),
request_id,
Vec::new(),
);
}
/// create the qaul RPC definitions of a public key
///
/// Returns a tuple with the key type & the base58 encoded
/// (key_type: String, key_base58: String)
fn get_protobuf_public_key(key: PublicKey) -> (String, String) {
// extract values
let key_type: String;
let key_base58: String;
#[allow(unreachable_patterns)]
match key.try_into_ed25519() {
Ok(ed_key) => {
key_type = "Ed25519".to_owned();
key_base58 = bs58::encode(ed_key.to_bytes()).into_string();
}
_ => {
key_type = "UNDEFINED".to_owned();
key_base58 = "UNDEFINED".to_owned();
}
}
(key_type, key_base58)
}
fn hash_password(password: Option<String>) -> (Option<String>, Option<String>) {
let (password_hash, password_salt) = match password {
Some(pwd) if !pwd.is_empty() => {
let argon2 = Argon2::default();
let salt = SaltString::generate(&mut OsRng);
match argon2.hash_password(pwd.as_bytes(), &salt) {
Ok(hash) => (Some(hash.to_string()), Some(salt.as_str().to_string())),
Err(e) => {
log::error!("Failed to hash the password: {}", e);
(None, None)
}
}
}
_ => (None, None),
};
(password_hash, password_salt)
}
}