标签:res 正则表达式 cts redirect dia 用户 char col har
一.权限概念:
什么是权限: 一个含义正则表达式的url
二.基于RBAC设计表关系:
设置权限首先得有权限表,管理角色权限:
model:
class User(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) roles=models.ManyToManyField("Role") def __str__(self): return self.name class Role(models.Model): title=models.CharField(max_length=32) permissions=models.ManyToManyField("Permission") def __str__(self): return self.title class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) def __str__(self): return self.title
然后基于admin录入数据。
然后进行权限的录入和校验
1 ,登录认证:将登陆用户的权限注入session
在rbac应用中创建一个service包放处理中间件的文件和rbac文件
rbac.py
from rbac.models import Role def initial_sesson(user,request): """ 功能:将当前登录人的所有权限录入session中 :param user: 当前登录人 """ # 查询当前登录人的所有权限列表 # 查看当前登录人的所有角色 # ret=Role.objects.filter(user=user) permissions = Role.objects.filter(user=user).values("permissions__url", "permissions__is_menu", "permissions__title", "permissions__icon", ).distinct() # distinct去重 print(permissions) permission_list = [] permission_menu_list = [] for item in permissions: # 构建权限列表 permission_list.append(item["permissions__url"]) # 构建菜单权限列表 if item["permissions__is_menu"]: permission_menu_list.append({ "title":item["permissions__title"], "icon":item["permissions__icon"], "url":item["permissions__url"], }) # 将当前登录人的权限列表注入session中 request.session["permission_list"] = permission_list # 将当前登录人的菜单权限列表注入session中 print("permission_menu_list",permission_menu_list) request.session["permission_menu_list"] = permission_menu_list
view视图:
from django.shortcuts import render, HttpResponse, redirect, reverse from rbac.models import User from rbac.service.rbac import initial_sesson def login(request): if request.method == "POST": # 认证 user = request.POST.get("user") pwd = request.POST.get("pwd") user = User.objects.filter(name=user,password=pwd).first() if user: # 登录成功 # 保存登录用户状态信息 request.session["user_id"]=user.pk # 录入权限session,将登录权限录入session表中 initial_sesson(user,request) return redirect("/customer/list/") return render(request, ‘web/login.html‘)
2, 基于中间件和正则实现权限校验
middlewares.py:
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse,redirect import re class PermissionMiddleWare(MiddlewareMixin): def process_request(self,request): print("permission_list",request.session.get("permission_list")) current_path = request.path # 设置白名单放行 for reg in ["/login/","/admin/*"]: ret=re.search(reg,current_path) if ret: return None # /customers/edit/1 # 校验是否登录 user_id=request.session.get("user_id") if not user_id: return redirect("/login/") # 校验权限 permission_list = request.session.get("permission_list") for reg in permission_list: reg = "^%s$"%reg ret = re.search(reg,current_path) if ret: return None return HttpResponse("无访问权限!")
标签:res 正则表达式 cts redirect dia 用户 char col har
原文地址:https://www.cnblogs.com/zwq-/p/10004504.html