一.访问权限的使用和设计(方式一)
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(to="Role") def __str__(self): return self.name class Meta: verbose_name_plural = "用户表" class Role(models.Model): title=models.CharField(max_length=32) permissions=models.ManyToManyField(to="Permission") def __str__(self): return self.title class Meta: verbose_name_plural = "角色表" class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) class Meta: verbose_name_plural = "权限表" def __str__(self):return self.title
URL from django.contrib import admin from django.urls import path from myapp import views urlpatterns= [ path('admin/', admin.site.urls), path('login/', views.login), path('user/', views.users), path('role/', views.roles), path('user/add/', views.add_user), ]
viwes from django.shortcuts import render,HttpResponse # Create your views here. from webauth import models def login(request): if request.method == "POST": name=request.POST.get("user") pwd = request.POST.get("pwd") print(name,pwd) user_obj=models.User.objects.filter(name=name,pwd=pwd).first() if user_obj: # 查询登录成的所有用户权限 # 查询当前登录用户的所有角色 ret=user_obj.roles.all() print(ret) # <QuerySet [<Role: ceo>, <Role: 保安部>]> ############################### 在session中注册用户ID###################### bb=request.session["user_id"] = user_obj.pk print(bb,"session存储值") ret1 = user_obj.roles.values("permissions__url") print(ret1,"11111") # < QuerySet[ {'permissions__url': 'user/add/'}, {'permissions__url': '/user/'}, {'permissions__url': '/role/'}, {'permissions__url': '/user/'}] > 11111 ret11 = user_obj.roles.all().values("title") print(ret11,"22222") # < QuerySet[{'title': 'ceo'}, {'title': '保安部'}] > 22222 ret12= user_obj.roles.values("title") print(ret12,"333333") # < QuerySet[{'title': 'ceo'}, {'title': '保安部'}] > 333333 ret3 = user_obj.roles.values("permissions__url").distinct() print(ret3) li_list=[] for items in ret3: li_list.append(items["permissions__url"]) print(li_list,"访问权限_________________________") # ['/user/add/', '/user/', '/role/', '/user/dels/(\d+)/', '/user/edit/(\d+)/'] ###############################在session注册权限列表############################## aa=request.session["li_list"] = li_list print(aa,"权限保存在session中哈哈哈") # ['/user/add/', '/user/', '/role/', '/user/dels/(\d+)/', '/user/edit/(\d+)/'] return HttpResponse("ok") return render(request,"01login.html") # 用户 def users(request): user_list=models.User.objects.all() return render(request,"users.html",locals()) import re # 添加 def add_user(request): add_list=request.session["li_list"] # 在session中获取权限 在做校验 print(add_list,"#在session中获取权限 在做校验") # ['/user/add/', '/user/', '/role/', '/user/dels/(\d+)/', '/user/edit/(\d+)/'] path_info=request.path_info # / user / add / print(path_info) flag=False for add_li in add_list: re_li="^%s$"%add_li ret=re.match(re_li,path_info) if ret: flag=True break if not flag: return HttpResponse("没有访问权限") return HttpResponse("add user.....") # 角色 def roles(request): add_list=request.session["li_list"] # 在session中获取权限 在做校验 print(add_list,"#在session中获取权限 在做校验") # ['/user/add/', '/user/', '/role/', '/user/dels/(\d+)/', '/user/edit/(\d+)/'] path_info=request.path_info # / user / add / print(path_info) flag=False for add_li in add_list: re_li="^%s$"%add_li ret=re.match(re_li,path_info) if ret: flag=True break if not flag: return HttpResponse("没有访问权限") role_list=models.Role.objects.all() return render(request,"roles.html",locals())
二.访问权限的使用和设计(中间件 方式二)
在中间件做 登录 权限 白名单
import re from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse,redirect 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 # return None 结束中间件 过掉 user_id=request.session.get("user_id") # 校验是否登录 if not user_id: return redirect("/login/") # 校验权限 permission_list = request.session.get("permission_list",[]) # ['/users/', '/users/add', '/users/delete/(\d+)', 'users/edit/(\d+)'] flag = False for permission in permission_list: permission = "^%s$" % permission ret = re.match(permission, current_path) if ret: flag = True break if not flag: return HttpResponse("没有访问权限!") return None
在settings中注册引入中间件
vews from django.shortcuts import render,HttpResponse # Create your views here. from webauth import models def initial_session(user,request): permissions = user.roles.all().values("permissions__url").distinct() permission_list = [] for item in permissions: permission_list.append(item["permissions__url"]) print(permission_list) request.session["permission_list"] = permission_list def login(request): if request.method == "POST": name=request.POST.get("user") pwd = request.POST.get("pwd") print(name,pwd) user_obj=models.User.objects.filter(name=name,pwd=pwd).first() if user_obj: request.session["user_id"] = user_obj.pk initial_session(user_obj, request) return HttpResponse("登录成功!") return render(request,"01login.html") # 用户 def users(request): user_list=models.User.objects.all() return render(request,"users.html",locals()) import re # 添加 def add_user(request): return HttpResponse("add user.....") # 角色 def roles(request): role_list=models.Role.objects.all() return render(request,"roles.html",locals())
urls from django.contrib import admin from django.urls import path from myapp import views urlpatterns= [ path('admin/', admin.site.urls), path('login/', views.login), path('user/', views.users), path('role/', views.roles), path('user/add/', views.add_user), ]