]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
f93ef335e5dc495a79f21a937559bd4da831d44d
[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(context.pool()).await?;
25
26     // Fetch that username / email
27     let username_or_email = data.username_or_email.clone();
28     let local_user_view = LocalUserView::find_by_email_or_name(context.pool(), &username_or_email)
29       .await
30       .with_lemmy_type(LemmyErrorType::IncorrectLogin)?;
31
32     // Verify the password
33     let valid: bool = verify(
34       &data.password,
35       &local_user_view.local_user.password_encrypted,
36     )
37     .unwrap_or(false);
38     if !valid {
39       return Err(LemmyErrorType::IncorrectLogin)?;
40     }
41     check_user_valid(
42       local_user_view.person.banned,
43       local_user_view.person.ban_expires,
44       local_user_view.person.deleted,
45     )?;
46
47     // Check if the user's email is verified if email verification is turned on
48     // However, skip checking verification if the user is an admin
49     if !local_user_view.person.admin
50       && site_view.local_site.require_email_verification
51       && !local_user_view.local_user.email_verified
52     {
53       return Err(LemmyErrorType::EmailNotVerified)?;
54     }
55
56     check_registration_application(&local_user_view, &site_view.local_site, context.pool()).await?;
57
58     // Check the totp
59     check_totp_2fa_valid(
60       &local_user_view.local_user.totp_2fa_secret,
61       &data.totp_2fa_token,
62       &site_view.site.name,
63       &local_user_view.person.name,
64     )?;
65
66     // Return the jwt
67     Ok(LoginResponse {
68       jwt: Some(
69         Claims::jwt(
70           local_user_view.local_user.id.0,
71           &context.secret().jwt_secret,
72           &context.settings().hostname,
73         )?
74         .into(),
75       ),
76       verify_email_sent: false,
77       registration_created: false,
78     })
79   }
80 }