]> Untitled Git - lemmy.git/blob - crates/api_crud/src/user/delete.rs
28f42831ed8c078cde6fcd67f4000c01432dc7b4
[lemmy.git] / crates / api_crud / src / user / delete.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use bcrypt::verify;
4 use lemmy_api_common::{blocking, get_local_user_view_from_jwt, person::*};
5 use lemmy_db_schema::source::{comment::Comment, person::Person, post::Post};
6 use lemmy_utils::{ApiError, ConnectionId, LemmyError};
7 use lemmy_websocket::LemmyContext;
8
9 #[async_trait::async_trait(?Send)]
10 impl PerformCrud for DeleteAccount {
11   type Response = LoginResponse;
12
13   async fn perform(
14     &self,
15     context: &Data<LemmyContext>,
16     _websocket_id: Option<ConnectionId>,
17   ) -> Result<LoginResponse, LemmyError> {
18     let data: &DeleteAccount = self;
19     let local_user_view =
20       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
21
22     // Verify the password
23     let valid: bool = verify(
24       &data.password,
25       &local_user_view.local_user.password_encrypted,
26     )
27     .unwrap_or(false);
28     if !valid {
29       return Err(ApiError::err_plain("password_incorrect").into());
30     }
31
32     // Comments
33     let person_id = local_user_view.person.id;
34     let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id);
35     blocking(context.pool(), permadelete)
36       .await?
37       .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
38
39     // Posts
40     let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id);
41     blocking(context.pool(), permadelete)
42       .await?
43       .map_err(|e| ApiError::err("couldnt_update_post", e))?;
44
45     blocking(context.pool(), move |conn| {
46       Person::delete_account(conn, person_id)
47     })
48     .await??;
49
50     Ok(LoginResponse {
51       jwt: data.auth.to_owned(),
52     })
53   }
54 }