]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/remove.rs
Dont return error in case optional auth is invalid (#2879)
[lemmy.git] / crates / api_crud / src / community / remove.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{CommunityResponse, RemoveCommunity},
5   context::LemmyContext,
6   utils::{is_admin, local_user_view_from_jwt},
7   websocket::UserOperationCrud,
8 };
9 use lemmy_db_schema::{
10   source::{
11     community::{Community, CommunityUpdateForm},
12     moderator::{ModRemoveCommunity, ModRemoveCommunityForm},
13   },
14   traits::Crud,
15 };
16 use lemmy_utils::{error::LemmyError, utils::time::naive_from_unix, ConnectionId};
17
18 #[async_trait::async_trait(?Send)]
19 impl PerformCrud for RemoveCommunity {
20   type Response = CommunityResponse;
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<CommunityResponse, LemmyError> {
28     let data: &RemoveCommunity = self;
29     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
30
31     // Verify its an admin (only an admin can remove a community)
32     is_admin(&local_user_view)?;
33
34     // Do the remove
35     let community_id = data.community_id;
36     let removed = data.removed;
37     Community::update(
38       context.pool(),
39       community_id,
40       &CommunityUpdateForm::builder()
41         .removed(Some(removed))
42         .build(),
43     )
44     .await
45     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
46
47     // Mod tables
48     let expires = data.expires.map(naive_from_unix);
49     let form = ModRemoveCommunityForm {
50       mod_person_id: local_user_view.person.id,
51       community_id: data.community_id,
52       removed: Some(removed),
53       reason: data.reason.clone(),
54       expires,
55     };
56     ModRemoveCommunity::create(context.pool(), &form).await?;
57
58     let res = context
59       .send_community_ws_message(
60         &UserOperationCrud::RemoveCommunity,
61         data.community_id,
62         websocket_id,
63         Some(local_user_view.person.id),
64       )
65       .await?;
66
67     Ok(res)
68   }
69 }