权限
web网站权限什么是权限? 一个含正则表达式的URl是一个权限方案1: 用户表 id name 1 alex 2 egon 权限表 id user_id url title 1 1 /customer/add/ 添加客户 2 1 /customers/list/ 查看客户 2 1 /consult_records/ 查看跟进记录 2 1 /consult_records/add/ 添加跟进记录 方案2(RBAC:role based access control): 用户表 id name 1 alex 2 egon user2role id user_id role_id 1 1 3 2 2 3 角色表 id title 1 CEO 2 销售总监 3 销售 role2permission id role_id permission_id 1 3 1 2 3 2 3 3 3 4 3 4 权限表 id url title 1 /customer/add/ 添加客户 2 /customers/list/ 查看客户 2 /consult_records/ 查看跟进记录 2 /consult_records/add/ 添加跟进记录
model
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("Role") def __str__(self): return self.nameclass Role(models.Model): title = models.CharField(max_length=32) permission = models.ManyToManyField("Permission") def __str__(self): return self.title
admin
from django.contrib import admin# Register your models here.from app01.models import User,Role,Permissionadmin.site.register(User)class RoleConfig(admin.ModelAdmin): list_display = ["title"]admin.site.register(Role,RoleConfig)class PermissionConfig(admin.ModelAdmin): list_display = ["pk","title","url"] ordering = ["pk"]admin.site.register(Permission,PermissionConfig)
view
def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") user_obj = User.objects.filter(name=user,pwd=pwd).first() if user_obj: request.session["user_id"] = user_obj.pk permissions = Role.objects.filter(user=user_obj).values("permission__url").distinct() permissions_list = [] for item in permissions: permissions_list.append(item["permission__url"]) request.session["permissions_list"] = permissions_list return HttpResponse("登录成功!") return render(request,"login.html")
middleware
from django.utils.deprecation import MiddlewareMixinimport refrom django.shortcuts import redirect,HttpResponseclass PermissionMiddleWare(MiddlewareMixin): def process_request(self,request): # 设置白名单放行 for reg in ["/login/","/admin/*"]: ret = re.search(reg,request.path) if ret: return None # 检验是否登录 if not request.session.get("user_id"): return redirect("/login/") # 权限 permissions_list = request.session.get("permissions_list") for reg in permissions_list: reg = "^%s$" % reg ret = re.search(reg,request.path) if ret: return None return HttpResponse("没有权限!")