backend: get current user

This commit is contained in:
Sphereso 2024-07-11 22:59:42 +02:00
parent 2f7e1c9924
commit 8602142210
3 changed files with 25 additions and 2 deletions

View file

@ -33,7 +33,7 @@ pub fn create_jwt(
jsonwebtoken::encode(&Header::default(), &claims, key) jsonwebtoken::encode(&Header::default(), &claims, key)
} }
pub struct AuthedUser(entity::user::Model); pub struct AuthedUser(pub entity::user::Model);
impl AuthedUser { impl AuthedUser {
fn parse_token(req: &HttpRequest) -> Result<Claims, Error> { fn parse_token(req: &HttpRequest) -> Result<Claims, Error> {

View file

@ -1,4 +1,7 @@
use actix_web::{error::ErrorInternalServerError, web, Responder}; use actix_web::{
error::{ErrorInternalServerError, ErrorNotFound, ErrorUnauthorized},
web, Responder,
};
use argon2::{ use argon2::{
password_hash::{rand_core::OsRng, PasswordHasher, SaltString}, password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
Argon2, Argon2,
@ -23,6 +26,7 @@ pub struct CreateUserDto {
name: String, name: String,
email: String, email: String,
password: String, password: String,
admin: bool,
} }
impl From<entity::user::Model> for UserWithoutPassword { impl From<entity::user::Model> for UserWithoutPassword {
@ -53,10 +57,27 @@ impl UserController {
)) ))
} }
pub async fn get_current_user(
state: web::Data<AppState>,
executor: AuthedUser,
) -> actix_web::Result<impl Responder> {
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( pub async fn create_user(
state: web::Data<AppState>, state: web::Data<AppState>,
user: web::Json<CreateUserDto>, user: web::Json<CreateUserDto>,
executor: AuthedUser,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
if !executor.0.admin {
return Err(ErrorUnauthorized("Invalid Permissions"));
}
let db = &state.db; let db = &state.db;
let user = user.into_inner(); let user = user.into_inner();
@ -72,6 +93,7 @@ impl UserController {
name: ActiveValue::Set(user.name), name: ActiveValue::Set(user.name),
email: ActiveValue::Set(user.email), email: ActiveValue::Set(user.email),
hash: ActiveValue::Set(password_hash.to_string()), hash: ActiveValue::Set(password_hash.to_string()),
admin: ActiveValue::Set(user.admin),
}; };
let result = user.insert(db).await.map_err(ErrorInternalServerError)?; let result = user.insert(db).await.map_err(ErrorInternalServerError)?;

View file

@ -10,6 +10,7 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.post(UserController::create_user), .post(UserController::create_user),
) )
.service(web::resource("/users/{user_id}")) .service(web::resource("/users/{user_id}"))
.route("/users/me", web::get().to(UserController::get_current_user))
.service( .service(
web::resource("/licenses") web::resource("/licenses")
.get(LicenseController::list_groups) .get(LicenseController::list_groups)