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