]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/login.rs
implement language tags for site/community in db and api (#2434)
[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::site::Site;
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     // Fetch that username / email
26     let username_or_email = data.username_or_email.clone();
27     let local_user_view = blocking(context.pool(), move |conn| {
28       LocalUserView::find_by_email_or_name(conn, &username_or_email)
29     })
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     let site = blocking(context.pool(), Site::read_local).await??;
49     if site.require_email_verification && !local_user_view.local_user.email_verified {
50       return Err(LemmyError::from_message("email_not_verified"));
51     }
52
53     check_registration_application(&site, &local_user_view, context.pool()).await?;
54
55     // Return the jwt
56     Ok(LoginResponse {
57       jwt: Some(
58         Claims::jwt(
59           local_user_view.local_user.id.0,
60           &context.secret().jwt_secret,
61           &context.settings().hostname,
62         )?
63         .into(),
64       ),
65       verify_email_sent: false,
66       registration_created: false,
67     })
68   }
69 }