diff --git a/crates/backend/src/auth.rs b/crates/backend/src/auth.rs index bfea0c4..76715f1 100644 --- a/crates/backend/src/auth.rs +++ b/crates/backend/src/auth.rs @@ -33,7 +33,7 @@ pub fn create_jwt( jsonwebtoken::encode(&Header::default(), &claims, key) } -pub struct AuthedUser(entity::user::Model); +pub struct AuthedUser(pub entity::user::Model); impl AuthedUser { fn parse_token(req: &HttpRequest) -> Result { diff --git a/crates/backend/src/controller/user.rs b/crates/backend/src/controller/user.rs index 61c5279..e8b8657 100644 --- a/crates/backend/src/controller/user.rs +++ b/crates/backend/src/controller/user.rs @@ -1,4 +1,7 @@ -use actix_web::{error::ErrorInternalServerError, web, Responder}; +use actix_web::{ + error::{ErrorInternalServerError, ErrorNotFound, ErrorUnauthorized}, + web, Responder, +}; use argon2::{ password_hash::{rand_core::OsRng, PasswordHasher, SaltString}, Argon2, @@ -23,6 +26,7 @@ pub struct CreateUserDto { name: String, email: String, password: String, + admin: bool, } impl From for UserWithoutPassword { @@ -53,10 +57,27 @@ impl UserController { )) } + pub async fn get_current_user( + state: web::Data, + executor: AuthedUser, + ) -> actix_web::Result { + let db = &state.db; + let user = entity::prelude::User::find_by_id(executor.0.id) + .one(db) + .await + .map_err(ErrorInternalServerError)? + .ok_or(ErrorNotFound("Not Found"))?; + Ok(web::Json(user)) + } + pub async fn create_user( state: web::Data, user: web::Json, + executor: AuthedUser, ) -> actix_web::Result { + if !executor.0.admin { + return Err(ErrorUnauthorized("Invalid Permissions")); + } let db = &state.db; let user = user.into_inner(); @@ -72,6 +93,7 @@ impl UserController { name: ActiveValue::Set(user.name), email: ActiveValue::Set(user.email), hash: ActiveValue::Set(password_hash.to_string()), + admin: ActiveValue::Set(user.admin), }; let result = user.insert(db).await.map_err(ErrorInternalServerError)?; diff --git a/crates/backend/src/routes.rs b/crates/backend/src/routes.rs index d5a5b4f..be1850b 100644 --- a/crates/backend/src/routes.rs +++ b/crates/backend/src/routes.rs @@ -10,6 +10,7 @@ pub fn config(cfg: &mut web::ServiceConfig) { .post(UserController::create_user), ) .service(web::resource("/users/{user_id}")) + .route("/users/me", web::get().to(UserController::get_current_user)) .service( web::resource("/licenses") .get(LicenseController::list_groups)