File size: 1,024 Bytes
b7fdfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use argon2::{
    Argon2, PasswordHasher,
    password_hash::{SaltString, rand_core::OsRng},
};
use serde::Deserialize;
use sqlx::prelude::FromRow;

#[derive(Deserialize)]
pub struct UserRequest {
    username: String,
    password: String,
}

#[derive(FromRow, Deserialize)]
pub struct UserSql {
    id: i32,
    username: String,
    password: String,
}

trait Checked {
    fn username(&self) -> &String;
    fn password(&self) -> &String;

    fn is_null(&self) -> bool {
        self.username().trim() == "" || self.password().trim() == ""
    }

    fn hash_password(&self) -> String {
        let salt = SaltString::generate(&mut OsRng);
        let argon2 = Argon2::default();
        let hashed_password = argon2
            .hash_password(self.password().as_bytes(), &salt)
            .unwrap()
            .to_string();
        hashed_password
    }
}

impl Checked for UserSql {
    fn username(&self) -> &String {
        &self.username
    }
    fn password(&self) -> &String {
        &self.password
    }
}