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