summaryrefslogtreecommitdiff
path: root/server/src/routes/user.rs
blob: 1bb56b95d07f90f176a76f2124b8ad198733b973 (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
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(get_me))
        .route("/:id", get(get_user))
}

/// 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())),
    }
}

/// 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())),
    }
}