aboutsummaryrefslogtreecommitdiffstats
path: root/arthur/apis/directory/keycloak.py
blob: 836dfae023025a1fe7781f69bcded426ed7f2345 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""Utilities for interacting with the Keycloak REST API."""

from functools import cache

from keycloak import KeycloakAdmin

from arthur.config import CONFIG


@cache
def create_client() -> KeycloakAdmin:
    """Create a new client for the Keycloak API."""
    return KeycloakAdmin(
        server_url=str(CONFIG.keycloak_address),
        username=CONFIG.keycloak_username,
        password=CONFIG.keycloak_password.get_secret_value(),
        realm_name=CONFIG.keycloak_user_realm,
        user_realm_name="master",
    )


def force_password_reset(username: str, password: str) -> None:
    """Force a password reset for a user."""
    client = create_client()

    user_id = client.get_user_id(username)

    if not user_id:
        msg = f"User {username} not found in Keycloak."
        raise ValueError(msg)

    client.set_user_password(user_id, password, temporary=True)