]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/add_admin.rs
Split apart api files (#2216)
[lemmy.git] / crates / api / src / local_user / add_admin.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   get_local_user_view_from_jwt,
6   is_admin,
7   person::{AddAdmin, AddAdminResponse},
8 };
9 use lemmy_db_schema::{
10   source::{
11     moderator::{ModAdd, ModAddForm},
12     person::Person,
13   },
14   traits::Crud,
15 };
16 use lemmy_db_views_actor::person_view::PersonViewSafe;
17 use lemmy_utils::{ConnectionId, LemmyError};
18 use lemmy_websocket::{messages::SendAllMessage, LemmyContext, UserOperation};
19
20 #[async_trait::async_trait(?Send)]
21 impl Perform for AddAdmin {
22   type Response = AddAdminResponse;
23
24   #[tracing::instrument(skip(context, websocket_id))]
25   async fn perform(
26     &self,
27     context: &Data<LemmyContext>,
28     websocket_id: Option<ConnectionId>,
29   ) -> Result<AddAdminResponse, LemmyError> {
30     let data: &AddAdmin = self;
31     let local_user_view =
32       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
33
34     // Make sure user is an admin
35     is_admin(&local_user_view)?;
36
37     let added = data.added;
38     let added_person_id = data.person_id;
39     let added_admin = blocking(context.pool(), move |conn| {
40       Person::add_admin(conn, added_person_id, added)
41     })
42     .await?
43     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?;
44
45     // Mod tables
46     let form = ModAddForm {
47       mod_person_id: local_user_view.person.id,
48       other_person_id: added_admin.id,
49       removed: Some(!data.added),
50     };
51
52     blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
53
54     let admins = blocking(context.pool(), PersonViewSafe::admins).await??;
55
56     let res = AddAdminResponse { admins };
57
58     context.chat_server().do_send(SendAllMessage {
59       op: UserOperation::AddAdmin,
60       response: res.clone(),
61       websocket_id,
62     });
63
64     Ok(res)
65   }
66 }