]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
Updating `login.rs` with generic `incorrect_login` response. (#3549)
[lemmy.git] / crates / api / src / local_user / login.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::{Login, LoginResponse},
7   utils::{check_registration_application, check_user_valid},
8 };
9 use lemmy_db_views::structs::{LocalUserView, SiteView};
10 use lemmy_utils::{claims::Claims, error::LemmyError, utils::validation::check_totp_2fa_valid};
11
12 #[async_trait::async_trait(?Send)]
13 impl Perform for Login {
14   type Response = LoginResponse;
15
16   #[tracing::instrument(skip(context))]
17   async fn perform(&self, context: &Data<LemmyContext>) -> Result<LoginResponse, LemmyError> {
18     let data: &Login = self;
19
20     let site_view = SiteView::read_local(context.pool()).await?;
21
22     // Fetch that username / email
23     let username_or_email = data.username_or_email.clone();
24     let local_user_view = LocalUserView::find_by_email_or_name(context.pool(), &username_or_email)
25       .await
26       .map_err(|e| LemmyError::from_error_message(e, "incorrect_login"))?;
27
28     // Verify the password
29     let valid: bool = verify(
30       &data.password,
31       &local_user_view.local_user.password_encrypted,
32     )
33     .unwrap_or(false);
34     if !valid {
35       return Err(LemmyError::from_message("incorrect_login"));
36     }
37     check_user_valid(
38       local_user_view.person.banned,
39       local_user_view.person.ban_expires,
40       local_user_view.person.deleted,
41     )?;
42
43     // Check if the user's email is verified if email verification is turned on
44     // However, skip checking verification if the user is an admin
45     if !local_user_view.person.admin
46       && site_view.local_site.require_email_verification
47       && !local_user_view.local_user.email_verified
48     {
49       return Err(LemmyError::from_message("email_not_verified"));
50     }
51
52     check_registration_application(&local_user_view, &site_view.local_site, context.pool()).await?;
53
54     // Check the totp
55     check_totp_2fa_valid(
56       &local_user_view.local_user.totp_2fa_secret,
57       &data.totp_2fa_token,
58       &site_view.site.name,
59       &local_user_view.person.name,
60     )?;
61
62     // Return the jwt
63     Ok(LoginResponse {
64       jwt: Some(
65         Claims::jwt(
66           local_user_view.local_user.id.0,
67           &context.secret().jwt_secret,
68           &context.settings().hostname,
69         )?
70         .into(),
71       ),
72       verify_email_sent: false,
73       registration_created: false,
74     })
75   }
76 }