summaryrefslogtreecommitdiff
path: root/server/src
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-12-01 10:18:51 +0100
committerSanto Cariotti <santo@dcariotti.me>2022-12-01 10:18:51 +0100
commit4371ba5f0916147e8d60237d1e2fbb6a1fdf834a (patch)
treeba78ed9d1b7724c5d4587ba0987a74b7a58af5fb /server/src
parent1177bd52c49789f2b38d9cb961fb87fbc0f1f844 (diff)
Replace /me endpoint with /:id
Diffstat (limited to 'server/src')
-rw-r--r--server/src/errors.rs6
-rw-r--r--server/src/routes/user.rs24
2 files changed, 25 insertions, 5 deletions
diff --git a/server/src/errors.rs b/server/src/errors.rs
index 72eb837..10c8f32 100644
--- a/server/src/errors.rs
+++ b/server/src/errors.rs
@@ -17,6 +17,8 @@ pub enum AppError {
TokenCreation,
/// Raised when a passed token is not valid
InvalidToken,
+ /// Raised if an user wants to do something can't do
+ Unauthorized,
}
/// Use `AppError` as response for an endpoint
@@ -39,6 +41,10 @@ impl IntoResponse for AppError {
"Token creation error".to_string(),
),
AppError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token".to_string()),
+ AppError::Unauthorized => (
+ StatusCode::UNAUTHORIZED,
+ "Can't perform this action".to_string(),
+ ),
};
let body = Json(json!({
diff --git a/server/src/routes/user.rs b/server/src/routes/user.rs
index d0aa056..d5a09e2 100644
--- a/server/src/routes/user.rs
+++ b/server/src/routes/user.rs
@@ -3,13 +3,13 @@ use crate::models::{
auth::Claims,
user::{User, UserList},
};
-use axum::{routing::get, Json, Router};
+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("/me", get(get_user))
+ .route("/:id", get(get_user))
}
/// List users. Checks Authorization token
@@ -19,9 +19,23 @@ async fn list_users(_: Claims) -> Result<Json<Vec<UserList>>, AppError> {
Ok(Json(users))
}
-/// Get the user from the `Authorization` header token
-async fn get_user(claims: Claims) -> Result<Json<UserList>, AppError> {
- match User::find_by_id(claims.user_id).await {
+/// 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())),
}