qm_customer/
cleanup.rs

1use futures::stream::FuturesUnordered;
2
3use qm_entity::ids::InfraContext;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeSet;
6use std::collections::HashSet;
7use std::sync::Arc;
8use strum::AsRefStr;
9use tokio::sync::Semaphore;
10use tracing::error;
11
12use qm_entity::ids::CustomerIds;
13use qm_entity::ids::InstitutionIds;
14use qm_entity::ids::OrganizationIds;
15use qm_keycloak::Keycloak;
16use qm_keycloak::KeycloakError;
17use sqlx::types::Uuid;
18
19#[derive(
20    Default, AsRefStr, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
21)]
22pub enum CleanupTaskType {
23    #[strum(serialize = "customers")]
24    Customers(CustomerIds),
25    #[strum(serialize = "organizations")]
26    Organizations(OrganizationIds),
27    #[strum(serialize = "institutions")]
28    Institutions(InstitutionIds),
29    #[default]
30    #[strum(serialize = "none")]
31    None,
32}
33
34#[derive(Default, Debug, Clone, Serialize, Deserialize)]
35pub struct CleanupTask {
36    pub id: Uuid,
37    pub ty: CleanupTaskType,
38}
39
40impl CleanupTask {
41    pub fn new(ty: CleanupTaskType) -> Self {
42        Self {
43            id: Uuid::new_v4(),
44            ty,
45        }
46    }
47}
48
49async fn remove_users_by_access(
50    realm: &str,
51    keycloak: &Keycloak,
52    role_name: &str,
53) -> anyhow::Result<()> {
54    let result = keycloak.role_members(realm, role_name).await;
55    match result {
56        Ok(users) => {
57            for user in users {
58                keycloak
59                    .remove_user(realm, user.id.as_deref().unwrap())
60                    .await?;
61            }
62        }
63        Err(err) => match err {
64            KeycloakError::HttpFailure { status: 404, .. } => {}
65            _ => Err(err)?,
66        },
67    }
68    Ok(())
69}
70
71pub async fn cleanup_api_clients(
72    keycloak: &Keycloak,
73    client_ids: Vec<String>,
74) -> anyhow::Result<()> {
75    let client_ids_set: HashSet<InfraContext> = HashSet::from_iter(
76        client_ids
77            .into_iter()
78            .filter_map(|v| v.parse::<InfraContext>().ok()),
79    );
80    let mut clients = keycloak.clients(keycloak.config().realm()).await?;
81    clients.retain(|v| {
82        v.client_id
83            .as_ref()
84            .and_then(|v| v.parse::<InfraContext>().ok())
85            .map(|id| match &id {
86                InfraContext::Customer(_) => client_ids_set.contains(&id),
87                InfraContext::Organization(v) => {
88                    client_ids_set.contains(&id)
89                        || client_ids_set.contains(&InfraContext::Customer(v.parent()))
90                }
91                InfraContext::Institution(v) => {
92                    client_ids_set.contains(&id)
93                        || client_ids_set.contains(&InfraContext::Organization(v.parent()))
94                        || client_ids_set.contains(&InfraContext::Customer(v.root()))
95                }
96            })
97            .unwrap_or(false)
98    });
99    for client in clients {
100        if let Some(client_id) = client.id.as_deref() {
101            let result = keycloak
102                .remove_client_with_uuid(keycloak.config().realm(), client_id)
103                .await;
104            if let Err(e) = result {
105                match e {
106                    KeycloakError::HttpFailure { status: 404, .. } => {}
107                    _ => {
108                        error!("{e:#?}");
109                    }
110                }
111            }
112        }
113    }
114
115    Ok(())
116}
117
118pub async fn cleanup_roles(keycloak: &Keycloak, roles: BTreeSet<String>) -> anyhow::Result<()> {
119    if !roles.is_empty() {
120        let semaphore = Arc::new(Semaphore::new(4));
121        let role_remove_tasks = FuturesUnordered::new();
122        for role in roles.clone().into_iter() {
123            let keycloak = keycloak.clone();
124            let permit = semaphore.clone().acquire_owned().await.unwrap();
125
126            role_remove_tasks.push(tokio::spawn(async move {
127                let realm = keycloak.config().realm();
128                tracing::debug!("remove users with role from keycloak {role}");
129                if remove_users_by_access(realm, &keycloak, &role)
130                    .await
131                    .is_err()
132                {
133                    drop(permit);
134                    return anyhow::Ok(role);
135                }
136                tracing::debug!("remove role from keycloak {role}");
137                let result = keycloak.remove_role(realm, &role).await;
138                drop(permit);
139                match result {
140                    Ok(_) => {}
141                    Err(err) => match err {
142                        KeycloakError::HttpFailure { status: 404, .. } => {}
143                        _ => {
144                            tracing::error!("Error: {err:#?}");
145                            Err(err)?;
146                        }
147                    },
148                }
149                anyhow::Ok(role)
150            }));
151        }
152    }
153    Ok(())
154}