summaryrefslogtreecommitdiff
path: root/server/src/routes/user.rs
blob: d5a09e26944da5857f1f5ab1df6a5616254ed773 (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
use crate::errors::AppError;
use crate::models::{
    auth::Claims,
    user::{User, UserList},
};
use axum::{extract::Path, routing::get, Json, Router};

/// Create routes for `/v1/users/` namespace
pub fn create_route() -> Router {
    Router::new()
        .route("/", get(list_users))
        .route("/:id", get(get_user))
}

/// List users. Checks Authorization token
async fn list_users(_: Claims) -> Result<Json<Vec<UserList>>, AppError> {
    let users = User::list().await?;

    Ok(Json(users))
}

/// Search an user by `user_id`. It works only if the user passed by `Authorization` token is the
/// same of the url or a staffer.
async fn get_user(Path(user_id): Path<i32>, claims: Claims) -> Result<Json<UserList>, AppError> {
    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);
        }
    }

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