对于权限管理,不单单的只是控制能不能访问的路径,而且还需要根据用户的权限,当用户某个页面时,在页面上展示什么,比如有些用户能访问首页,但是没有添加用户的权限,这就不能将添加按钮展现在首页,而对于具有添加用户权限的用户则需要将添加用户的按钮显示在首页上
- 1.在访问列表页面时,是否需要判断;有无添加权限,有无编辑权限;
在rbac下的models中添加Group类在权限表中添加code字段和外键group
class Group(models.Model):
"""
权限组
"""
caption = models.CharField(verbose_name='组名称',max_length=16)
class Permission(models.Model):
"""
权限表
"""
title = models.CharField(verbose_name='标题',max_length=32)
url = models.CharField(verbose_name="含正则URL",max_length=64)
is_menu = models.BooleanField(verbose_name="是否是菜单")
code = models.CharField(verbose_name="代码",max_length=16)
group = models.ForeignKey(verbose_name='所属组',to="Group")
class Meta:
verbose_name_plural = "权限表"
def __str__(self):
return self.title
2.在rbac/service/init_permission.py/init_permission类中进行修改
结构化数据模型,方便以后操作
data = {
1: {
'codes': ['list','add','edit','del'],
'urls':[
/userinfo/,
/userinfo/add/,
/userinfo/edit/(\d+)/,
/userinfo/del/(\d+)/,
]
},
2: {
'codes': ['list','add','edit','del'],
'urls':[
/userinfo/,
/userinfo/add/,
/userinfo/edit/(\d+)/,
/userinfo/del/(\d+)/,
]
},
}
permission_list = user.roles.values('permissions__title',
"permissions__code",
'permissions__url',
'permissions__is_menu',
"permissions__group__id",
).distinct()
result={}
for item in permission_list:
groupid=item["permissions__group__id"]
code=item["permissions__code"]
url=item["permissions__url"]
if groupid in result:
result[groupid]["codes"].append(code)
result[groupid]["urls"].append(url)
else:
result[groupid]={
"codes":[code,],
"urls":[url,]
}
print(result)
request.session[settings.PERMISSIONS_URL_DICT_KEY] = result
3.对中间件进行修改
import re
from django.shortcuts import redirect,HttpResponse
from django.conf import settings
class MiddlewareMixin(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__()
def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
class RbacMiddleware(MiddlewareMixin):
def process_request(self,request):
# 1. 获取当前请求的URL
# request.path_info
# 2. 获取Session中保存当前用户的权限
# request.session.get("permission_url_list')
current_url = request.path_info
# 当前请求不需要执行权限验证
for url in settings.VALID_URL:
if re.match(url,current_url):
return None
permission_dict = request.session.get(settings.PERMISSION_URL_DICT_KEY)
if not permission_dict:
return redirect('/login/')
flag = False
for group_id,code_url in permission_dict.items():
for db_url in code_url['urls']:
regax = "^{0}$".format(db_url)
if re.match(regax, current_url):
request.permission_code_list = code_url['codes']
flag = True
break
if flag:
break
if not flag:
return HttpResponse('无权访问')
rbac.py
4.对views进行操作,是否页面上显示功能按钮:
方法1·:在模块中进行判断
{% if "add/edit/del" in request.permission_code_list %}
添加/编辑/删除
{% endif%}
在模块中进行判断
{% if pagepermission.has_add %}
{% endif %}