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