You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
1.1 KiB
Python

2 years ago
import jwt
from django.conf import settings
from user.models import UserProfile
from django.http import HttpResponse, JsonResponse
from django.utils.deprecation import MiddlewareMixin
import logging
from rest_framework.response import Response
logger = logging.getLogger('mylogger')
2 years ago
class CheckTokenMiddleware(MiddlewareMixin):
def process_request(self, request):
# todo 登录时不需要校验token
path_info = request.path_info
2 years ago
if path_info.endswith('login') or path_info.endswith('add_user'):
2 years ago
return
my_auth = request.META.get('HTTP_TOKEN')
if not my_auth:
return JsonResponse(data={'msg': '非法请求,请求头中未携带token'}, status=201)
try:
token = my_auth.split(' ')[1]
res_dict = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
except Exception as e:
logger.info(e)
return JsonResponse({'msg': f'非法token{e}'}, status=201)
# request.user = UserProfile.objects.filter(id=res_dict.get('user_id')).first()
# logger.info(res_dict)
return