diff --git a/api/users/models.py b/api/users/models.py index 7c8f48915dfc..4033b1952ce9 100644 --- a/api/users/models.py +++ b/api/users/models.py @@ -4,6 +4,7 @@ from django.conf import settings from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser +from django.core.exceptions import ImproperlyConfigured from django.core.mail import send_mail from django.db import models from django.db.models import Count, QuerySet @@ -42,6 +43,9 @@ InviteLink, ) +if settings.IS_RBAC_INSTALLED: + from rbac.models import UserRole + logger = logging.getLogger(__name__) mailer_lite = MailerLite() @@ -255,6 +259,14 @@ def get_user_organisation( "User %d is not part of organisation %d" % (self.id, organisation_id) ) + def get_user_roles(self): + if not settings.IS_RBAC_INSTALLED: + raise ImproperlyConfigured( + "RBAC is not installed. Unable to retrieve user roles." + ) + + return UserRole.objects.filter(user=self) + def get_permitted_projects( self, permission_key: str, tag_ids: typing.List[int] = None ) -> QuerySet[Project]: diff --git a/api/users/serializers.py b/api/users/serializers.py index 789b1b1412f5..73ce665ec994 100644 --- a/api/users/serializers.py +++ b/api/users/serializers.py @@ -1,3 +1,4 @@ +from django.conf import settings from djoser.serializers import UserSerializer as DjoserUserSerializer from rest_framework import serializers from rest_framework.exceptions import ValidationError @@ -5,6 +6,9 @@ from organisations.models import Organisation from organisations.serializers import UserOrganisationSerializer +if settings.IS_RBAC_INSTALLED: + from rbac.serializers import UserRoleSerializer + from .models import FFAdminUser, UserPermissionGroup @@ -56,9 +60,15 @@ class Meta: class UserListSerializer(serializers.ModelSerializer): role = serializers.SerializerMethodField(read_only=True) join_date = serializers.SerializerMethodField(read_only=True) + if settings.IS_RBAC_INSTALLED: + roles = UserRoleSerializer(many=True, read_only=True, source="get_user_roles") default_fields = ("id", "email", "first_name", "last_name", "last_login") - organisation_users_fields = ("role", "date_joined") + organisation_users_fields = ( + "role", + "date_joined", + *([] if not settings.IS_RBAC_INSTALLED else ["roles"]), + ) class Meta: model = FFAdminUser