You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
EduSystem/EduSystemServer/API/middle.py

48 lines
2.2 KiB

1 year ago
import jwt
from django.http import JsonResponse
1 year ago
from EduSystemServer.settings import TOKEN_KEY
from EduSystemServer.utils import ResponseUtil
1 year ago
from Eduadmin.models import Admin
from Student.models import Student
from teacher.models import Teacher
1 year ago
class JWTMiddleware:
"""
JWT中间件验证用户是否登录
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
1 year ago
# 检查请求的路径是否是登录路由,如果是,放行
if request.path == '/login' \
or request.path == "/index" \
or request.path == "/" \
or request.path.startswith("/admin")\
or request.path.startswith("/static"):
response = self.get_response(request)
return response
1 year ago
# 从请求头中获取 Token
token = request.META.get('HTTP_AUTHORIZATION', '')
try:
# 验证 Token
payload = jwt.decode(token, TOKEN_KEY, algorithms=['HS256'])
# 将解码后的 Token 数据存储在 request 中,以便视图可以访问
1 year ago
if payload.get("type") == "student":
if not Student.objects.filter(username=payload.get("username")).exists():
1 year ago
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
1 year ago
if payload.get("type") == "teacher":
if not Teacher.objects.filter(username=payload.get("username")).exists():
1 year ago
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
1 year ago
if payload.get("type") == "admin":
if not Admin.objects.filter(username=payload.get("username")).exists():
1 year ago
return JsonResponse(ResponseUtil.error("用户不存在!"), status=401)
1 year ago
request.jwt_payload = payload
except jwt.ExpiredSignatureError:
1 year ago
return JsonResponse(ResponseUtil.error("Token 失效,请重新登录!"), status=401)
1 year ago
except jwt.DecodeError:
1 year ago
return JsonResponse(ResponseUtil.error("Token Error"), status=401)
1 year ago
# 继续处理请求
response = self.get_response(request)
1 year ago
return response