關於權限:html
首先明確權限是爲了限制其餘訪問的url數據庫
經過在models使之關聯的表再經過關聯表的權限來permissions的url 來檢測url的訪問django
一.session
須要三個類五張表app
1 from django.db import models 2 3 # Create your models here. 4 class User(models.Model): 5 6 name=models.CharField(max_length=32) 7 roles=models.ManyToManyField("Role") 8 9 def __str__(self): 10 return self.name 11 12 class Role(models.Model): 13 14 title=models.CharField(max_length=32) 15 permissions=models.ManyToManyField("Permission") 16 17 def __str__(self): 18 return self.title 19 20 21 class Permission(models.Model): 22 23 title = models.CharField(max_length=32) 24 url = models.CharField(max_length=32) 25 is_menu = models.BooleanField(default=False) 26 icon=models.CharField(max_length=32,null=True,blank=True) 27 28 def __str__(self): 29 return self.title
二.ide
再經過admin來建立表的數據url
注意的是,爲了方便顯示各字段,能夠建立類引用ModelAdmin來進行修飾spa
1 from django.contrib import admin 2 3 from app01.models import User,Role,Permission 4 5 # Register your models here. 6 admin.site.register(User) 7 class RoleConfig(admin.ModelAdmin): 8 list_display = ["title"] 9 10 admin.site.register(Role,RoleConfig) 11 12 class PermissionConfig(admin.ModelAdmin): 13 list_display = ["title","pk","url","is_menu","icon"] 14 # list_editable = ['url', 'is_menu', 'icon'] 15 16 admin.site.register(Permission,PermissionConfig)
三.code
建立好數據庫後,須要在login上進行htm
驗證登陸
保存用戶登陸的狀態信息寫入session中(確認在登陸)
查詢當前登陸人的權限列表
將權限列表寫入session中
1 def login(request): 2 3 if request.method=="POST": 4 # 認證 5 6 user=request.POST.get("user") 7 8 user=User.objects.filter(name=user).first() 9 if user: 10 # 登陸成功 11 12 # 保存登陸用戶狀態信息 13 14 request.session["user_id"]=user.pk 15 16 # 查詢當前登陸人的全部權限列表 17 # 查看當前登陸人的全部角色 18 # ret=Role.objects.filter(user=user) 19 20 permissions=Role.objects.filter(user=user).values("permissions__url").distinct() 21 print(permissions) 22 23 permission_list=[] 24 for item in permissions: 25 permission_list.append(item["permissions__url"]) 26 27 # 將當前登陸人的權限列表注入session中 28 request.session["permission_list"]=permission_list 29 30 return HttpResponse("登陸成功") 31 else: 32 val="HAPPY" 33 n=12 34 35 36 return render(request,'login.html',locals())
四.
經過中間件的形式來驗證用戶的使用權限
設置白名單
檢驗是否登陸
校驗權限
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import HttpResponse,redirect 3 import re 4 5 6 class PermissionMiddleWare(MiddlewareMixin): 7 8 def process_request(self,request): 9 print(1) 10 print("permission_list",request.session.get("permission_list")) 11 current_path = request.path 12 13 # 設置白名單放行 14 for reg in ["/login/","/admin/*"]: 15 ret=re.search(reg,current_path) 16 if ret: 17 return None 18 # /customers/edit/1 19 20 # 校驗是否登陸 21 22 user_id=request.session.get("user_id") 23 print("user_id",user_id) 24 if not user_id: 25 return redirect("/login/") 26 27 # 校驗權限 28 29 30 permission_list=request.session.get("permission_list") 31 32 for reg in permission_list: 33 reg="^%s$"%reg 34 ret=re.search(reg,current_path) 35 if ret: 36 return None 37 38 return HttpResponse("無訪問權限!")
這樣初始的權限就完成了