2018-09-03 03:24:25 +00:00
|
|
|
|
# ~*~ coding: utf-8 ~*~
|
2021-04-13 07:46:49 +00:00
|
|
|
|
from collections import defaultdict
|
|
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
|
from django.utils.translation import gettext as _
|
2018-09-03 03:24:25 +00:00
|
|
|
|
from rest_framework import generics
|
2023-02-07 09:51:22 +00:00
|
|
|
|
from rest_framework.decorators import action
|
2018-09-03 03:24:25 +00:00
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
from rest_framework_bulk import BulkModelViewSet
|
|
|
|
|
|
2023-05-18 09:31:40 +00:00
|
|
|
|
from common.api import CommonApiMixin, SuggestionMixin
|
2023-05-18 13:34:19 +00:00
|
|
|
|
from common.drf.filters import AttrRulesFilterBackend
|
2023-02-07 09:51:22 +00:00
|
|
|
|
from common.utils import get_logger
|
2022-03-17 06:47:24 +00:00
|
|
|
|
from orgs.utils import current_org, tmp_to_root_org
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from rbac.models import Role, RoleBinding
|
2023-04-21 09:31:39 +00:00
|
|
|
|
from rbac.permissions import RBACPermission
|
2021-08-24 06:20:54 +00:00
|
|
|
|
from users.utils import LoginBlockUtil, MFABlockUtils
|
2021-10-21 08:16:50 +00:00
|
|
|
|
from .mixins import UserQuerysetMixin
|
2020-03-20 10:21:27 +00:00
|
|
|
|
from .. import serializers
|
2023-05-25 03:38:20 +00:00
|
|
|
|
from ..exceptions import UnableToDeleteAllUsers
|
2023-02-07 09:51:22 +00:00
|
|
|
|
from ..filters import UserFilter
|
|
|
|
|
from ..models import User
|
|
|
|
|
from ..notifications import ResetMFAMsg
|
2023-04-21 09:31:39 +00:00
|
|
|
|
from ..permissions import UserObjectPermission
|
2022-02-17 12:13:31 +00:00
|
|
|
|
from ..serializers import (
|
|
|
|
|
UserSerializer,
|
|
|
|
|
MiniUserSerializer, InviteSerializer
|
|
|
|
|
)
|
2019-01-10 03:50:08 +00:00
|
|
|
|
from ..signals import post_user_create
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
2018-09-03 03:24:25 +00:00
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
__all__ = [
|
2019-12-16 08:53:29 +00:00
|
|
|
|
'UserViewSet', 'UserChangePasswordApi',
|
2021-11-15 06:27:11 +00:00
|
|
|
|
'UserUnblockPKApi', 'UserResetMFAApi',
|
2018-09-03 03:24:25 +00:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2022-02-24 04:03:40 +00:00
|
|
|
|
class UserViewSet(CommonApiMixin, UserQuerysetMixin, SuggestionMixin, BulkModelViewSet):
|
2021-08-17 10:50:15 +00:00
|
|
|
|
filterset_class = UserFilter
|
2023-05-18 13:34:19 +00:00
|
|
|
|
extra_filter_backends = [AttrRulesFilterBackend]
|
2022-07-07 08:21:39 +00:00
|
|
|
|
search_fields = ('username', 'email', 'name')
|
2023-04-21 09:31:39 +00:00
|
|
|
|
permission_classes = [RBACPermission, UserObjectPermission]
|
2020-06-11 10:24:56 +00:00
|
|
|
|
serializer_classes = {
|
|
|
|
|
'default': UserSerializer,
|
2020-10-14 07:17:06 +00:00
|
|
|
|
'suggestion': MiniUserSerializer,
|
|
|
|
|
'invite': InviteSerializer,
|
2020-06-11 10:24:56 +00:00
|
|
|
|
}
|
2022-02-23 06:43:47 +00:00
|
|
|
|
ordering = ('name',)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
2022-02-24 04:03:40 +00:00
|
|
|
|
'match': 'users.match_user',
|
2022-02-17 12:13:31 +00:00
|
|
|
|
'invite': 'users.invite_user',
|
|
|
|
|
'remove': 'users.remove_user',
|
|
|
|
|
'bulk_remove': 'users.remove_user',
|
|
|
|
|
}
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
2019-10-18 07:05:45 +00:00
|
|
|
|
def get_queryset(self):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
queryset = super().get_queryset().prefetch_related('groups')
|
2020-11-26 02:34:27 +00:00
|
|
|
|
return queryset
|
2019-10-18 07:05:45 +00:00
|
|
|
|
|
2023-05-25 03:38:20 +00:00
|
|
|
|
def allow_bulk_destroy(self, qs, filtered):
|
|
|
|
|
is_valid = filtered.count() < qs.count()
|
|
|
|
|
if not is_valid:
|
|
|
|
|
raise UnableToDeleteAllUsers()
|
|
|
|
|
return True
|
|
|
|
|
|
2022-03-17 06:47:24 +00:00
|
|
|
|
@action(methods=['get'], detail=False, url_path='suggestions')
|
|
|
|
|
def match(self, request, *args, **kwargs):
|
|
|
|
|
with tmp_to_root_org():
|
|
|
|
|
return super().match(request, *args, **kwargs)
|
|
|
|
|
|
2023-02-22 14:20:11 +00:00
|
|
|
|
def get_serializer(self, *args, **kwargs):
|
|
|
|
|
"""重写 get_serializer,用于设置用户的角色缓存
|
|
|
|
|
放到 paginate_queryset 里面会导致 导出有问题, 因为导出的时候,没有 pager
|
|
|
|
|
"""
|
|
|
|
|
if len(args) == 1 and kwargs.get('many'):
|
|
|
|
|
queryset = self.set_users_roles_for_cache(args[0])
|
|
|
|
|
args = (queryset,)
|
|
|
|
|
return super().get_serializer(*args, **kwargs)
|
|
|
|
|
|
2020-10-10 11:05:22 +00:00
|
|
|
|
@staticmethod
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def set_users_roles_for_cache(queryset):
|
|
|
|
|
# Todo: 未来有机会用 SQL 实现
|
|
|
|
|
queryset_list = queryset
|
|
|
|
|
user_ids = [u.id for u in queryset_list]
|
|
|
|
|
role_bindings = RoleBinding.objects.filter(user__in=user_ids) \
|
|
|
|
|
.values('user_id', 'role_id', 'scope')
|
|
|
|
|
|
|
|
|
|
role_mapper = {r.id: r for r in Role.objects.all()}
|
|
|
|
|
user_org_role_mapper = defaultdict(set)
|
|
|
|
|
user_system_role_mapper = defaultdict(set)
|
|
|
|
|
|
|
|
|
|
for binding in role_bindings:
|
|
|
|
|
role_id = binding['role_id']
|
|
|
|
|
user_id = binding['user_id']
|
|
|
|
|
if binding['scope'] == RoleBinding.Scope.system:
|
|
|
|
|
user_system_role_mapper[user_id].add(role_mapper[role_id])
|
2021-03-15 06:53:19 +00:00
|
|
|
|
else:
|
2022-02-17 12:13:31 +00:00
|
|
|
|
user_org_role_mapper[user_id].add(role_mapper[role_id])
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
for u in queryset_list:
|
|
|
|
|
system_roles = user_system_role_mapper[u.id]
|
|
|
|
|
org_roles = user_org_role_mapper[u.id]
|
|
|
|
|
u.org_roles.cache_set(org_roles)
|
|
|
|
|
u.system_roles.cache_set(system_roles)
|
|
|
|
|
return queryset_list
|
2018-12-18 09:28:45 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def perform_create(self, serializer):
|
2020-08-19 09:38:21 +00:00
|
|
|
|
users = serializer.save()
|
|
|
|
|
if isinstance(users, User):
|
|
|
|
|
users = [users]
|
2022-02-17 12:13:31 +00:00
|
|
|
|
self.send_created_signal(users)
|
2020-08-19 09:38:21 +00:00
|
|
|
|
|
2019-08-12 09:05:01 +00:00
|
|
|
|
def perform_bulk_update(self, serializer):
|
2021-03-08 02:08:51 +00:00
|
|
|
|
user_ids = [
|
2019-09-12 10:56:26 +00:00
|
|
|
|
d.get("id") or d.get("pk") for d in serializer.validated_data
|
|
|
|
|
]
|
2021-03-08 02:08:51 +00:00
|
|
|
|
users = current_org.get_members().filter(id__in=user_ids)
|
2019-09-12 10:56:26 +00:00
|
|
|
|
for user in users:
|
|
|
|
|
self.check_object_permissions(self.request, user)
|
2019-08-12 09:05:01 +00:00
|
|
|
|
return super().perform_bulk_update(serializer)
|
2019-04-25 02:11:50 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def perform_bulk_destroy(self, objects):
|
|
|
|
|
for obj in objects:
|
|
|
|
|
self.check_object_permissions(self.request, obj)
|
|
|
|
|
self.perform_destroy(obj)
|
|
|
|
|
|
|
|
|
|
@action(methods=['post'], detail=False)
|
2020-10-14 07:17:06 +00:00
|
|
|
|
def invite(self, request):
|
2021-03-02 06:57:48 +00:00
|
|
|
|
if not current_org or current_org.is_root():
|
2020-10-14 07:17:06 +00:00
|
|
|
|
error = {"error": "Not a valid org"}
|
|
|
|
|
return Response(error, status=400)
|
|
|
|
|
|
|
|
|
|
serializer_cls = self.get_serializer_class()
|
2022-02-17 12:13:31 +00:00
|
|
|
|
serializer = serializer_cls(data=request.data)
|
2020-10-14 07:17:06 +00:00
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
|
validated_data = serializer.validated_data
|
2021-04-13 07:46:49 +00:00
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
users = validated_data['users']
|
|
|
|
|
org_roles = validated_data['org_roles']
|
|
|
|
|
for user in users:
|
|
|
|
|
user.org_roles.set(org_roles)
|
2020-10-14 07:17:06 +00:00
|
|
|
|
return Response(serializer.data, status=201)
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
@action(methods=['post'], detail=True)
|
2021-03-15 06:53:19 +00:00
|
|
|
|
def remove(self, request, *args, **kwargs):
|
|
|
|
|
instance = self.get_object()
|
|
|
|
|
instance.remove()
|
|
|
|
|
return Response(status=204)
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
@action(methods=['post'], detail=False, url_path='remove')
|
2021-03-15 06:53:19 +00:00
|
|
|
|
def bulk_remove(self, request, *args, **kwargs):
|
|
|
|
|
qs = self.get_queryset()
|
|
|
|
|
filtered = self.filter_queryset(qs)
|
|
|
|
|
|
|
|
|
|
for instance in filtered:
|
|
|
|
|
instance.remove()
|
|
|
|
|
return Response(status=204)
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
def send_created_signal(self, users):
|
|
|
|
|
if not isinstance(users, list):
|
|
|
|
|
users = [users]
|
|
|
|
|
for user in users:
|
|
|
|
|
post_user_create.send(self.__class__, user=user)
|
|
|
|
|
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
2021-08-02 03:53:08 +00:00
|
|
|
|
class UserChangePasswordApi(UserQuerysetMixin, generics.UpdateAPIView):
|
2019-08-21 12:27:21 +00:00
|
|
|
|
serializer_class = serializers.ChangeUserPasswordSerializer
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
|
def perform_update(self, serializer):
|
|
|
|
|
user = self.get_object()
|
|
|
|
|
user.password_raw = serializer.validated_data["password"]
|
|
|
|
|
user.save()
|
|
|
|
|
|
|
|
|
|
|
2019-10-18 07:05:45 +00:00
|
|
|
|
class UserUnblockPKApi(UserQuerysetMixin, generics.UpdateAPIView):
|
2019-08-21 12:27:21 +00:00
|
|
|
|
serializer_class = serializers.UserSerializer
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
|
def perform_update(self, serializer):
|
|
|
|
|
user = self.get_object()
|
|
|
|
|
username = user.username if user else ''
|
2021-04-08 04:47:49 +00:00
|
|
|
|
LoginBlockUtil.unblock_user(username)
|
|
|
|
|
MFABlockUtils.unblock_user(username)
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
|
|
2021-11-15 06:27:11 +00:00
|
|
|
|
class UserResetMFAApi(UserQuerysetMixin, generics.RetrieveAPIView):
|
2019-08-21 12:27:21 +00:00
|
|
|
|
serializer_class = serializers.ResetOTPSerializer
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
|
|
|
|
user = self.get_object() if kwargs.get('pk') else request.user
|
|
|
|
|
if user == request.user:
|
|
|
|
|
msg = _("Could not reset self otp, use profile reset instead")
|
2021-11-25 09:47:18 +00:00
|
|
|
|
return Response({"error": msg}, status=400)
|
2021-10-21 08:16:50 +00:00
|
|
|
|
|
2021-11-15 06:27:11 +00:00
|
|
|
|
backends = user.active_mfa_backends_mapper
|
2021-11-23 07:11:52 +00:00
|
|
|
|
for backend in backends.values():
|
2021-11-15 06:27:11 +00:00
|
|
|
|
if backend.can_disable():
|
|
|
|
|
backend.disable()
|
2021-08-24 06:20:54 +00:00
|
|
|
|
|
2021-11-15 06:27:11 +00:00
|
|
|
|
ResetMFAMsg(user).publish_async()
|
2019-09-27 06:18:51 +00:00
|
|
|
|
return Response({"msg": "success"})
|