فهرست منبع

实现根据当前登入用户来获取对应角色的菜单

DYaiu 4 سال پیش
والد
کامیت
3d4514e58d
1فایلهای تغییر یافته به همراه18 افزوده شده و 1 حذف شده
  1. 18 1
      basic/views.py

+ 18 - 1
basic/views.py

@@ -1,10 +1,12 @@
+from django.contrib.auth.models import Group
 from django.db.models import Sum
 from rest_framework import status
 from rest_framework.response import Response
 from rest_framework.views import APIView
 from rest_framework.viewsets import ModelViewSet
+from rolepermissions.roles import get_user_roles
 
-from basic.models import Menu
+from basic.models import Menu, RouterMenu, GroupRouterMenu
 from basic.serializer import MenuSerializer, RouterMenuSerializer, GroupRouterMenuSerializer
 from payment.models import Payment
 
@@ -28,6 +30,21 @@ class GroupRouterMenuView(APIView):
     serializer_class = GroupRouterMenuSerializer
     pagination_class = None
 
+    def get(self, request):
+        user = request.user
+
+        if user.is_superuser:
+            return Response(RouterMenu.objects.all().values(), status=status.HTTP_200_OK)
+
+        role = get_user_roles(user)
+        # 根据当前用户的角色获取角色id
+        roleArr = Group.objects.filter(name__in=[r.get_name() for r in role]).all().values('id')
+        # 根据角色id查到所有相关的角色与菜单对应的记录
+        menu = GroupRouterMenu.objects.filter(group_id__in=[arr['id'] for arr in roleArr]).all()
+        # 生成菜单列表
+        data = [RouterMenuSerializer(m.menu).data for m in menu]
+        return Response(data, status=status.HTTP_200_OK)
+
 
 class RouterMenuView(ModelViewSet):
     queryset = Menu.objects.all()