**记住每一个url都是一个权限**
注册
可插拔试的权限,可以先写其他的逻辑,在最后再把权限加上
将rbac组件拷贝到项目上,注册项目
修改表结构
将写好的用户表对rbac的User表进行一对一的关系建立,修改完成后做数据库迁移:
记住null等于true..后面再添加用户
将权限组件放在中间件上
MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'rbac.service.rbac.ValidPermission', ]
写登录的视图函数:
切记1.将user_id写入session中
2.登录成功之后需要注册权限
if user: request.session['user_id']=user.id initial_session(user,request)
在所展示的页面上的html里添加菜单:
{% load my_tags %} <div class="menu"> {% get_menu request %} </div> <div class="content">
将权限的数据录入到数据库中
注册权限的代码逻辑:
def initial_session(user,request): '''注册权限和菜单权限''' permissions = user.roles.all().values("permissions__url","permissions__group_id","permissions__action").distinct() permission_dict={} for item in permissions: gid=item.get('permissions__group_id') if not gid in permission_dict: permission_dict[gid]={ "urls":[item["permissions__url"],], "actions":[item["permissions__action"],] } else: permission_dict[gid]["urls"].append(item["permissions__url"]) permission_dict[gid]["actions"].append(item["permissions__action"]) request.session['permission_dict']=permission_dict # 注册菜单权限 permissions = user.roles.all().values("permissions__url","permissions__action","permissions__title").distinct() menu_permission_list=[] for item in permissions: if item["permissions__action"]=="list": menu_permission_list.append((item["permissions__url"],item["permissions__title"])) request.session["menu_permission_list"]=menu_permission_list
权限中间件:
from django.shortcuts import HttpResponse,redirect class ValidPermission(MiddlewareMixin): def process_request(self,request): # 当前访问路径 current_path = request.path_info # 检查是否属于白名单 valid_url_list=["/login/","/reg/","/admin/.*"] for valid_url in valid_url_list: ret=re.match(valid_url,current_path) if ret: return None # 校验是否登录 user_id=request.session.get("user_id") if not user_id: return redirect("/login/") permission_dict=request.session.get("permission_dict") for item in permission_dict.values(): urls=item['urls'] for reg in urls: reg="^%s$"%reg ret=re.match(reg,current_path) if ret: request.actions=item['actions'] return None return HttpResponse("没有访问权限!")
request.actions=item['actions'] 可以在相应的视图中,进行判断是否要显示增加或者删除按钮等操作