-
在建模型时给权限分组
from django.db import models # Create your models here. class User(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) roles=models.ManyToManyField(to="Role") def __str__(self): return self.name class Role(models.Model): title=models.CharField(max_length=32) permissions=models.ManyToManyField(to="Permission") def __str__(self): return self.title class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) action=models.CharField(max_length=32,default="") group=models.ForeignKey("PermissionGroup",default=1) def __str__(self):return self.title class PermissionGroup(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title
-
将session用户数据存取打包
def initial_session(user,request) ##方案2 permissions = user.roles.all().values("permissions__url","permissions__group_id","permissions__action").distinct() print("permissions",permissions) # 获取用户的权限url,权限组,和执行方法 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"]) print(permission_dict) request.session['permission_dict']=permission_dict # 注册菜单权限 permissions = user.roles.all().values("permissions__url","permissions__action","permissions__group__title").distinct() print("permissions",permissions) menu_permission_list=[] for item in permissions: if item["permissions__action"]=="list": menu_permission_list.append((item["permissions__url"],item["permissions__group__title"])) print(menu_permission_list) request.session["menu_permission_list"]=menu_permission_list
想要的permission_dict格式
{1: {'urls': ['/users/add/', '/users/delete/(\\d+)', 'users/edit/(\\d+)'], 'action': ['add', 'delete', 'edit']}, 2: {'urls': ['/roles/'], 'action': ['list']} }
-
url定义形式
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users1/', views.users), url(r'^users/add', views.add_user), url(r'^users/delete/(\d+)', views.del_user), url(r'^roles/', views.roles), url(r'^login/', views.login), ]
-
自定义的rbac权限管理中间件
import re from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse,redirect def reg(request,current_path): # 校验权限1(permission_list) permission_list = request.session.get("permission_list", []) flag = False for permission in permission_list: permission = "^%s$" % permission ret = re.match(permission, current_path) # 权限匹配 if ret: flag = True break return flag 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'] # 给request添加actions属性 return HttpResponse("没有访问权限!")
注册 自己的中间件
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" ]
-
view.py中权限的的使用
from django.shortcuts import render,HttpResponse,redirect # Create your views here. from rbac.models import * class Per(object): def __init__(self,actions): self.actions=actions def add(self): return "add" in self.actions def delete(self): return "delete" in self.actions def edit(self): return "edit" in self.actions def list(self): return "list" in self.actions def users(request): user_list=User.objects.all() # permission_list=request.session.get("permission_list") #print(permission_list) # 查询当前登录人得名字 id=request.session.get("user_id") user=User.objects.filter(id=id).first() per=Per(request.actions) return render(request, "rbac/users.html", locals()) def add_user(request): return HttpResponse("add user.....") def del_user(request,id): return HttpResponse("del"+id) def roles(request): # 查询当前登录人得名字 id = request.session.get("user_id") user = User.objects.filter(id=id).first() role_list=Role.objects.all() per = Per(request.actions) return render(request, "rbac/roles.html", locals()) from rbac.service.perssions import * def login(request): if request.method=="POST": user=request.POST.get("user") pwd=request.POST.get("pwd") user=User.objects.filter(name=user,pwd=pwd).first() if user: ############################### 在session中注册用户ID###################### request.session["user_id"]=user.pk ###############################在session注册权限列表############################## # 查询当前登录用户的所有角色 # ret=user.roles.all() # print(ret)# <QuerySet [<Role: 保洁>, <Role: 销售>]> # 查询当前登录用户的所有权限,注册到session中 initial_session(user,request) #return HttpResponse("登录成功!") return redirect("/users/") return render(request,"login.html")
python笔记(Django rbac组件)
最新推荐文章于 2024-07-06 03:01:37 发布