]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/change_password.rs
ffe452c92c71436afed8cfd6719016726f2e663c
[lemmy.git] / crates / api / src / local_user / change_password.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use bcrypt::verify;
4 use lemmy_api_common::{
5   context::LemmyContext,
6   person::{ChangePassword, LoginResponse},
7   utils::{local_user_view_from_jwt, password_length_check},
8 };
9 use lemmy_db_schema::source::local_user::LocalUser;
10 use lemmy_utils::{
11   claims::Claims,
12   error::{LemmyError, LemmyErrorType},
13 };
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for ChangePassword {
17   type Response = LoginResponse;
18
19   #[tracing::instrument(skip(self, context))]
20   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
21     let data: &ChangePassword = self;
22     let local_user_view = local_user_view_from_jwt(data.auth.as_ref(), context).await?;
23
24     password_length_check(&data.new_password)?;
25
26     // Make sure passwords match
27     if data.new_password != data.new_password_verify {
28       return Err(LemmyErrorType::PasswordsDoNotMatch)?;
29     }
30
31     // Check the old password
32     let valid: bool = verify(
33       &data.old_password,
34       &local_user_view.local_user.password_encrypted,
35     )
36     .unwrap_or(false);
37     if !valid {
38       return Err(LemmyErrorType::IncorrectLogin)?;
39     }
40
41     let local_user_id = local_user_view.local_user.id;
42     let new_password = data.new_password.clone();
43     let updated_local_user =
44       LocalUser::update_password(context.pool(), local_user_id, &new_password).await?;
45
46     // Return the jwt
47     Ok(LoginResponse {
48       jwt: Some(
49         Claims::jwt(
50           updated_local_user.id.0,
51           &context.secret().jwt_secret,
52           &context.settings().hostname,
53         )?
54         .into(),
55       ),
56       verify_email_sent: false,
57       registration_created: false,
58     })
59   }
60 }