Skip to content

Commit

Permalink
Adds third-party auth support to the app.
Browse files Browse the repository at this point in the history
This is indended to be reviewed and merged after #96 as that has the required infrastructure support. It's not strictly required for this, though.

This adds:
- Authentication backend pieces for retrieving Keycloak user data
- Test routes for Keycloak integration
- Pulls in some remaining necessary libraries (fsm, reversion, oauth)
  • Loading branch information
jkachel committed Feb 28, 2024
1 parent cb1908b commit 77ec839
Show file tree
Hide file tree
Showing 16 changed files with 726 additions and 84 deletions.
Empty file added authentication/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions authentication/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""Django Admin for authentication app"""

from django.contrib import admin

from authentication import models

admin.site.register(models.KeycloakUserToken)
admin.site.register(models.KeycloakAdminToken)
150 changes: 150 additions & 0 deletions authentication/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""API functions for authentication."""

import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from oauthlib.oauth2 import (
BackendApplicationClient,
InvalidGrantError,
TokenExpiredError,
)
from requests_oauthlib import OAuth2Session

from authentication.models import KeycloakAdminToken
from unified_ecommerce.celery import app

User = get_user_model()
log = logging.getLogger(__name__)


def keycloak_session_init(url, **kwargs):
"""
Initialize a Keycloak session.
This is a helper function that will initialize a Keycloak session with the
provided URL. It will also handle refreshing the token if it has expired.
Args:
url (str): The Keycloak admin URL.
**kwargs: Additional arguments to pass to the OAuth2Session initializer.
Returns:
None, or dict of data returned.
"""

token_url = (
f"{settings.KEYCLOAK_ADMIN_URL}/auth/realms/master/"
"protocol/openid-connect/token"
)
client = BackendApplicationClient(client_id=settings.KEYCLOAK_ADMIN_CLIENT_ID)

auto_refresh_kwargs = {
"client_id": settings.KEYCLOAK_ADMIN_CLIENT_ID,
"client_secret": settings.KEYCLOAK_ADMIN_CLIENT_SECRET,
}

def update_token(token):
log_str = f"Refreshing Keycloak token {token}"
log.warning(log_str)
KeycloakAdminToken.objects.all().delete()
KeycloakAdminToken.objects.create(
authorization_token=token.get("access_token"),
refresh_token=token.get("refresh_token", None),
authorization_token_expires_in=token.get("access_token_expires_in", 60),
refresh_token_expires_in=token.get("refresh_token_expires_in", 60),
)

def check_for_token():
token = KeycloakAdminToken.latest()

if not token:
this_dumb_message_because_ruff_is_annoying = "No token found"
raise TokenExpiredError(this_dumb_message_because_ruff_is_annoying)

return token

# Note: we call get_user_info here in both the try and the except because you won't
# get a token error until you attempt to make a request.
try:
token = check_for_token()

log_str = f"Trying to start up a session with token {token.token_formatted}"
log.warning(log_str)

session = OAuth2Session(
client=client,
token=token.token_formatted,
auto_refresh_url=token_url,
auto_refresh_kwargs=auto_refresh_kwargs,
token_updater=update_token,
)

keycloak_info = session.get(url, **kwargs).json()
except (InvalidGrantError, TokenExpiredError) as ige:
log_str = f"Token error, trying to get a new token: {ige}"
log.warning(log_str)

session = OAuth2Session(client=client)
token = session.fetch_token(
token_url=token_url,
client_id=settings.KEYCLOAK_ADMIN_CLIENT_ID,
client_secret=settings.KEYCLOAK_ADMIN_CLIENT_SECRET,
verify=False,
)

update_token(token)
session = OAuth2Session(client=client, token=token)
keycloak_info = session.get(url, **kwargs).json()

log_str = f"Keycloak info returned: {keycloak_info}"
log.warning(log_str)

return keycloak_info


def keycloak_get_user(user: User):
"""Get a user from Keycloak."""

userinfo_url = (
f"{settings.KEYCLOAK_ADMIN_URL}/auth/admin/"
f"realms/{settings.KEYCLOAK_ADMIN_REALM}/users/"
)

log_str = f"Trying to get user info for {user.username}"
log.warning(log_str)

if user.keycloak_user_tokens.exists():
params = {"id": user.keycloak_user_tokens.first().keycloak_id}
else:
params = {"email": user.username}

userinfo = keycloak_session_init(userinfo_url, verify=False, params=params)

