qm_customer/schema/
groups.rs

1use async_graphql::{Context, FieldResult, Object};
2use async_graphql::{ErrorExtensions, ResultExt};
3use futures::StreamExt;
4use qm_entity::error::EntityError;
5use qm_entity::exerr;
6use qm_entity::ids::InfraContext;
7use qm_keycloak::realm::ensure_groups_with_roles;
8
9use std::collections::HashSet;
10
11use std::sync::Arc;
12
13use crate::cache::CacheDB;
14use crate::query::fetch_group_by_id;
15use crate::schema::auth::AuthGuard;
16use sqlx::types::Uuid;
17
18use crate::groups::RelatedBuiltInGroup;
19use crate::marker::Marker;
20use crate::model::{Group, GroupDetail, Role, UserGroup};
21use qm_role::AccessLevel;
22
23use crate::model::{QmCustomer, QmInstitution, QmOrganization /* OrganizationUnit */};
24use crate::schema::auth::AuthCtx;
25use crate::schema::RelatedAuth;
26use crate::schema::RelatedPermission;
27use crate::schema::RelatedResource;
28use crate::schema::RelatedStorage;
29
30#[Object]
31impl UserGroup {
32    async fn id(&self) -> Arc<str> {
33        self.group_id.clone()
34    }
35
36    async fn name(&self) -> Option<Arc<str>> {
37        self.group_detail.display_name.clone()
38    }
39
40    async fn roles(&self, ctx: &Context<'_>) -> Option<Arc<[Arc<Role>]>> {
41        let cache = ctx.data::<CacheDB>().ok();
42        if cache.is_none() {
43            tracing::warn!("qm::customer::cache::CacheDB is not installed in schema context");
44            return None;
45        }
46        let cache = cache.unwrap();
47        cache.roles_by_group_id(&self.group_id).await
48    }
49
50    async fn customer(&self, ctx: &Context<'_>) -> Option<Arc<QmCustomer>> {
51        let cache = ctx.data::<CacheDB>().ok();
52        if cache.is_none() {
53            tracing::warn!("qm::customer::cache::CacheDB is not installed in schema context");
54            return None;
55        }
56        let cache = cache.unwrap();
57        if let Some(id) = self
58            .group_detail
59            .context
60            .as_ref()
61            .map(InfraContext::customer_id)
62        {
63            return cache.customer_by_id(&id).await;
64        }
65        None
66    }
67
68    async fn organization(&self, ctx: &Context<'_>) -> Option<Arc<QmOrganization>> {
69        let cache = ctx.data::<CacheDB>().ok();
70        if cache.is_none() {
71            tracing::warn!("qm::customer::cache::CacheDB is not installed in schema context");
72            return None;
73        }
74        let cache = cache.unwrap();
75        if let Some(id) = self
76            .group_detail
77            .context
78            .as_ref()
79            .and_then(InfraContext::organization_id)
80        {
81            return cache.organization_by_id(&id).await;
82        }
83        None
84    }
85
86    // async fn organization_unit(&self, ctx: &Context<'_>) -> Option<Arc<OrganizationUnit>> {
87    //     let cache = ctx.data::<CacheDB>().ok();
88    //     if cache.is_none() {
89    //         tracing::warn!("qm::customer::cache::CacheDB is not installed in schema context");
90    //         return None;
91    //     }
92    //     let cache = cache.unwrap();
93    //     if let Some(id) = self
94    //         .group_detail
95    //         .context
96    //         .as_ref()
97    //         .and_then(InfraContext::organization_unit_id)
98    //     {
99    //         return cache.organization_unit_by_id(&id).await;
100    //     }
101    //     None
102    // }
103
104    async fn institution(&self, ctx: &Context<'_>) -> Option<Arc<QmInstitution>> {
105        let cache = ctx.data::<CacheDB>().ok();
106        if cache.is_none() {
107            tracing::warn!("qm::customer::cache::CacheDB is not installed in schema context");
108            return None;
109        }
110        let cache = cache.unwrap();
111        if let Some(id) = self
112            .group_detail
113            .context
114            .as_ref()
115            .and_then(InfraContext::institution_id)
116        {
117            return cache.institution_by_id(&id).await;
118        }
119        None
120    }
121
122    async fn allowed_access_levels(&self) -> Option<Arc<[AccessLevel]>> {
123        self.group_detail.allowed_access_levels.clone()
124    }
125
126    async fn allowed_types(&self) -> Option<Arc<[Arc<str>]>> {
127        self.group_detail.allowed_types.clone()
128    }
129}
130
131pub struct Groups;
132impl Default for Groups {
133    fn default() -> Self {
134        Self
135    }
136}
137
138#[Object]
139impl Groups {
140    async fn app(&self, ctx: &Context<'_>) -> FieldResult<Vec<UserGroup>> {
141        let cache = ctx.data_unchecked::<CacheDB>();
142        let groups = cache.groups_by_parent("app").await;
143        Ok(futures::stream::iter(groups)
144            .filter_map(|g| async move {
145                cache.group_detail_by_id(&g.id).await.map(|v| UserGroup {
146                    group_id: g.id.clone(),
147                    group_detail: v,
148                })
149            })
150            .collect()
151            .await)
152    }
153
154    async fn custom(
155        &self,
156        ctx: &Context<'_>,
157        context: InfraContext,
158    ) -> FieldResult<Vec<UserGroup>> {
159        let cache = ctx.data_unchecked::<CacheDB>();
160        let parent = format!("custom@{context}");
161        let groups = cache.groups_by_parent(&parent).await;
162        Ok(futures::stream::iter(groups)
163            .filter_map(|g| async move {
164                cache.group_detail_by_id(&g.id).await.map(|v| UserGroup {
165                    group_id: g.id.clone(),
166                    group_detail: v,
167                })
168            })
169            .collect()
170            .await)
171    }
172}
173
174pub struct Ctx<'a, Auth, Store, Resource, Permission>(
175    pub &'a AuthCtx<'a, Auth, Store, Resource, Permission>,
176)
177where
178    Auth: RelatedAuth<Resource, Permission>,
179    Store: RelatedStorage,
180    Resource: RelatedResource,
181    Permission: RelatedPermission;
182impl<'a, Auth, Store, Resource, Permission> Ctx<'a, Auth, Store, Resource, Permission>
183where
184    Auth: RelatedAuth<Resource, Permission>,
185    Store: RelatedStorage,
186    Resource: RelatedResource,
187    Permission: RelatedPermission,
188{
189    pub async fn create(
190        &self,
191        name: String,
192        context: InfraContext,
193        allowed_access_levels: HashSet<AccessLevel>,
194        allowed_types: HashSet<String>,
195        roles: HashSet<qm_role::Role<Resource, Permission>>,
196    ) -> async_graphql::FieldResult<Arc<UserGroup>> {
197        let path = format!(
198            "/custom@{context}/{}",
199            inflector::cases::snakecase::to_snake_case(name.replace('/', "").trim())
200        );
201        if self
202            .0
203            .store
204            .cache_db()
205            .group_id_by_path(&path)
206            .await
207            .is_some()
208        {
209            return exerr!(name_conflict::<Group>(name));
210        }
211        let groups = ensure_groups_with_roles(
212            self.0.store.keycloak().config().realm(),
213            self.0.store.keycloak(),
214            vec![qm_role::Group::<Resource, Permission>::new(
215                name,
216                path.clone(),
217                allowed_access_levels.clone().into_iter().collect(),
218                allowed_types.clone().into_iter().collect(),
219                roles.into_iter().collect(),
220            )],
221            false,
222        )
223        .await?;
224        let kc_group = groups.get(&path).ok_or(EntityError::internal())?;
225        let group_query = fetch_group_by_id(
226            self.0.store.keycloak_db(),
227            kc_group.id.as_ref().ok_or(EntityError::internal())?,
228        )
229        .await?;
230        let parent_name = Arc::from(group_query.parent_name.unwrap());
231        let group = Arc::new(Group {
232            id: Arc::from(group_query.group_id.unwrap()),
233            parent_group: group_query.parent_group.map(Arc::from),
234            name: Arc::from(group_query.name.unwrap()),
235        });
236        let group_detail = Arc::new(GroupDetail {
237            allowed_access_levels: Some(allowed_access_levels.into_iter().collect()),
238            allowed_types: Some(allowed_types.into_iter().map(|s| s.into()).collect()),
239            built_in: false,
240            context: Some(context),
241            display_name: group_query.display_name.map(Arc::from),
242        });
243        let group_id = group.id.clone();
244        self.0
245            .store
246            .cache_db()
247            .user()
248            .new_group(group, parent_name, group_detail.clone())
249            .await;
250        Ok(Arc::new(UserGroup {
251            group_detail,
252            group_id,
253        }))
254    }
255
256    pub async fn remove(&self, ids: &[Arc<str>]) -> async_graphql::FieldResult<u64> {
257        let mut i = 0;
258        for id in ids {
259            self.0
260                .store
261                .keycloak()
262                .remove_group(self.0.store.keycloak().config().realm(), id)
263                .await?;
264            i += 1;
265        }
266        Ok(i)
267    }
268}
269
270pub struct GroupQueryRoot<Auth, Store, Resource, Permission, BuiltInGroup> {
271    _marker: Marker<Auth, Store, Resource, Permission, BuiltInGroup>,
272}
273
274impl<Auth, Store, Resource, Permission, BuiltInGroup> Default
275    for GroupQueryRoot<Auth, Store, Resource, Permission, BuiltInGroup>
276{
277    fn default() -> Self {
278        Self {
279            _marker: std::marker::PhantomData,
280        }
281    }
282}
283
284#[Object]
285impl<Auth, Store, Resource, Permission, BuiltInGroup>
286    GroupQueryRoot<Auth, Store, Resource, Permission, BuiltInGroup>
287where
288    Auth: RelatedAuth<Resource, Permission>,
289    Store: RelatedStorage,
290    Resource: RelatedResource,
291    Permission: RelatedPermission,
292    BuiltInGroup: RelatedBuiltInGroup,
293{
294    #[graphql(
295        guard = "AuthGuard::<Auth, Store, Resource, Permission>::new(qm_role::role!(Resource::user(), Permission::create()))"
296    )]
297    async fn groups(&self) -> Groups {
298        Groups
299    }
300}
301
302pub struct GroupMutationRoot<Auth, Store, Resource, Permission, BuiltInGroup> {
303    _marker: Marker<Auth, Store, Resource, Permission, BuiltInGroup>,
304}
305
306impl<Auth, Store, Resource, Permission, BuiltInGroup> Default
307    for GroupMutationRoot<Auth, Store, Resource, Permission, BuiltInGroup>
308{
309    fn default() -> Self {
310        Self {
311            _marker: std::marker::PhantomData,
312        }
313    }
314}
315
316#[Object]
317impl<Auth, Store, Resource, Permission, BuiltInGroup>
318    GroupMutationRoot<Auth, Store, Resource, Permission, BuiltInGroup>
319where
320    Auth: RelatedAuth<Resource, Permission>,
321    Store: RelatedStorage,
322    Resource: RelatedResource,
323    Permission: RelatedPermission,
324    BuiltInGroup: RelatedBuiltInGroup,
325{
326    async fn create_group(
327        &self,
328        ctx: &Context<'_>,
329        context: InfraContext,
330        name: String,
331        allowed_access_levels: HashSet<AccessLevel>,
332        allowed_types: HashSet<String>,
333        roles: HashSet<qm_role::Role<Resource, Permission>>,
334    ) -> async_graphql::FieldResult<Arc<UserGroup>> {
335        let auth_ctx = AuthCtx::<'_, Auth, Store, Resource, Permission>::new_with_role(
336            ctx,
337            &qm_role::role!(Resource::user(), Permission::create()),
338        )
339        .await?;
340        auth_ctx.can_mutate(Some(&context)).await?;
341        if allowed_access_levels
342            .iter()
343            .any(|lvl| matches!(lvl, &AccessLevel::Admin | AccessLevel::None))
344        {
345            return exerr!(bad_request(
346                "UserGroup",
347                "unable to create custom group with allowed access level ADMIN or NONE"
348            ));
349        }
350        if roles.iter().any(|r| r.ty.is_admin()) {
351            return exerr!(bad_request(
352                "UserGroup",
353                "unable to create custom group with role 'administration'"
354            ));
355        }
356        if !auth_ctx.is_admin {
357            for role in roles.iter() {
358                if !auth_ctx.auth.has_role_object(role) {
359                    return exerr!(unauthorized(&auth_ctx.auth));
360                }
361            }
362        }
363        let roles = roles.into_iter().collect();
364        Ctx(&auth_ctx)
365            .create(name, context, allowed_access_levels, allowed_types, roles)
366            .await
367    }
368
369    async fn remove_groups(
370        &self,
371        ctx: &Context<'_>,
372        ids: Arc<[Uuid]>,
373    ) -> async_graphql::FieldResult<u64> {
374        let auth_ctx = AuthCtx::<'_, Auth, Store, Resource, Permission>::new_with_role(
375            ctx,
376            &qm_role::role!(Resource::user(), Permission::create()),
377        )
378        .await?;
379        let mut group_ids = vec![];
380        for id in ids.iter() {
381            let id: Arc<str> = Arc::from(id.to_string());
382            auth_ctx
383                .store
384                .cache_db()
385                .group_by_id(&id)
386                .await
387                .ok_or(EntityError::not_found_by_id::<Group>(id.as_ref()))
388                .extend()?;
389            let group_detail = auth_ctx
390                .store
391                .cache_db()
392                .group_detail_by_id(&id)
393                .await
394                .ok_or(EntityError::not_found_by_id::<Group>(id.as_ref()))
395                .extend()?;
396            if group_detail.built_in {
397                return exerr!(bad_request("Group", "unable to remove built in groups"));
398            }
399            auth_ctx.can_mutate(group_detail.context.as_ref()).await?;
400            group_ids.push(id);
401        }
402        Ctx(&auth_ctx).remove(&group_ids).await
403    }
404}