UnisKB/apps/system_manage/views/platform_access.py

198 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
from common.auth import TokenAuth
from common.result import result
from common.log.log import log
from system_manage.models.platform_access import PlatformRole, PlatformRoleMember, PlatformGrant
from system_manage import platform_access as access
from users.models import User
class RoleInput(serializers.ModelSerializer):
modules = serializers.ListField(child=serializers.ChoiceField(choices=list(access.MODULES)), required=False)
user_ids = serializers.ListField(child=serializers.UUIDField(), required=False, write_only=True)
class Meta:
model = PlatformRole
fields = ['name', 'description', 'enabled', 'modules', 'user_ids']
class GrantInput(serializers.ModelSerializer):
legacy_id = serializers.CharField(required=False, write_only=True)
actions = serializers.ListField(child=serializers.ChoiceField(choices=list(access.ACTIONS)), allow_empty=False)
class Meta:
model = PlatformGrant
fields = ['subject_type', 'subject_id', 'resource_type', 'target', 'actions', 'expires_at', 'legacy_id']
validators = []
def validate(self, data):
if data['resource_type'] == 'FEATURE':
raise ValidationError('暂不支持功能授权')
subject = data['subject_type']
key = data.get('subject_id', '')
if subject == 'ALL':
if key:
raise ValidationError('公共授权无需指定用户或角色')
else:
try:
key = str(serializers.UUIDField().run_validation(key))
except serializers.ValidationError:
raise ValidationError('授权对象无效')
if subject == 'ROLE':
exists = PlatformRole.objects.filter(pk=key).exists()
else:
from users.serializers.user import exclude_unactivated_users
exists = exclude_unactivated_users(User.objects.filter(pk=key)).exists()
if not exists:
raise ValidationError('授权对象不存在或未激活')
data['subject_id'] = key
access.validate_target(data['resource_type'], data['target'])
if data['resource_type'] == 'FEATURE' and set(data['actions']) - {'VIEW', 'USE'}:
raise ValidationError('功能仅支持查看、使用权限')
if data['resource_type'] == 'MODULE' and set(data['actions']) != {'VIEW'}:
raise ValidationError('功能入口仅支持查看权限')
if data.get('expires_at') and data['expires_at'] <= timezone.now():
raise ValidationError('有效期须晚于当前时间')
data['actions'] = sorted(set(data['actions']))
return data
def role_data(role):
return {'id': str(role.id), 'name': role.name, 'description': role.description,
'enabled': role.enabled, 'is_default': role.is_default, 'modules': role.modules,
'is_builtin': str(role.id) in (access.DEFAULT_ROLE_ID, access.ADMIN_ROLE_ID),
'is_admin_role': str(role.id) == access.ADMIN_ROLE_ID,
'user_ids': [str(pk) for pk in role.members.values_list('user_id', flat=True)]}
def valid_users(ids):
ids = set(ids)
# Membership can be prepared for a disabled account; authentication still blocks it.
if User.objects.filter(pk__in=ids).count() != len(ids):
raise ValidationError('用户不存在')
return ids
class AccessView(APIView):
authentication_classes = [TokenAuth]
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
access.require_admin(request.user)
def get(self, request):
from users.serializers.user import exclude_unactivated_users
users = list(exclude_unactivated_users(User.objects.all()).values('id', 'username', 'nick_name', 'role'))
return result.success({'roles': [role_data(r) for r in PlatformRole.objects.order_by('created_at')],
'users': users, 'resources': access.catalog(), 'modules': access.MODULES, 'actions': access.ACTIONS,
'grants': access.authorization_rows()})
class RoleView(AccessView):
http_method_names = ['post', 'delete', 'options']
@log(menu='Role management', operate='Save role')
@transaction.atomic
def post(self, request, pk=None):
PlatformRole.objects.select_for_update().get(pk=access.ADMIN_ROLE_ID)
role = get_object_or_404(PlatformRole.objects.select_for_update(), pk=pk) if pk else None
serializer = RoleInput(instance=role, data=request.data)
serializer.is_valid(raise_exception=True)
data = dict(serializer.validated_data)
members = data.pop('user_ids', None)
if role and role.is_default and data.get('enabled', True) is False:
raise ValidationError('默认角色不可停用')
if role and str(role.id) == access.ADMIN_ROLE_ID:
if any(data.get(key, getattr(role, key)) != getattr(role, key) for key in ('name', 'enabled', 'modules')):
raise ValidationError('系统管理员的名称、权限和启用状态不可修改')
if members is not None:
members = valid_users(members)
if role is None:
role = PlatformRole.objects.create(**data)
else:
for key, value in data.items():
setattr(role, key, value)
role.save()
if members is not None:
existing = set(role.members.values_list('user_id', flat=True))
for user_id in sorted(existing | members, key=str):
ids = {str(pk) for pk in PlatformRoleMember.objects.filter(user_id=user_id).values_list('role_id', flat=True)}
if user_id in members:
ids.add(str(role.id))
else:
ids.discard(str(role.id))
access.assign_roles(user_id, ids, request.user.id)
return result.success(role_data(role))
@log(menu='Role management', operate='Delete role')
@transaction.atomic
def delete(self, request, pk):
role = get_object_or_404(PlatformRole.objects.select_for_update(), pk=pk)
if role.is_default or str(role.id) == access.ADMIN_ROLE_ID:
raise ValidationError('内置角色不可删除')
PlatformGrant.objects.filter(subject_type='ROLE', subject_id=str(role.id)).delete()
role.delete()
return result.success(True)
class GrantsView(AccessView):
http_method_names = ['post', 'delete', 'options']
@log(menu='Resource authorization', operate='Save grants')
@transaction.atomic
def post(self, request):
# Validate the entire batch before changing anything.
data = request.data.get('grants')
if not isinstance(data, list) or not 1 <= len(data) <= 500:
raise ValidationError('请选择授权资源(最多500项)')
serializer = GrantInput(data=data, many=True)
serializer.is_valid(raise_exception=True)
for item in serializer.validated_data:
values = dict(item)
legacy_id = values.pop('legacy_id', None)
if legacy_id:
access.remove_compatibility_grant(legacy_id, values)
elif values['resource_type'] == 'MODULE' and values['subject_type'] in ('ROLE', 'USER'):
key = ('role-menu:' if values['subject_type'] == 'ROLE' else 'user-menu:') + values['subject_id'] + ':' + values['target']
if any(str(r['id']) == key for r in access.authorization_rows()):
access.remove_compatibility_grant(key, values)
subject_type = values['subject_type']
# Serialize with role deletion so no dangling role grant is created.
if subject_type == 'ROLE':
get_object_or_404(PlatformRole.objects.select_for_update(), pk=values['subject_id'])
defaults = {k: values.pop(k, None) for k in ('actions', 'expires_at')}
PlatformGrant.objects.update_or_create(workspace_id='default', **values,
defaults={**defaults, 'granted_by': request.user})
return result.success(True)
@log(menu='Resource authorization', operate='Revoke grant')
@transaction.atomic
def delete(self, request, pk):
if ':' in str(pk):
access.remove_compatibility_grant(str(pk))
return result.success(True)
pk = serializers.UUIDField().run_validation(pk)
get_object_or_404(PlatformGrant, pk=pk).delete()
return result.success(True)
class UserAccessView(AccessView):
http_method_names = ['get', 'put', 'options']
def get(self, request, user_id):
user = get_object_or_404(User, pk=user_id)
data = access.effective_detail(user)
data['user_id'] = str(user.id)
data['role_ids'] = list({str(pk) for pk in PlatformRoleMember.objects.filter(user=user).values_list('role_id', flat=True)} | {access.DEFAULT_ROLE_ID})
return result.success(data)
@log(menu='Role management', operate='Assign user roles')
@transaction.atomic
def put(self, request, user_id):
ids = serializers.ListField(child=serializers.UUIDField(), max_length=100).run_validation(request.data.get('role_ids'))
get_object_or_404(User, pk=user_id)
access.assign_roles(user_id, ids, request.user.id)
return self.get(request, user_id)