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