Skip to content

Commit

Permalink
fix: validate current password before change to the new password (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lzyct authored Aug 21, 2024
1 parent f67cfff commit 88c10f7
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions src/features/auth/data/repository/auth_repository_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,25 +131,28 @@ impl AuthRepositoryImpl for AuthRepository {
}

fn update_password(&self, user: Uuid, params: UpdatePasswordParams) -> AppResult<()> {
users::table
.filter(user_id.eq(user))
.get_result::<User>(&mut self.source.get().unwrap())
.map(|user| {
let old_password_param = &params.old_password.unwrap_or("".to_string());
let new_password_param = &params.new_password.unwrap_or("".to_string());

if !&old_password_param.is_empty()
&& verify(old_password_param, &user.password).unwrap()
{
let new_password = bcrypt::hash(new_password_param, DEFAULT_COST).unwrap();
diesel::update(users::table)
.filter(user_id.eq(&user.id))
.set(password.eq(&new_password))
.execute(&mut self.source.get().unwrap())
.expect("Error updating user password");
}
let user = users::table
.filter(user_id.eq(user))
.get_result::<User>(&mut self.source.get().unwrap())
.map_err(|_| APIError::UserNotFoundError)?;

let current_password = &params.old_password.unwrap_or("".to_string());
let new_password_param = &params.new_password.unwrap_or("".to_string());

// validate current password
if !verify(current_password, &user.password).unwrap() {
return Err(APIError::BadRequest {
message: "Invalid current password".to_string(),
})
.map_err(|_| APIError::InternalError)
}

let new_password = bcrypt::hash(new_password_param, DEFAULT_COST).unwrap();
diesel::update(users::table)
.filter(user_id.eq(&user.id))
.set(password.eq(&new_password))
.execute(&mut self.source.get().unwrap())
.expect("Error updating user password");
Ok(())
}

fn verify_token(&self, params: &TokenData<AuthToken>) -> AppResult<Uuid> {
Expand Down

0 comments on commit 88c10f7

Please sign in to comment.