]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/change_password_after_reset.rs
Adding diesel enums for SortType and ListingType (#2808)
[lemmy.git] / crates / api / src / local_user / change_password_after_reset.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   context::LemmyContext,
5   person::{LoginResponse, PasswordChangeAfterReset},
6   utils::password_length_check,
7 };
8 use lemmy_db_schema::{
9   source::{local_user::LocalUser, password_reset_request::PasswordResetRequest},
10   RegistrationMode,
11 };
12 use lemmy_db_views::structs::SiteView;
13 use lemmy_utils::{claims::Claims, error::LemmyError, ConnectionId};
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for PasswordChangeAfterReset {
17   type Response = LoginResponse;
18
19   #[tracing::instrument(skip(self, context, _websocket_id))]
20   async fn perform(
21     &self,
22     context: &Data<LemmyContext>,
23     _websocket_id: Option<ConnectionId>,
24   ) -> Result<LoginResponse, LemmyError> {
25     let data: &PasswordChangeAfterReset = self;
26
27     // Fetch the user_id from the token
28     let token = data.token.clone();
29     let local_user_id = PasswordResetRequest::read_from_token(context.pool(), &token)
30       .await
31       .map(|p| p.local_user_id)?;
32
33     password_length_check(&data.password)?;
34
35     // Make sure passwords match
36     if data.password != data.password_verify {
37       return Err(LemmyError::from_message("passwords_dont_match"));
38     }
39
40     // Update the user with the new password
41     let password = data.password.clone();
42     let updated_local_user = LocalUser::update_password(context.pool(), local_user_id, &password)
43       .await
44       .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?;
45
46     // Return the jwt if login is allowed
47     let site_view = SiteView::read_local(context.pool()).await?;
48     let jwt = if site_view.local_site.registration_mode == RegistrationMode::RequireApplication
49       && !updated_local_user.accepted_application
50     {
51       None
52     } else {
53       Some(
54         Claims::jwt(
55           updated_local_user.id.0,
56           &context.secret().jwt_secret,
57           &context.settings().hostname,
58         )?
59         .into(),
60       )
61     };
62
63     Ok(LoginResponse {
64       jwt,
65       verify_email_sent: false,
66       registration_created: false,
67     })
68   }
69 }