]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/change_password.rs
Remove chatserver (#2919)
[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::{claims::Claims, error::LemmyError};
11
12 #[async_trait::async_trait(?Send)]
13 impl Perform for ChangePassword {
14   type Response = LoginResponse;
15
16   #[tracing::instrument(skip(self, context))]
17   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
18     let data: &ChangePassword = self;
19     let local_user_view = local_user_view_from_jwt(data.auth.as_ref(), context).await?;
20
21     password_length_check(&data.new_password)?;
22
23     // Make sure passwords match
24     if data.new_password != data.new_password_verify {
25       return Err(LemmyError::from_message("passwords_dont_match"));
26     }
27
28     // Check the old password
29     let valid: bool = verify(
30       &data.old_password,
31       &local_user_view.local_user.password_encrypted,
32     )
33     .unwrap_or(false);
34     if !valid {
35       return Err(LemmyError::from_message("password_incorrect"));
36     }
37
38     let local_user_id = local_user_view.local_user.id;
39     let new_password = data.new_password.clone();
40     let updated_local_user =
41       LocalUser::update_password(context.pool(), local_user_id, &new_password).await?;
42
43     // Return the jwt
44     Ok(LoginResponse {
45       jwt: Some(
46         Claims::jwt(
47           updated_local_user.id.0,
48           &context.secret().jwt_secret,
49           &context.settings().hostname,
50         )?
51         .into(),
52       ),
53       verify_email_sent: false,
54       registration_created: false,
55     })
56   }
57 }