]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/change_password.rs
Extract Activitypub logic into separate library (#2288)
[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   person::{ChangePassword, LoginResponse},
6   utils::{blocking, get_local_user_view_from_jwt, password_length_check},
7 };
8 use lemmy_db_schema::source::local_user::LocalUser;
9 use lemmy_utils::{claims::Claims, error::LemmyError, ConnectionId};
10 use lemmy_websocket::LemmyContext;
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 =
24       get_local_user_view_from_jwt(data.auth.as_ref(), context.pool(), context.secret()).await?;
25
26     password_length_check(&data.new_password)?;
27
28     // Make sure passwords match
29     if data.new_password != data.new_password_verify {
30       return Err(LemmyError::from_message("passwords_dont_match"));
31     }
32
33     // Check the old password
34     let valid: bool = verify(
35       &data.old_password,
36       &local_user_view.local_user.password_encrypted,
37     )
38     .unwrap_or(false);
39     if !valid {
40       return Err(LemmyError::from_message("password_incorrect"));
41     }
42
43     let local_user_id = local_user_view.local_user.id;
44     let new_password = data.new_password.to_owned();
45     let updated_local_user = blocking(context.pool(), move |conn| {
46       LocalUser::update_password(conn, local_user_id, &new_password)
47     })
48     .await??;
49
50     // Return the jwt
51     Ok(LoginResponse {
52       jwt: Some(
53         Claims::jwt(
54           updated_local_user.id.0,
55           &context.secret().jwt_secret,
56           &context.settings().hostname,
57         )?
58         .into(),
59       ),
60       verify_email_sent: false,
61       registration_created: false,
62     })
63   }
64 }