一、创建rbac的app
python manage.py startapp rbac 注入;settings.py的INSTALLED_APPS中
二、创建rbac表,在rbac的models.py中添加
from django.db import models # 权限表 class Permission(models.Model): title = models.CharField(verbose_name='标题', max_length=32) url = models.CharField(verbose_name='含正则的URL', max_length=128) is_menu = models.BooleanField(verbose_name='是否可做菜单',default=False) icon = models.CharField(max_length=32,null=True,blank=True) def __str__(self): return self.title # 角色 class Role(models.Model): title = models.CharField(verbose_name='角色名称', max_length=32) permissions = models.ManyToManyField(verbose_name='拥有的所有权限', to='Permission', blank=True) def __str__(self): return self.title # 用户表 class UserInfo(models.Model): name = models.CharField(verbose_name='用户名', max_length=32) password = models.CharField(verbose_name='密码', max_length=200) email = models.CharField(verbose_name='邮箱', max_length=32) roles = models.ManyToManyField(verbose_name='拥有的所有角色', to='Role', blank=True) def __str__(self): return self.name
创建数据库结构 python.exe manage.py makemigrations && python.exe manage.py migrate
三、创建权限检查表,在rbac下创建middleware文件,在该目录下创建rbac.py文件
from django.utils.deprecation import MiddlewareMixin from xyglweb import settings from django.shortcuts import redirect, render import re class RbacMiddleware(MiddlewareMixin): def process_request(self,request): # 1、获取当前请求的url current_url = request.path_info #1.5 添加白名单 for reg in settings.VAILD_URL: if re.match(reg,current_url): return None #2、获取当前用户的session中的所有权限 permission_list = request.session.get(settings.PERMISSION_SESSION_KEY) role_list = request.session.get(settings.ROLE_SESSION_KEY) if not permission_list: return redirect('/portal/') #3、进行权限校验 print(current_url) print(role_list,'RRRRRRRRRRRRRRR') # print(permission_list) flag = False for item in permission_list: reg = "^%s$" % item.get('permissions__url') if re.match(reg,current_url): flag = True break if not flag: return render(request,'error/403.html')
注入;settings.py的MIDDLEWARE中 “'rbac.middleware.rbac.RbacMiddleware',”
四、在settings中配置变量
PERMISSION_SESSION_KEY = "permission_list" MENU_SESSION_KEY = "menu_list" ROLE_SESSION_KEY = "role_list" #1.5 添加白名单 VAILD_URL = [ '^/admin/*', '^/portal/$', '^/$', '/clean_cookie/', # '/ywworkportal/','/addywwork/','/upload/','/yunweiticx/','/addxgg1port/','/delgg1/','/article_detail/','/editblog/','/delblog/','/addxgg2port/','/delgg2/', # '/addxgg3port/','/delgg3/','/addxgg4port/','/delgg4/', ]
五、在rbac的admin.py中注册
from django.contrib import admin # Register your models here. from rbac import models class PermissionAdmin(admin.ModelAdmin): list_display = ['title','url','is_menu','icon'] # list_editable = ['url'] class RoleAdmin(admin.ModelAdmin): list_display = ['title'] class UserInfoAdmin(admin.ModelAdmin): list_display = ['name','email'] admin.site.register(models.Permission,PermissionAdmin) admin.site.register(models.Role,RoleAdmin) admin.site.register(models.UserInfo,UserInfoAdmin)