summaryrefslogtreecommitdiffstats
path: root/src/routes/user.rs
blob: 31366a0950eadc0513cff72890606ee9a8b4111a (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
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
use crate::{
    errors::AppError,
    files::{delete_upload, upload},
    models::{
        auth::Claims,
        user::{User, UserEdit, UserList},
    },
    pagination::{ModelPagination, Pagination, UserPagination},
};
use axum::{
    extract::{ContentLengthLimit, Multipart, Path, Query},
    routing::{delete, get, put},
    Json, Router,
};

/// Create routes for `/v1/users/` namespace
pub fn create_route() -> Router {
    Router::new()
        .route("/", get(list_users))
        .route("/me", get(get_me))
        .route("/me/avatar", put(edit_my_avatar).delete(delete_my_avatar))
        .route("/:id", get(get_user).put(edit_user))
        .route("/:id/avatar", delete(delete_avatar))
        .route("/:id/models", get(get_user_models))
}

/// List users. Checks Authorization token
async fn list_users(
    _: Claims,
    pagination: Query<Pagination>,
) -> Result<Json<UserPagination>, AppError> {
    let page = pagination.0.page.unwrap_or_default();
    let results = User::list(page).await?;
    let count = User::count().await?;

    Ok(Json(UserPagination { count, results }))
}

/// Get info about me
async fn get_me(claims: Claims) -> Result<Json<UserList>, AppError> {
    match User::find_by_id(claims.user_id).await {
        Ok(user) => Ok(Json(user)),
        Err(_) => Err(AppError::NotFound("User not found".to_string())),
    }
}

/// Edit the avatar of the user linked to the claims
async fn edit_my_avatar(
    claims: Claims,
    ContentLengthLimit(multipart): ContentLengthLimit<Multipart, { 1024 * 1024 * 5 }>,
) -> Result<Json<UserList>, AppError> {
    let mut user = match User::find_by_id(claims.user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    if user.avatar.is_some() {
        let avatar_url = user.avatar.as_ref().unwrap();
        delete_upload(avatar_url)?;
    }

    match upload(
        multipart,
        vec!["jpg", "jpeg", "png", "webp"],
        Some(format!("avatar-{}", user.id)),
    )
    .await
    {
        Ok(saved_file) => {
            user.edit_avatar(Some(saved_file)).await?;

            Ok(Json(user))
        }
        Err(e) => Err(e),
    }
}

/// A staffer can delete an user `id`'s avatar
async fn delete_avatar(
    Path(user_id): Path<i32>,
    claims: Claims,
) -> Result<Json<UserList>, AppError> {
    let mut user = match User::find_by_id(user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    // If the user of the access token is different than the user they want to edit, checks if the
    // first user is an admin
    if claims.user_id != user.id {
        match User::find_by_id(claims.user_id).await {
            Ok(user) => {
                if !(user.is_staff.unwrap()) {
                    return Err(AppError::Unauthorized);
                }
            }
            Err(_) => {
                return Err(AppError::NotFound("User not found".to_string()));
            }
        };
    }

    if user.avatar.is_some() {
        let avatar_url = user.avatar.as_ref().unwrap();
        delete_upload(avatar_url)?;
    }

    user.edit_avatar(None).await?;

    Ok(Json(user))
}

/// Delete the avatar of the user linked to the claims
async fn delete_my_avatar(claims: Claims) -> Result<Json<UserList>, AppError> {
    let mut user = match User::find_by_id(claims.user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    if user.avatar.is_some() {
        let avatar_url = user.avatar.as_ref().unwrap();
        delete_upload(avatar_url)?;
    }

    user.edit_avatar(None).await?;

    Ok(Json(user))
}

/// Get an user with id = `user_id`
async fn get_user(Path(user_id): Path<i32>) -> Result<Json<UserList>, AppError> {
    match User::find_by_id(user_id).await {
        Ok(user) => Ok(Json(user)),
        Err(_) => Err(AppError::NotFound("User not found".to_string())),
    }
}

/// Edit an user with id = `user_id`. Only staffers and owner of that account can perform this
/// action.
/// Only staffers can update the user `is_staff` value
async fn edit_user(
    Path(user_id): Path<i32>,
    Json(mut payload): Json<UserEdit>,
    claims: Claims,
) -> Result<Json<UserList>, AppError> {
    let mut user = match User::find_by_id(user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    let claimed = match User::find_by_id(claims.user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    if user.id != claimed.id {
        if !(claimed.is_staff.unwrap()) {
            return Err(AppError::Unauthorized);
        }
    }

    if !claimed.is_staff.unwrap() && user.is_staff != payload.is_staff {
        payload.is_staff = user.is_staff;
    }

    if user.email != payload.email && User::email_has_taken(&payload.email).await? {
        return Err(AppError::BadRequest(
            "An user with this email already exists".to_string(),
        ));
    }

    if user.username != payload.username && User::username_has_taken(&payload.username).await? {
        return Err(AppError::BadRequest(
            "An user with this username already exists".to_string(),
        ));
    }

    user.edit(payload).await?;

    Ok(Json(user))
}

/// Get user models list
async fn get_user_models(
    Path(user_id): Path<i32>,
    pagination: Query<Pagination>,
) -> Result<Json<ModelPagination>, AppError> {
    let user = match User::find_by_id(user_id).await {
        Ok(user) => user,
        Err(_) => {
            return Err(AppError::NotFound("User not found".to_string()));
        }
    };

    let page = pagination.0.page.unwrap_or_default();
    let results = user.get_models(page).await?;
    let count = user.count_models().await?;

    Ok(Json(ModelPagination { count, results }))
}