DEVELOPMENT ENVIRONMENT

~liljamo/ulairi

ref: e78be1f39347874c13c8ff1c08025ec375b5e928 ulairi/ulairi-api/src/users/model.rs -rw-r--r-- 3.3 KiB
e78be1f3Jonni Liljamo I lost the old commit history... 1 year, 11 months ago
                                                                                
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
use crate::schema::users;

use diesel;
use diesel::pg::PgConnection;
use diesel::prelude::*;

use serde::{Deserialize, Serialize};

use argon2::{
    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Argon2,
};

#[derive(Serialize, Deserialize, Queryable, AsChangeset)]
#[table_name = "users"]
pub struct User {
    pub id: i32,
    pub username: String,
    pub email: String,
    pub password: String,
}

#[derive(Serialize, Deserialize, Insertable)]
#[table_name = "users"]
pub struct InsertableUser {
    pub username: String,
    pub email: String,
    pub password: String,
}

impl User {
    pub fn create(user: InsertableUser, connection: &PgConnection) -> QueryResult<User> {
        // Generate a salt
        let salt = SaltString::generate(&mut OsRng);

        // Hash the password to PHC string
        let password_hash = Argon2::default()
            .hash_password(user.password.as_bytes(), &salt)
            .unwrap()
            .to_string();

        let encrypted_user = InsertableUser {
            password: password_hash,
            ..user
        };

        // Insert the user into the database
        diesel::insert_into(users::table)
            .values(encrypted_user)
            .execute(connection)?;

        // Query the database for the encrypted user
        users::table.order(users::id.desc()).first(connection)
    }

    pub fn get_by_username_and_password(
        username: String,
        password: String,
        connection: &PgConnection,
    ) -> Option<User> {
        // Query the database for the user
        let res = users::table
            .filter(users::username.eq(username))
            .get_result::<User>(connection);

        // Check if the user exists
        match res {
            Ok(user) => {
                let parsed_hash = PasswordHash::new(&user.password).unwrap();

                // Check if the password is correct
                if Argon2::default()
                    .verify_password(password.as_bytes(), &parsed_hash)
                    .is_ok()
                {
                    Some(user)
                } else {
                    None
                }
            }
            Err(_) => None,
        }
    }

    pub fn get_by_email(email: String, connection: &PgConnection) -> Option<User> {
        // Query the database for the user
        let res = users::table
            .filter(users::email.eq(email))
            .get_result::<User>(connection);

        // Check if the user exists
        match res {
            Ok(user) => Some(user),
            Err(_) => None,
        }
    }

    pub fn email_is_taken(email: String, connection: &PgConnection) -> bool {
        // Query the database for the user
        let res = users::table
            .filter(users::email.eq(email))
            .get_result::<User>(connection);

        // Check if the user exists
        match res {
            Ok(_) => true,
            Err(_) => false,
        }
    }

    pub fn username_is_taken(username: String, connection: &PgConnection) -> bool {
        // Query the database for the user
        let res = users::table
            .filter(users::username.eq(username))
            .get_result::<User>(connection);

        // Check if the user exists
        match res {
            Ok(_) => true,
            Err(_) => false,
        }
    }
}