from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse
from django.urls import reverse
from www import models
class AuthMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path_info in [reverse("login")]:
return
# {id:'',username:"",is_super:True}
user_dict = request.session.get("user_session_key")
if not user_dict:
return redirect("login")
request.user_dict = user_dict
class PermissionMiddleware(MiddlewareMixin):
def process_view(self, request, callback, *args, **kwargs):
if request.path_info in [reverse("login")]:
return
# *超级用户校验
if request.user_dict['is_super']:
# 所有菜单都应该展示出来
menus = models.Menu.objects.all().values("id", "title", "permissions__name", "permissions__code")
request.menu_list = menus
return
# *普通用户校验
# print("中间件", request.user_dict)
# 1.获取当前访问的路由
url_name = request.resolver_match.url_name
# view_name = request.resolver_match.view_name api: url_name
# 2.获取当前用户
user_object = models.User.objects.filter(id=request.user_dict['id']).first()
# 获取当用户的所有菜单
menus = models.Menu.objects.filter(user=user_object).values("id", "title", "permissions__name","permissions__code")
request.menu_list = menus
# 当前用户所有的权限
# role_per_list = user_object.roles.all().values("permissions__name", "permissions__code").distinct()
role_per_list = user_object.roles.all().values("permissions__name", "permissions__code")
permission_dict = {item['permissions__code']: item['permissions__name'] for item in role_per_list}
request.permission_dict = permission_dict
print("中间件", permission_dict)
if url_name in permission_dict:
return
return HttpResponse("无权访问")
标签:__,name,示例,中间件,request,django,dict,user,permissions
From: https://www.cnblogs.com/cloud-2-jane/p/18401021