]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
Add diesel_async, get rid of blocking function (#2510)
[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   person::{Login, LoginResponse},
6   utils::{check_registration_application, check_user_valid},
7 };
8 use lemmy_db_schema::source::local_site::LocalSite;
9 use lemmy_db_views::structs::LocalUserView;
10 use lemmy_utils::{claims::Claims, error::LemmyError, ConnectionId};
11 use lemmy_websocket::LemmyContext;
12
13 #[async_trait::async_trait(?Send)]
14 impl Perform for Login {
15   type Response = LoginResponse;
16
17   #[tracing::instrument(skip(context, _websocket_id))]
18   async fn perform(
19     &self,
20     context: &Data<LemmyContext>,
21     _websocket_id: Option<ConnectionId>,
22   ) -> Result<LoginResponse, LemmyError> {
23     let data: &Login = self;
24
25     let local_site = LocalSite::read(context.pool()).await?;
26
27     // Fetch that username / email
28     let username_or_email = data.username_or_email.clone();
29     let local_user_view = LocalUserView::find_by_email_or_name(context.pool(), &username_or_email)
30       .await
31       .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?;
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(LemmyError::from_message("password_incorrect"));
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     if local_site.require_email_verification && !local_user_view.local_user.email_verified {
49       return Err(LemmyError::from_message("email_not_verified"));
50     }
51
52     check_registration_application(&local_user_view, &local_site, context.pool()).await?;
53
54     // Return the jwt
55     Ok(LoginResponse {
56       jwt: Some(
57         Claims::jwt(
58           local_user_view.local_user.id.0,
59           &context.secret().jwt_secret,
60           &context.settings().hostname,
61         )?
62         .into(),
63       ),
64       verify_email_sent: false,
65       registration_created: false,
66     })
67   }
68 }