]> Untitled Git - lemmy.git/blob - crates/api/src/site/leave_admin.rs
Moving settings to Database. (#2492)
[lemmy.git] / crates / api / src / site / leave_admin.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   site::{GetSiteResponse, LeaveAdmin},
5   utils::{blocking, get_local_user_view_from_jwt, is_admin},
6 };
7 use lemmy_db_schema::{
8   source::{
9     actor_language::SiteLanguage,
10     language::Language,
11     moderator::{ModAdd, ModAddForm},
12     person::{Person, PersonUpdateForm},
13   },
14   traits::Crud,
15 };
16 use lemmy_db_views::structs::SiteView;
17 use lemmy_db_views_actor::structs::PersonViewSafe;
18 use lemmy_utils::{error::LemmyError, version, ConnectionId};
19 use lemmy_websocket::LemmyContext;
20
21 #[async_trait::async_trait(?Send)]
22 impl Perform for LeaveAdmin {
23   type Response = GetSiteResponse;
24
25   #[tracing::instrument(skip(context, _websocket_id))]
26   async fn perform(
27     &self,
28     context: &Data<LemmyContext>,
29     _websocket_id: Option<ConnectionId>,
30   ) -> Result<GetSiteResponse, LemmyError> {
31     let data: &LeaveAdmin = self;
32     let local_user_view =
33       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
34
35     is_admin(&local_user_view)?;
36
37     // Make sure there isn't just one admin (so if one leaves, there will still be one left)
38     let admins = blocking(context.pool(), PersonViewSafe::admins).await??;
39     if admins.len() == 1 {
40       return Err(LemmyError::from_message("cannot_leave_admin"));
41     }
42
43     let person_id = local_user_view.person.id;
44     blocking(context.pool(), move |conn| {
45       Person::update(
46         conn,
47         person_id,
48         &PersonUpdateForm::builder().admin(Some(false)).build(),
49       )
50     })
51     .await??;
52
53     // Mod tables
54     let form = ModAddForm {
55       mod_person_id: person_id,
56       other_person_id: person_id,
57       removed: Some(true),
58     };
59
60     blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
61
62     // Reread site and admins
63     let site_view = blocking(context.pool(), SiteView::read_local).await??;
64     let admins = blocking(context.pool(), PersonViewSafe::admins).await??;
65
66     let all_languages = blocking(context.pool(), Language::read_all).await??;
67     let discussion_languages = blocking(context.pool(), SiteLanguage::read_local).await??;
68
69     Ok(GetSiteResponse {
70       site_view,
71       admins,
72       online: 0,
73       version: version::VERSION.to_string(),
74       my_user: None,
75       federated_instances: None,
76       all_languages,
77       discussion_languages,
78     })
79   }
80 }