summaryrefslogtreecommitdiff
path: root/server/src/models/user.rs
blob: 356b9a213eeab54f6edd4eaad5a07ef91f2469cd (plain)
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
use crate::db::get_client;
use crate::errors::AppError;

use serde::{Deserialize, Serialize};
use sqlx::Row;
use validator::Validate;

/// User model
#[derive(Deserialize, Serialize, Validate, sqlx::FromRow)]
pub struct User {
    id: i32,
    name: String,
    #[validate(length(min = 4, message = "Can not be empty"))]
    email: String,
    #[validate(length(min = 2, message = "Can not be empty"))]
    username: String,
    #[validate(length(min = 8, message = "Must be min 8 chars length"))]
    password: String,
    is_staff: Option<bool>,
    avatar: Option<String>,
}

/// Response used to print a user (or a users list)
#[derive(Deserialize, Serialize, Validate, sqlx::FromRow)]
pub struct UserList {
    // It is public because it used by `Claims` creation
    pub id: i32,
    pub name: String,
    #[validate(length(min = 4, message = "Can not be empty"))]
    pub email: String,
    #[validate(length(min = 2, message = "Can not be empty"))]
    pub username: String,
    pub is_staff: Option<bool>,
    pub avatar: Option<String>,
}

impl User {
    /// By default an user has id = 0. It is not created yet
    pub fn new(name: String, email: String, username: String, password: String) -> Self {
        Self {
            id: 0,
            name,
            email,
            username,
            password,
            is_staff: Some(false),
            avatar: None,
        }
    }

    /// Create a new user from the model using a SHA256 crypted password
    pub async fn create(user: User) -> Result<UserList, AppError> {
        let pool = unsafe { get_client() };

        user.validate()
            .map_err(|error| AppError::BadRequest(error.to_string()))?;

        let crypted_password = sha256::digest(user.password);

        let rec: UserList = sqlx::query_as(
            r#"
                INSERT INTO users (name, email, username, password)
                VALUES ( $1, $2, $3, $4)
                RETURNING id, name, email, username, is_staff, avatar
            "#,
        )
        .bind(user.name)
        .bind(user.email)
        .bind(user.username)
        .bind(crypted_password)
        .fetch_one(pool)
        .await?;

        Ok(rec)
    }

    /// Find a user using the model. It used for login
    pub async fn find(user: User) -> Result<UserList, AppError> {
        let pool = unsafe { get_client() };

        let crypted_password = sha256::digest(user.password);

        let rec: UserList = sqlx::query_as(
            r#"
                SELECT id, name, email, username, is_staff, avatar FROM "users"
                WHERE username = $1 AND password = $2
            "#,
        )
        .bind(user.username)
        .bind(crypted_password)
        .fetch_one(pool)
        .await?;

        Ok(rec)
    }

    /// Returns the user with id = `user_id`
    pub async fn find_by_id(user_id: i32) -> Result<UserList, AppError> {
        let pool = unsafe { get_client() };

        let rec: UserList = sqlx::query_as(
            r#"
                SELECT id, name, email, username, is_staff, avatar FROM "users"
                WHERE id = $1
            "#,
        )
        .bind(user_id)
        .fetch_one(pool)
        .await?;

        Ok(rec)
    }

    /// List all users
    pub async fn list() -> Result<Vec<UserList>, AppError> {
        let pool = unsafe { get_client() };
        let rows: Vec<UserList> = sqlx::query_as(
            r#"SELECT id, name, email, username, is_staff, avatar FROM users
            ORDER BY id DESC
            LIMIT $1 OFFSET $2
            "#,
        )
        .fetch_all(pool)
        .await?;

        Ok(rows)
    }

    /// Prevent the "uniquess" Postgres fields check. Check if username has been taken
    pub async fn username_has_taken(username: &String) -> Result<bool, AppError> {
        let pool = unsafe { get_client() };
        let cursor = sqlx::query(
            r#"
                SELECT COUNT(id) as count FROM users WHERE username = $1
            "#,
        )
        .bind(username)
        .fetch_one(pool)
        .await?;

        let count: i64 = cursor.try_get(0).unwrap();

        Ok(count > 0)
    }

    /// Prevent the "uniquess" Postgres fields check. Check if email has been taken
    pub async fn email_has_taken(email: &String) -> Result<bool, AppError> {
        let pool = unsafe { get_client() };
        let cursor = sqlx::query(
            r#"
                SELECT COUNT(id) as count FROM users WHERE email = $1
            "#,
        )
        .bind(email)
        .fetch_one(pool)
        .await?;

        let count: i64 = cursor.try_get(0).unwrap();

        Ok(count > 0)
    }
}