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