b3-users 0.1.4

A simple user management system for the Internet Computer
Documentation
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
// user.rs
use super::account::{UserAccountArgs, UserAccountData};
use crate::error::UserStateError;

use candid::Principal;
use ic_cdk::export::{candid::CandidType, serde::Deserialize};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

#[derive(Debug, CandidType, Deserialize, Default, Clone)]
pub struct UserData {
    password: Option<u64>,
    profile: UserProfile,
    pub name: String,
    pub email: String,
    pub balance: u128,
    pub accounts: Vec<UserAccountData>,
    pub settings: HashMap<String, UserDataSettingValue>,
}

#[derive(Debug, CandidType, Deserialize, Default, Clone)]
pub struct UserProfile {
    pub full_name: Option<String>,
    pub address: Option<String>,
    pub phone_number: Option<String>,
    pub attributes: HashMap<String, String>,
}

impl UserData {
    // New values for the user data.
    pub fn new(user_args: UserDataArgs, account_args: UserAccountArgs) -> Self {
        let mut user_data = UserData::default();

        user_data.update(user_args);

        user_data.accounts = Vec::with_capacity(256);

        let name = if let Some(name) = account_args.name {
            name
        } else {
            "Account 0".to_string()
        };

        user_data
            .accounts
            .insert(0, UserAccountData::new(account_args.public_key, name));

        user_data
    }

    /// Updates the user's data based on the provided UserDataArgs struct.
    /// Only updates fields that are set to Some(value) in the options.
    pub fn update(&mut self, args: UserDataArgs) -> UserDataArgs {
        if let Some(name) = args.name {
            self.name = name;
        }

        if let Some(email) = args.email {
            self.email = email;
        }

        if let Some(balance) = args.balance {
            self.balance = balance;
        }

        if let Some(settings) = args.settings {
            for (key, value) in settings {
                self.settings.insert(key, value);
            }
        }

        if let Some(profile) = args.profile {
            self.update_profile(profile);
        }

        if let Some(password) = args.password {
            self.password = Some(hash_password(&password));
        }

        UserDataArgs {
            name: Some(self.name.clone()),
            email: Some(self.email.clone()),
            balance: Some(self.balance),
            settings: Some(self.settings.clone()),
            profile: Some(UserProfileArgs {
                full_name: self.profile.full_name.clone(),
                address: self.profile.address.clone(),
                phone_number: self.profile.phone_number.clone(),
                attributes: Some(self.profile.attributes.clone()),
            }),
            password: None,
        }
    }

    /// Update the user's profile.
    /// Only updates fields that are set to Some(value) in the options.
    /// Returns the updated profile.
    pub fn update_profile(&mut self, args: UserProfileArgs) -> UserProfileArgs {
        if let Some(full_name) = args.full_name {
            self.profile.full_name = Some(full_name);
        }

        if let Some(account) = args.address {
            self.profile.address = Some(account);
        }

        if let Some(phone_number) = args.phone_number {
            self.profile.phone_number = Some(phone_number);
        }

        if let Some(attributes) = args.attributes {
            for (key, value) in attributes {
                self.profile.attributes.insert(key, value);
            }
        }

        UserProfileArgs {
            full_name: self.profile.full_name.clone(),
            address: self.profile.address.clone(),
            phone_number: self.profile.phone_number.clone(),
            attributes: Some(self.profile.attributes.clone()),
        }
    }

    /// Adds a new account for the user with the given key and account data.
    /// Returns an error if the key already exists.
    pub fn create_account(
        &mut self,
        args: UserAccountArgs,
    ) -> Result<UserAccountData, UserStateError> {
        let key = self.get_new_key()?;

        let public_key = args.public_key;

        let name = if let Some(name) = args.name {
            name
        } else {
            format!("Account {}", key)
        };

        let account_data = UserAccountData::new(public_key, name);

        self.accounts.insert(key, account_data.clone());

        Ok(account_data)
    }

    /// New Key to add to derivation path based on the number of accounts created.
    /// Returns the new key.
    pub fn get_new_key(&self) -> Result<usize, UserStateError> {
        if self.accounts.len() > 255 {
            return Err(UserStateError::AccountLimitReached);
        }

        let key = self.accounts.len();

        Ok(key)
    }

    /// Get Derivation Path for the given key.
    /// Returns the derivation path.
    pub fn get_derivation_path(
        &self,
        principal: Principal,
        key: u8,
    ) -> Result<Vec<u8>, UserStateError> {
        if key as usize > self.accounts.len() {
            return Err(UserStateError::InvalidAccountKey);
        }

        let mut derivation_path = principal.as_slice().to_vec();

        derivation_path.push(key);

        Ok(derivation_path)
    }

