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, 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, claims: Claims) -> Result, 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())), } }