python项目结束后权限管理配置
一、创建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)
六、登录用户成功后调用权限检查
from rbac.services.init_permission import init_preimssion
def login(request):
try:
if request.method == 'GET':
return render(request, 'login.html')
else:
user = request.POST.get('name')
pwd = request.POST.get('password')
pwd1 = make_password(pwd,'hongjun')
obj = models.UserInfo.objects.filter(name=user,password=pwd1).first()
if obj:
obje = redirect('/portal/')
# 1、max_age=10 10秒后退出系统
# 2、获取时间差退出系统
import datetime
from datetime import timedelta
ct = datetime.datetime.utcnow()
# print(ct)
v = timedelta(seconds=60000)
value = ct + v
# print(value)
obje.set_signed_cookie('ticket', 'zhanghongjun21342', salt='zhanghongjun123', expires=value)
# 权限及菜单信息初始化
init_preimssion(request,obj)
return obje
else:
return render(request, 'login.html')
except:
return redirect('/')
七、在左边任务链位置添加一下内容,实现模块权限自动展示(有权限则展示,无权限不展示)
{% for item in request.session.menu_list %} <a class="glyphicon {{ item.icon }} active" type="font-size:20px" href="{{ item.url }}" >{{ item.title }}</a> {% endfor %}
八、效果图如下