    /// Checks if the key is valid for the user.
    /// Returns an error if the key is invalid.
    pub fn get_key_is_valid(&self, key: usize) -> Result<(), UserStateError> {
        if key >= self.accounts.len() {
            return Err(UserStateError::InvalidAccountKey);
        }

        Ok(())
    }

    /// Retrieves an account by key for the user.
    /// Returns the account data if the key is found, or error if the key was not found.
    pub fn get_account(&self, key: usize) -> Result<UserAccountData, UserStateError> {
        self.get_key_is_valid(key)?;

        Ok(self.accounts[key].clone())
    }

    /// Retrieves a mutable reference to the account by key for the user.
    /// Returns the account data if the key is found, or error if the key was not found.
    pub fn get_account_mut(&mut self, key: usize) -> Result<&mut UserAccountData, UserStateError> {
        self.get_key_is_valid(key)?;

        Ok(&mut self.accounts[key])
    }

    /// Retrieves all the accounts created by the user.
    /// Returns a Vec of UserAccountData objects.
    pub fn get_accounts(&self) -> &Vec<UserAccountData> {
        &self.accounts
    }

    /// Sets the password for the user.
    pub fn set_password(&mut self, password: &str) -> Result<(), UserStateError> {
        let hashed_password = hash_password(password);

        self.password = Some(hashed_password);

        Ok(())
    }

    /// Checks if the provided password matches the user's password.
    pub fn check_password(&self, password: &str) -> Result<bool, UserStateError> {
        let input_hash = hash_password(password);

        if let Some(password_hash) = self.password {
            Ok(input_hash == password_hash)
        } else {
            Err(UserStateError::PasswordNotSet)
        }
    }

    /// Retrieves the user's setting.
    /// Returns the value if the key is found, or None if the key was not found.
    pub fn get_setting(&self, key: &str) -> Result<UserDataSettingValue, UserStateError> {
        if let Some(value) = self.settings.get(key) {
            Ok(value.clone())
        } else {
            Err(UserStateError::SettingNotFound)
        }
    }

    /// Retrieves a mutable reference to the user's setting.
    /// Returns the value if the key is found, or None if the key was not found.
    pub fn get_setting_mut(
        &mut self,
        key: &str,
    ) -> Result<&mut UserDataSettingValue, UserStateError> {
        if let Some(value) = self.settings.get_mut(key) {
            Ok(value)
        } else {
            Err(UserStateError::SettingNotFound)
        }
    }

    /// Retrieves a setting value by key for the user.
    /// Returns the value if the key is found, or None if the key was not found.
    pub fn get_settings(&self) -> &HashMap<String, UserDataSettingValue> {
        &self.settings
    }

    /// Sets a setting key-value pair for the user.
    pub fn set_setting(&mut self, key: String, value: UserDataSettingValue) -> () {
        let value = value.into();
        self.settings.insert(key, value);
    }

    /// Removes a setting key for the user.
    /// Returns the removed value if it existed, or None if the key was not found.
    pub fn remove_setting(&mut self, key: &str) -> Result<bool, UserStateError> {
        if self.settings.remove(key).is_some() {
            Ok(true)
        } else {
            Err(UserStateError::SettingNotFound)
        }
    }

    /// Updates all the settings for the user with the new settings.
    pub fn update_settings(&mut self, new_settings: HashMap<String, UserDataSettingValue>) {
        self.settings = new_settings;
    }
}

fn hash_password(password: &str) -> u64 {
    let mut hasher = DefaultHasher::new();
    password.hash(&mut hasher);

    hasher.finish()
}

#[derive(CandidType, Deserialize, Default, Debug, Clone, PartialEq)]
pub struct UserDataArgs {
    pub name: Option<String>,
    pub email: Option<String>,
    pub balance: Option<u128>,
    pub password: Option<String>,
    pub profile: Option<UserProfileArgs>,
    pub settings: Option<HashMap<String, UserDataSettingValue>>,
}

#[derive(Debug, CandidType, Clone, Default, Deserialize, PartialEq)]
pub struct UserProfileArgs {
    pub full_name: Option<String>,
    pub address: Option<String>,
    pub phone_number: Option<String>,
    pub attributes: Option<HashMap<String, String>>,
}

