parent
f3658ac3bc
commit
535a691e56
@ -1,23 +1,29 @@
|
|||||||
|
import jwt
|
||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
|
from EduSystemServer.settings import TOKEN_KEY
|
||||||
|
from EduSystemServer.utils import ResponseUtil
|
||||||
|
|
||||||
|
|
||||||
class AuthMiddleware:
|
class JWTMiddleware:
|
||||||
"""
|
|
||||||
验证权限登录中间件
|
|
||||||
"""
|
|
||||||
def __init__(self, get_response):
|
def __init__(self, get_response):
|
||||||
self.get_response = get_response
|
self.get_response = get_response
|
||||||
|
|
||||||
def __call__(self, request):
|
def __call__(self, request):
|
||||||
path = request.path
|
# 检查请求的路径是否是登录路由,如果是,放行
|
||||||
if path in [
|
if request.path == '/login':
|
||||||
"/login",
|
|
||||||
]:
|
|
||||||
response = self.get_response(request)
|
response = self.get_response(request)
|
||||||
return response
|
return response
|
||||||
|
# 从请求头中获取 Token
|
||||||
session = request.session
|
token = request.META.get('HTTP_AUTHORIZATION', '')
|
||||||
if not session.get("username") and not session.get("type"):
|
try:
|
||||||
return JsonResponse({"code": -1, "msg": "not login!"}, status=401)
|
# 验证 Token
|
||||||
|
payload = jwt.decode(token, TOKEN_KEY, algorithms=['HS256'])
|
||||||
|
# 将解码后的 Token 数据存储在 request 中,以便视图可以访问
|
||||||
|
request.jwt_payload = payload
|
||||||
|
except jwt.ExpiredSignatureError:
|
||||||
|
return JsonResponse(ResponseUtil.error("登录失效!"), status=401)
|
||||||
|
except jwt.DecodeError:
|
||||||
|
return JsonResponse(ResponseUtil.error("登录失效!"), status=401)
|
||||||
|
# 继续处理请求
|
||||||
response = self.get_response(request)
|
response = self.get_response(request)
|
||||||
return response
|
return response
|
Loading…
Reference in new issue