From b1dc4f362ef944c3842909b6a2dd88abf7f961d1 Mon Sep 17 00:00:00 2001
From: Alain Mazy <alain@mazy.be>
Date: Fri, 20 Sep 2024 17:14:11 +0200
Subject: [PATCH] Fixed roles removed from Keycloak that were still being
 listed in /settings/roles

---
 release-notes.md                    | 1 +
 sources/orthanc_auth_service/app.py | 7 +++++++
 2 files changed, 8 insertions(+)

diff --git a/release-notes.md b/release-notes.md
index 69f9a21..99343b7 100644
--- a/release-notes.md
+++ b/release-notes.md
@@ -9,6 +9,7 @@ Pending changes
 
 - Fixed typo in `KEYCLOAK_ADMIN_URI` that was not read correctly.
 - Fixed special characters that were not allowed in API keys.
+- Fixed roles removed from Keycloak that were still being listed in /settings/roles
 
 
 v 24.7.2
diff --git a/sources/orthanc_auth_service/app.py b/sources/orthanc_auth_service/app.py
index e5cebc9..20275a2 100644
--- a/sources/orthanc_auth_service/app.py
+++ b/sources/orthanc_auth_service/app.py
@@ -80,6 +80,13 @@ def ingest_keycloak_roles(roles_config: RolesConfigurationModel):
         for keycloak_role in all_keycloak_roles:
             if keycloak_role not in roles_config.roles:
                 roles_configuration.get_configured_roles().roles[keycloak_role] = RolePermissions()
+
+        # keep only the roles that are defined in Keycloak:
+        roles_to_remove_from_json = set(roles_configuration.get_configured_roles().roles.keys()).difference(set(all_keycloak_roles))
+        for role in roles_to_remove_from_json:
+            logging.info(f"Role was configured but does not exist in Keycloak: {role}")
+            del roles_configuration.get_configured_roles().roles[role]
+
     else:
         logging.error(f"No Keycloack admin client defined, you probably should define KEYCLOAK_CLIENT_SECRET")
         raise HTTPException(status_code=404, detail="No Keycloack admin client defined, you probably should define KEYCLOAK_CLIENT_SECRET")