#[derive(Debug, CandidType, Deserialize, Clone, PartialEq)]
pub enum UserDataSettingValue {
    StringValue(String),
    NumberValue(u128),
    FloatValue(f64),
    BoolValue(bool),
}

impl From<String> for UserDataSettingValue {
    fn from(value: String) -> Self {
        UserDataSettingValue::StringValue(value)
    }
}

impl From<f64> for UserDataSettingValue {
    fn from(value: f64) -> Self {
        UserDataSettingValue::FloatValue(value)
    }
}

impl From<u128> for UserDataSettingValue {
    fn from(value: u128) -> Self {
        UserDataSettingValue::NumberValue(value)
    }
}

impl From<bool> for UserDataSettingValue {
    fn from(value: bool) -> Self {
        UserDataSettingValue::BoolValue(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {

        #[test]
        fn test_user_data_arbitrary( user_args: UserDataArgs,account_args: UserAccountArgs) {
            let user_data = UserData::new(user_args.clone(), account_args);

            assert_eq!(user_data.name, user_args.name.unwrap_or_default());
            assert_eq!(user_data.email, user_args.email.unwrap_or_default());
            assert_eq!(user_data.balance, user_args.balance.unwrap_or_default());
        }

        #[test]
        fn test_create_account(account_args: UserAccountArgs, account_args2: UserAccountArgs, profile: UserProfileArgs) {
            let args = UserDataArgs {
                name: Some("test".to_string()),
                email: Some("test@example.com".to_string()),
                balance: Some(0),
                password: Some("password".to_string()),
                profile: Some(profile),
                settings: None,
            };

            let mut user_data = UserData::new(args, account_args);

            let account_data = user_data.create_account(account_args2.clone()).unwrap();

            assert_eq!(account_data.public_key, account_args2.public_key);
        }

        #[test]
        fn test_get_account(user_args: UserDataArgs, account_args: UserAccountArgs, name: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            let account_data = user_data.get_account(0).unwrap();

            assert_eq!(account_data.public_key, account_args.public_key);

            let mut account_data2 = user_data.get_account_mut(0).unwrap();

            account_data2.name = name.clone();

            assert_eq!(user_data.get_account(0).unwrap().name, name);
        }

        #[test]
        fn test_update_account(user_args: UserDataArgs, account_args: UserAccountArgs, name: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            let mut account_data = user_data.get_account_mut(0).unwrap();

            account_data.name = name.clone();

            assert_eq!(user_data.get_account(0).unwrap().name, name);
        }

        #[test]
        fn test_update_settings(user_args: UserDataArgs, account_args: UserAccountArgs, name: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            let mut settings = HashMap::new();
            settings.insert("name".to_string(), name.clone().into());

            user_data.update_settings(settings);

            assert_eq!(user_data.settings.get("name").unwrap(), &name.into());
        }

        #[test]
        fn test_update_password(user_args: UserDataArgs, account_args: UserAccountArgs, password: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            user_data.set_password(&password.clone()).unwrap();


            assert!(user_data.check_password(&password).unwrap());
        }

        #[test]
        fn test_update_email(user_args: UserDataArgs, account_args: UserAccountArgs, email: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            user_data.email = email.clone();

            assert_eq!(user_data.email, email);
        }

        #[test]
        fn test_update_name(user_args: UserDataArgs, account_args: UserAccountArgs, name: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            user_data.name = name.clone();

            assert_eq!(user_data.name, name);
        }

        #[test]
        fn test_update_balance(user_args: UserDataArgs, account_args: UserAccountArgs, balance: u128) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            user_data.balance = balance;

            assert_eq!(user_data.balance, balance);
        }

        #[test]
        fn test_update_profile(user_args: UserDataArgs, account_args: UserAccountArgs, name: String) {
            let mut user_data = UserData::new(user_args, account_args.clone());

            let mut profile = UserProfileArgs::default();
            profile.full_name = Some(name.clone());
            profile.address = Some("account".to_string());

            user_data.update_profile(profile);

            assert_eq!(user_data.profile.full_name.unwrap(), name);
        }

        #[test]
        fn test_update_profile_attributes(user_args: UserDataArgs, account_args: UserAccountArgs, key: String, value: String) {
            let mut user_data = UserData::new(user_args, account_args);

            let mut profile = UserProfileArgs::default();

            let mut attributes = HashMap::new();

            attributes.insert(key.clone(), value.clone());

            profile.attributes = Some(attributes);

            user_data.update_profile(profile);

            assert_eq!(user_data.profile.attributes.get(&key).unwrap(), &value);
        }
    }
}