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