]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/add_admin.rs
a58174fb4aed02347cf086a91f39bccfd323fd57
[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::{is_admin, local_user_view_from_jwt},
7 };
8 use lemmy_db_schema::{
9   source::{
10     moderator::{ModAdd, ModAddForm},
11     person::{Person, PersonUpdateForm},
12   },
13   traits::Crud,
14 };
15 use lemmy_db_views_actor::structs::PersonView;
16 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
17
18 #[async_trait::async_trait(?Send)]
19 impl Perform for AddAdmin {
20   type Response = AddAdminResponse;
21
22   #[tracing::instrument(skip(context))]
23   async fn perform(&self, context: &Data<LemmyContext>) -> Result<AddAdminResponse, LemmyError> {
24     let data: &AddAdmin = self;
25     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
26
27     // Make sure user is an admin
28     is_admin(&local_user_view)?;
29
30     let added = data.added;
31     let added_person_id = data.person_id;
32     let added_admin = Person::update(
33       context.pool(),
34       added_person_id,
35       &PersonUpdateForm::builder().admin(Some(added)).build(),
36     )
37     .await
38     .with_lemmy_type(LemmyErrorType::CouldntUpdateUser)?;
39
40     // Mod tables
41     let form = ModAddForm {
42       mod_person_id: local_user_view.person.id,
43       other_person_id: added_admin.id,
44       removed: Some(!data.added),
45     };
46
47     ModAdd::create(context.pool(), &form).await?;
48
49     let admins = PersonView::admins(context.pool()).await?;
50
51     Ok(AddAdminResponse { admins })
52   }
53 }