You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.5 KiB

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 drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from erp_system.models import RolesModel, PermissionsModel, Menu
from erp_system.serializers.roles_serialzier import RolesPartialSerializer, RoleSetPermissionSerializer, RolesSerializer
class RolesViewSet(ModelViewSet):
# 整个ERP系统有一个默认存在的角色特殊 admin角色。这个角色不允许删除
"""
create:
角色--新增
角色新增, status: 201(成功), return: 新增角色信息
destroy:
角色--删除
角色删除, status: 204(成功), return: None
multiple_delete:
角色--批量删除,必传参数ids=[1,2,3,4...]
角色批量删除, status: 204(成功), return: None
update:
角色--修改,不能修改角色,只是修改角色名字。
角色修改, status: 200(成功), return: 修改后的角色信息
partial_update:
角色--(不需要)局部修改(角色批量授权),针对某一个角色批量授权,之前存在的不变,之前没有的会增加权限
角色批量授权, status: 200(成功), return: 修改后的角色信息
set_permission_to_role:
角色--单个授权一次只能授予角色一个permission也可以取消一个permission
status: 200(成功), return: 修改后的角色信息
list:
角色--获取列表
角色列表信息, status: 200(成功), return: 角色信息列表
retrieve:
查询某一个角色
查询指定ID的角色, status: 200(成功), return: 用户角色
"""
queryset = RolesModel.objects.all()
def get_serializer_class(self):
"""
不同的视图函数采用的序列化器是不一样的
:return:
"""
if self.action == 'partial_update':
return RolesPartialSerializer
elif self.action == 'set_permission_to_role':
return RoleSetPermissionSerializer
else:
return RolesSerializer
@swagger_auto_schema(method='POST', request_body=RoleSetPermissionSerializer, operation_description='单一授权或者取消单一权限')
@action(methods=['POST'], detail=False)
def set_permission_to_role(self, request, *args, **kwargs):
ser: RoleSetPermissionSerializer = self.get_serializer(data=request.data)
if ser.is_valid():
role = RolesModel.objects.get(id=ser.validated_data.get('role_id'))
permission = PermissionsModel.objects.get(id=ser.validated_data.get('permission_id'))
if ser.validated_data.get('is_create'):
# 判断给当前角色新增一个权限, 首先判断该权限所对应的父菜单权限是否已经被授予了
parent = Menu.objects.filter(id=permission.menu.id).values_list('parent', flat=True).all()
if parent:
p_permission = PermissionsModel.objects.get(menu_id=parent[0])
role.permissions.add(p_permission)
role.permissions.add(permission)
else: # 取消权限
role.permissions.remove(permission)
return Response(data=RolesSerializer(instance=role).data)
def destroy(self, request, *args, **kwargs):
if self.get_object().name == 'admin':
return Response(data={'detail': 'admin角色不可删除'}, status=status.HTTP_400_BAD_REQUEST)
else:
pass