用户访问,在中间件从session中获取用户权限信息,并进行权限验证
目录
# -*- encoding: utf-8 -*-
"""
@File : midle.py
@Time : 2021-12-16 8:59
@Author : tangsai
@Email : 294168604@qq.com
@Software: PyCharm
"""
import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class CheckPermission(MiddlewareMixin):
"""
用户权限信息校验
"""
def process_request(self, request):
"""
当用户请求刚进入时候出发执行
:param request:
:return:
"""
"""
1. 获取当前用户请求的URL
2. 获取当前用户在session中保存的权限列表 ['/customer/list/','/customer/list/(?P<cid>\\d+)/']
3. 权限信息匹配
"""
valid_url_list = [
'/login/',
'/admin/.*'
]
current_url = request.path_info
for valid_url in valid_url_list:
if re.match(valid_url, current_url):
print(valid_url,current_url)
# 白名单中的URL无需权限验证即可访问
return None
permission_list = request.session.get('luffy_permission_url_list_key')
if not permission_list:
return HttpResponse('未获取到用户权限信息,请登录!')
flag = False
for url in permission_list:
reg = "^%s$" % url
if re.match(reg, current_url):
flag = True
break
if not flag:
return HttpResponse('无权访问')
setting.py中间件配置新增路径
'web.md.midle.CheckPermission'