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