if len(userinfo) == 0:
log.warning("Keycloak didn't return anything")
return None

return userinfo[0]


@app.task
def keycloak_update_user_account(user: int):
"""Update the user account using info from Keycloak asynchronously."""

user = User.objects.get(id=user)

keycloak_user = keycloak_get_user(user)

if keycloak_user is None:
return

user.first_name = keycloak_user["firstName"]
user.last_name = keycloak_user["lastName"]
user.email = keycloak_user["email"]
user.username = keycloak_user["id"]
user.save()

user.keycloak_user_tokens.all().delete()
user.keycloak_user_tokens.create(keycloak_id=keycloak_user["id"])
user.save()
10 changes: 10 additions & 0 deletions authentication/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""App initialization for authentication"""

from django.apps import AppConfig


class AuthenticationConfig(AppConfig):
"""Config for the authentication app"""

default_auto_field = "django.db.models.BigAutoField"
name = "authentication"
87 changes: 87 additions & 0 deletions authentication/backends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""User backends for authentication."""

import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import RemoteUserBackend

from authentication.api import keycloak_session_init

log = logging.getLogger(__name__)

User = get_user_model()


class KeycloakRemoteUserBackend(RemoteUserBackend):
"""
Backend for user auth that uses Keycloak to resolve the user's email address.
The RemoteUserBackend mostly covers what we want; however, the
X-Forwarded-User is always an email address, and users can change those. So, we
need to first hit the Keycloak API to figure out what their UUID is and create the
user with that instead.
"""

def authenticate(self, request, remote_user):
"""Authenticate the user, using Keycloak to grab their ID first."""

log_str = f"KeycloakRemoteUserBackend is running for {remote_user}"
log.warning(log_str)

userinfo_url = (
f"{settings.KEYCLOAK_ADMIN_URL}/auth/admin/"
f"realms/{settings.KEYCLOAK_ADMIN_REALM}/users/"
)

if not remote_user:
log.warning("No remote_user provided")
return None

userinfo = keycloak_session_init(
userinfo_url, verify=False, params={"email": remote_user}
)

if len(userinfo) == 0:
log.warning("Keycloak didn't return anything")
# User may have changed their email, so let's see if we can find an
# existing user

existing_user = User.objects.get(email=remote_user)

if existing_user is not None:
log_str = (
f"Found existing user {existing_user}, trying to get "
"Keycloak info for them"
)
log.warning(log_str)
userinfo = [
keycloak_session_init(
f"{userinfo_url}{existing_user.username}/", verify=False
)
]

if len(userinfo) == 0:
log_str = (
"Keycloak still returned nothing for ID "
f"{existing_user.username}, so giving up."
)
log.warning(log_str)
return None
else:
log.warning(
"Keycloak still returned nothing and we didn't find a user to"
" check, so giving up."
)
return None

authenticated_user = super().authenticate(request, userinfo[0]["id"])

if authenticated_user is not None:
# We might as well go ahead and update the record here too.
authenticated_user.email = userinfo[0]["email"]
authenticated_user.first_name = userinfo[0]["firstName"]
authenticated_user.last_name = userinfo[0]["lastName"]
authenticated_user.save()

return authenticated_user
35 changes: 35 additions & 0 deletions authentication/migrations/0001_add_keycloak_token_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Generated by Django 4.2.9 on 2024-01-31 21:30

from django.db import migrations, models


class Migration(migrations.Migration):
initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="KeycloakAdminToken",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created_on", models.DateTimeField(auto_now_add=True)),
("updated_on", models.DateTimeField(auto_now=True)),
("authorization_token", models.TextField()),
("refresh_token", models.TextField(blank=True)),
("authorization_token_expires_in", models.IntegerField()),
("refresh_token_expires_in", models.IntegerField(null=True)),
],
options={
"abstract": False,
},
),
]
48 changes: 48 additions & 0 deletions authentication/migrations/0002_add_keycloak_user_info_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Generated by Django 4.2.9 on 2024-02-01 15:52

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("authentication", "0001_add_keycloak_token_table"),
]

operations = [
migrations.CreateModel(
name="KeycloakUserToken",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created_on", models.DateTimeField(auto_now_add=True)),
("updated_on", models.DateTimeField(auto_now=True)),
(
"keycloak_id",
models.CharField(
blank=True, default=None, max_length=255, null=True, unique=True
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="keycloak_user_tokens",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
]
Empty file.
Loading

0 comments on commit 77ec839

Please sign in to comment.