backend: get current user
This commit is contained in:
parent
2f7e1c9924
commit
8602142210
3 changed files with 25 additions and 2 deletions
|
@ -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<Claims, Error> {
|
||||
|
|
|
@ -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<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(
|
||||
state: web::Data<AppState>,
|
||||
user: web::Json<CreateUserDto>,
|
||||
executor: AuthedUser,
|
||||
) -> actix_web::Result<impl Responder> {
|
||||
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)?;
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue