ljg.sh/ljg/core/auth.py

51 lines
1.5 KiB
Python
Raw Normal View History

2023-08-10 21:41:11 +02:00
from django.conf import settings
from django.contrib.auth.models import Permission
from django.db import transaction
2023-10-11 16:15:15 +02:00
from mozilla_django_oidc.auth import (
OIDCAuthenticationBackend as BaseOIDCAuthenticationBackend,
)
2023-08-10 21:41:11 +02:00
from .models import OIDCUser
def get_permissions(claims):
return Permission.objects.filter(
codename__in=claims.get("resource_access")[settings.OIDC_RP_CLIENT_ID]["roles"]
)
class OIDCAuthenticationBackend(BaseOIDCAuthenticationBackend):
@transaction.atomic
def create_user(self, claims):
user = self.UserModel.objects.create_user(
claims.get("preferred_username"), claims.get("email")
)
user.first_name = claims.get("given_name")
user.last_name = claims.get("family_name")
user.user_permissions.set(get_permissions(claims))
user.save()
OIDCUser.objects.create(uuid=claims.get("sub"), user=user)
return user
def update_user(self, user, claims):
user.user_permissions.set(get_permissions(claims))
user.save()
return user
def filter_users_by_claims(self, claims):
uuid = claims.get("sub")
if not uuid:
return self.UserModel.objects.none()
try:
oidc_user = OIDCUser.object.get(uuid=uuid)
return [oidc_user.user]
except OIDCUser.DoesNotExist:
return self.UserModel.objects.none()
def verify_claims(self, claims):
return settings.OIDC_RP_CLIENT_ID in claims.get("resource_access")