]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
Moving settings to Database. (#2492)
[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::{blocking, 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 = blocking(context.pool(), LocalSite::read).await??;
26
27     // Fetch that username / email
28     let username_or_email = data.username_or_email.clone();
29     let local_user_view = blocking(context.pool(), move |conn| {
30       LocalUserView::find_by_email_or_name(conn, &username_or_email)
31     })
32     .await?
33     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?;
34
35     // Verify the password
36     let valid: bool = verify(
37       &data.password,
38       &local_user_view.local_user.password_encrypted,
39     )
40     .unwrap_or(false);
41     if !valid {
42       return Err(LemmyError::from_message("password_incorrect"));
43     }
44     check_user_valid(
45       local_user_view.person.banned,
46       local_user_view.person.ban_expires,
47       local_user_view.person.deleted,
48     )?;
49
50     if local_site.require_email_verification && !local_user_view.local_user.email_verified {
51       return Err(LemmyError::from_message("email_not_verified"));
52     }
53
54     check_registration_application(&local_user_view, &local_site, context.pool()).await?;
55
56     // Return the jwt
57     Ok(LoginResponse {
58       jwt: Some(
59         Claims::jwt(
60           local_user_view.local_user.id.0,
61           &context.secret().jwt_secret,
62           &context.settings().hostname,
63         )?
64         .into(),
65       ),
66       verify_email_sent: false,
67       registration_created: false,
68     })
69   }
70 }