权限管理django中间件
from django.http import JsonResponse
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.apps import apps
import jwt
class MyMiddleware(MiddlewareMixin):
def __init__(self, get_response=None):
"""
初始化中间件,获取必要的模型引用。
参数:
get_response (callable, optional): 链中的下一个中间件。
"""
super().__init__(get_response)
self.UserModel = apps.get_model('userlogin', 'User')
self.UserRoleModel = apps.get_model('usermanage', 'UserRole')
self.RolePermissionModel = apps.get_model('usermanage', 'RolePermission')
self.RouteModel = apps.get_model('usermanage', 'Route')
def __call__(self, request: HttpRequest) -> HttpResponse:
"""
处理传入的请求。
参数:
request (HttpRequest): 传入的HTTP请求。
返回:
HttpResponse: HTTP响应。
"""
try:
token = request.headers['Authorization'].split(' ')[0]
user = jwt.decode(token, algorithms=["RS256"], options={"verify_signature": False})
user_id = self.UserModel.objects.get(sub=user['sub']).user_id
user_role = self.UserRoleModel.objects.filter(user_id=user_id).values_list('role_id', flat=True)
user_permission = self.RolePermissionModel.objects.filter(role_id__in=user_role).values_list('permission_id', flat=True)
permitted_urls = self.RouteModel.objects.filter(permission_id__in=user_permission).values_list('route_url', flat=True)
if request.path in permitted_urls:
return self.get_response(request)
else:
return JsonResponse({'code': 403, 'msg': '没有权限'})
except KeyError:
return JsonResponse({'code': 400, 'msg': 'Authorization头部缺少令牌'})
except jwt.DecodeError:
return JsonResponse({'code': 401, 'msg': '令牌无效或过期'})
except self.UserModel.DoesNotExist:
return JsonResponse({'code': 401, 'msg': '用户不存在'})
except Exception as e:
return JsonResponse({'code': 500, 'msg': '服务器内部错误'})