Skip to content
Snippets Groups Projects
Commit e0bf24e5 authored by Antoine Lambert's avatar Antoine Lambert
Browse files

django/utils: Add conversion functions between django and keycloak ids

Django uses integer identifiers while keycloak uses UUIDs so add some
utility functions to covert back and forth between the two.
parent 99e3c9be
No related branches found
Tags debian/upstream/0.6.3
No related merge requests found
Pipeline #3435 passed
......@@ -15,6 +15,40 @@ from swh.auth.django.models import OIDCUser
from swh.auth.keycloak import ExpiredSignatureError, KeycloakOpenIDConnect
def keycloak_uuid_to_django_id(keycloak_uuid: str) -> int:
"""Convert keycloak user uuid to its django integer id.
Args:
keycloak_uuid: UUID identifier of a Keycloak user
Returns:
Django integer identifier for the user
"""
return int("".join(keycloak_uuid.split("-")), 16)
def django_id_to_keycloak_uuid(django_id: int) -> str:
"""Convert django user integer id to its keycloak uuid.
Args:
django_id: Integer identifier of a django user
Returns:
Keycloak UUID identifier for the user
"""
django_hex_id = hex(django_id)[2:]
return "-".join(
[
django_hex_id[:8],
django_hex_id[8:12],
django_hex_id[12:16],
django_hex_id[16:20],
django_hex_id[20:],
]
)
def oidc_user_from_decoded_token(
decoded_token: Dict[str, Any], client_id: Optional[str] = None
) -> OIDCUser:
......@@ -32,7 +66,7 @@ def oidc_user_from_decoded_token(
# compute an integer user identifier for Django User model
# by concatenating all groups of the UUID4 user identifier
# generated by Keycloak and converting it from hex to decimal
user_id = int("".join(decoded_token["sub"].split("-")), 16)
user_id = keycloak_uuid_to_django_id(decoded_token["sub"])
# create a Django user that will not be saved to database
user = OIDCUser(
......
......@@ -5,12 +5,15 @@
from copy import copy
from datetime import datetime
import uuid
from django.test import override_settings
import pytest
from swh.auth.django.utils import (
django_id_to_keycloak_uuid,
keycloak_oidc_client,
keycloak_uuid_to_django_id,
oidc_user_from_decoded_token,
oidc_user_from_profile,
)
......@@ -130,3 +133,9 @@ def test_keycloak_oidc_client_parameters_from_django_settings():
assert kc_oidc_client.server_url == SERVER_URL
assert kc_oidc_client.realm_name == REALM_NAME
assert kc_oidc_client.client_id == CLIENT_ID
def test_django_id_to_keycloak_uuid():
keycloak_uuid = str(uuid.uuid4())
django_id = keycloak_uuid_to_django_id(keycloak_uuid)
assert django_id_to_keycloak_uuid(django_id) == keycloak_uuid
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment