django中间件判断用户有无权限访问当前的url
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import redirect, HttpResponse 3 import re 4 class RbacMiddleware(MiddlewareMixin): 5 6 def process_request(self, request): 7 8 # 获取访问的url 9 current_url = request.path_info 10 11 # 白名单 12 valid_url = ['^/login/$', '^/admin/.*'] 13 for item in valid_url: 14 if re.match(item, current_url): 15 return 16 17 # 是否登入 18 permission_list = request.session.get('permission_list') 19 if not permission_list: 20 return redirect('/login/') 21 22 # 是否有权限访问 23 flag = False 24 for item in permission_list: 25 reg = '^%s$' % item.get('permission__url') 26 if re.match(reg, current_url): 27 flag = True 28 break 29 if not flag: 30 return HttpResponse('无权访问')