GeneIT/geneit_backend/src/controllers/user_controller.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

2023-05-31 13:52:49 +00:00
//! # User controller
//!
//! The actions of the user on his account when he is authenticated.
2023-06-05 16:52:00 +00:00
use crate::constants::StaticConstraints;
2023-05-31 13:52:49 +00:00
use crate::controllers::HttpResult;
use crate::models::User;
2023-05-31 13:52:49 +00:00
use crate::services::login_token_service::LoginToken;
use crate::services::users_service;
2023-06-05 16:52:00 +00:00
use actix_web::web::Json;
2023-05-31 13:52:49 +00:00
use actix_web::HttpResponse;
#[derive(serde::Serialize)]
struct UserAPI<'a> {
#[serde(flatten)]
user: &'a User,
has_password: bool,
}
2023-05-31 13:52:49 +00:00
/// Get account information
pub async fn auth_info(token: LoginToken) -> HttpResult {
let user = users_service::get_by_id(token.user_id).await?;
Ok(HttpResponse::Ok().json(UserAPI {
user: &user,
has_password: user
.password
.as_deref()
.map(|p| !p.is_empty())
.unwrap_or_default(),
}))
2023-05-31 13:52:49 +00:00
}
2023-06-05 16:52:00 +00:00
#[derive(serde::Deserialize)]
pub struct ProfileUpdate {
name: String,
}
/// Update profile information
pub async fn update_profile(token: LoginToken, profile: Json<ProfileUpdate>) -> HttpResult {
if !StaticConstraints::default()
.user_name_len
.validate(&profile.name)
{
return Ok(HttpResponse::BadRequest().json("Nom invalide!"));
}
let mut user = users_service::get_by_id(token.user_id).await?;
user.name = profile.0.name;
users_service::update_account(user).await?;
Ok(HttpResponse::Accepted().finish())
}