Can replace password

This commit is contained in:
2023-06-05 19:02:51 +02:00
parent 0ed24d078d
commit c99a3a319c
3 changed files with 56 additions and 3 deletions

View File

@ -6,7 +6,9 @@ use crate::constants::StaticConstraints;
use crate::controllers::HttpResult;
use crate::models::User;
use crate::services::login_token_service::LoginToken;
use crate::services::users_service;
use crate::services::rate_limiter_service::RatedAction;
use crate::services::{rate_limiter_service, users_service};
use actix_remote_ip::RemoteIP;
use actix_web::web::Json;
use actix_web::HttpResponse;
@ -32,12 +34,12 @@ pub async fn auth_info(token: LoginToken) -> HttpResult {
}
#[derive(serde::Deserialize)]
pub struct ProfileUpdate {
pub struct ProfileUpdateQuery {
name: String,
}
/// Update profile information
pub async fn update_profile(token: LoginToken, profile: Json<ProfileUpdate>) -> HttpResult {
pub async fn update_profile(token: LoginToken, profile: Json<ProfileUpdateQuery>) -> HttpResult {
if !StaticConstraints::default()
.user_name_len
.validate(&profile.name)
@ -51,3 +53,47 @@ pub async fn update_profile(token: LoginToken, profile: Json<ProfileUpdate>) ->
Ok(HttpResponse::Accepted().finish())
}
#[derive(serde::Deserialize)]
pub struct ReplacePasswordQuery {
old_password: String,
new_password: String,
}
/// Replace user password
pub async fn replace_password(
remote_ip: RemoteIP,
token: LoginToken,
q: Json<ReplacePasswordQuery>,
) -> HttpResult {
// Rate limiting
if rate_limiter_service::should_block_action(
remote_ip.0,
RatedAction::RequestReplacePasswordSignedIn,
)
.await?
{
return Ok(HttpResponse::TooManyRequests().finish());
}
if !StaticConstraints::default()
.password_len
.validate(&q.old_password)
{
return Ok(HttpResponse::BadRequest().json("Nouveau mot de passe invalide!"));
}
let user = users_service::get_by_id(token.user_id).await?;
if !user.check_password(&q.old_password) {
rate_limiter_service::record_action(
remote_ip.0,
RatedAction::RequestReplacePasswordSignedIn,
)
.await?;
return Ok(HttpResponse::BadRequest().json("Ancien mot de passe invalide !"));
}
users_service::change_password(&user, &q.new_password).await?;
Ok(HttpResponse::Accepted().finish())
}