The Seven Year Itch.

MENU

Django 实现权限分组(权限控制实现 第三方满足不了需求)

November 13, 2017 • Read: 356 • 数据库,Python,MAC

  1. 在Django项目中新建permissions
  2. 引入库

from django.core.exceptions import ObjectDoesNotExist
from rest_framework.permissions import BasePermission
from xxx import models

实现代码

class CanAccess(BasePermission):
    def has_permission(self, request, view):
        kong_user = request.META.get(HEAD_KEY, "")
        pk = view.kwargs.get('pk', 0)
        url_method, url_path = request.method, request.path
        try:
            # 获取当前用户
            action_user = models.TbUser.objects.get(id=kong_user)
            # 获取当前用户所在的所有用户组
            action_groups = action_user.ugroups.all()
            # 遍历所有用户组具有的权限
            can_access_roles = []
            for group in action_groups:
                for role in group.roles.all().values_list("method", "link"):
                    can_access_roles.append(tuple(str(item) for item in role))
            if (str(url_method), str(url_path)) in can_access_roles:
                return True
            else:
                return False
        except Exception, e:
            return False

表的设计
表的设计

Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code