]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
Remove chatserver (#2919)
[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, "couldnt_find_that_username_or_email"))?;
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("password_incorrect"));
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     if site_view.local_site.require_email_verification && !local_user_view.local_user.email_verified
44     {
45       return Err(LemmyError::from_message("email_not_verified"));
46     }
47
48     check_registration_application(&local_user_view, &site_view.local_site, context.pool()).await?;
49
50     // Check the totp
51     check_totp_2fa_valid(
52       &local_user_view.local_user.totp_2fa_secret,
53       &data.totp_2fa_token,
54       &site_view.site.name,
55       &local_user_view.person.name,
56     )?;
57
58     // Return the jwt
59     Ok(LoginResponse {
60       jwt: Some(
61         Claims::jwt(
62           local_user_view.local_user.id.0,
63           &context.secret().jwt_secret,
64           &context.settings().hostname,
65         )?
66         .into(),
67       ),
68       verify_email_sent: false,
69       registration_created: false,
70     })
71   }
72 }