1 # RBAC中間件案例 2 3 import re 4 from django.shortcuts import redirect, HttpResponse 5 from django.conf import settings 6 7 8 class MiddlewareMixin(object): 9 def __init__(self, get_response=None): 10 self.get_response = get_response 11 super(MiddlewareMixin, self).__init__() 12 13 def __call__(self, request): 14 response = None 15 if hasattr(self, 'process_request'): 16 response = self.process_request(request) 17 if not response: 18 response = self.get_response(request) 19 if hasattr(self, 'process_response'): 20 response = self.process_response(request, response) 21 return response 22 23 24 class LoginMiddleware(MiddlewareMixin): 25 26 def process_request(self, request): 27 # login頁面放行 28 if request.path_info == '/stark11/login/': 29 return None 30 # 已經登陸了放行 31 if request.session.get('user_info'): 32 return None 33 # 不然返回login頁面 34 return redirect('/stark11/login/') 35 36 37 class RbacMiddleware(MiddlewareMixin): 38 39 def process_request(self, request): 40 # 1. 獲取當前請求的URL 41 # request.path_info 42 # 2. 獲取Session中保存當前用戶的權限 43 # request.session.get("permission_url_list') 44 current_url = request.path_info 45 46 # 當前請求不須要執行權限驗證 47 for url in settings.VALID_URL: 48 if re.match(url, current_url): 49 return None 50 51 permission_dict = request.session.get(settings.PERMISSION_URL_DICT_KEY) 52 if not permission_dict: 53 return redirect('/stark11/login/') 54 55 flag = False 56 for group_id, code_url in permission_dict.items(): 57 58 for db_url in code_url['urls']: 59 regax = "^{0}$".format(db_url) 60 if re.match(regax, current_url): 61 request.permission_code_list = code_url['codes'] 62 flag = True 63 break 64 if flag: 65 break 66 67 if not flag: 68 return HttpResponse('無權訪問')