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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
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 ' )
class CheckTokenMiddleware ( MiddlewareMixin ) :
def process_request ( self , request ) :
# todo 登录时不需要校验token
path_info = request . path_info
if path_info . endswith ( ' login ' ) :
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