2023-02-02 10:09:31 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2021-08-17 10:50:15 +00:00
|
|
|
from django_filters import rest_framework as filters
|
2020-07-06 03:14:20 +00:00
|
|
|
|
2021-08-17 10:50:15 +00:00
|
|
|
from common.drf.filters import BaseFilterSet
|
2023-02-02 10:09:31 +00:00
|
|
|
from common.utils import is_uuid
|
2024-04-03 07:48:40 +00:00
|
|
|
from rbac.models import Role, OrgRoleBinding, SystemRoleBinding
|
2023-02-02 10:09:31 +00:00
|
|
|
from users.models.user import User
|
2024-04-03 07:48:40 +00:00
|
|
|
from orgs.utils import current_org
|
2021-08-17 10:50:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
class UserFilter(BaseFilterSet):
|
2023-02-02 10:09:31 +00:00
|
|
|
system_roles = filters.CharFilter(method='filter_system_roles')
|
|
|
|
org_roles = filters.CharFilter(method='filter_org_roles')
|
2023-04-21 07:35:56 +00:00
|
|
|
groups = filters.CharFilter(field_name="groups__name", lookup_expr='exact')
|
2023-05-29 07:30:06 +00:00
|
|
|
group_id = filters.CharFilter(field_name="groups__id", lookup_expr='exact')
|
|
|
|
exclude_group_id = filters.CharFilter(
|
|
|
|
field_name="groups__id", lookup_expr='exact', exclude=True
|
|
|
|
)
|
2021-08-17 10:50:15 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = User
|
|
|
|
fields = (
|
2023-05-29 07:30:06 +00:00
|
|
|
'id', 'username', 'email', 'name',
|
|
|
|
'groups', 'group_id', 'exclude_group_id',
|
|
|
|
'source', 'org_roles', 'system_roles', 'is_active',
|
2021-08-17 10:50:15 +00:00
|
|
|
)
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
@staticmethod
|
2024-04-03 07:48:40 +00:00
|
|
|
def _get_role(value):
|
2023-02-02 10:09:31 +00:00
|
|
|
from rbac.builtin import BuiltinRole
|
|
|
|
roles = BuiltinRole.get_roles()
|
|
|
|
for role in roles.values():
|
|
|
|
if _(role.name) == value:
|
|
|
|
return role
|
|
|
|
|
|
|
|
if is_uuid(value):
|
|
|
|
return Role.objects.filter(id=value).first()
|
|
|
|
else:
|
|
|
|
return Role.objects.filter(name=value).first()
|
|
|
|
|
2024-04-03 07:48:40 +00:00
|
|
|
def _filter_roles(self, queryset, value, scope):
|
|
|
|
role = self._get_role(value)
|
2023-02-02 10:09:31 +00:00
|
|
|
if not role:
|
|
|
|
return queryset.none()
|
2024-04-03 07:48:40 +00:00
|
|
|
|
|
|
|
rb_model = SystemRoleBinding if scope == Role.Scope.system.value else OrgRoleBinding
|
|
|
|
user_ids = rb_model.objects.filter(role_id=role.id).values_list('user_id', flat=True)
|
|
|
|
queryset = queryset.filter(id__in=user_ids).distinct()
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
def filter_system_roles(self, queryset, name, value):
|
|
|
|
queryset = self._filter_roles(queryset=queryset, value=value, scope=Role.Scope.system.value)
|
2022-02-17 12:13:31 +00:00
|
|
|
return queryset
|
|
|
|
|
2023-02-02 10:09:31 +00:00
|
|
|
def filter_org_roles(self, queryset, name, value):
|
2024-04-03 07:48:40 +00:00
|
|
|
queryset = self._filter_roles(queryset=queryset, value=value, scope=Role.Scope.org.value)
|
2022-02-17 12:13:31 +00:00
|
|
|
return queryset
|