12345678910111213141516171819202122232425 |
- from rest_framework.authentication import BaseAuthentication
- from rest_framework import exceptions
- from rest_framework.authtoken.models import Token
- from django.contrib.sessions.backends.db import SessionStore
- import time
- from api.models import User
- class TokenAuthentication(BaseAuthentication):
- def authenticate(self, request):
- try:
- auth_header = request.headers.get('Authorization', '')
- if auth_header.startswith('Token '):
- token = auth_header.split(' ')[1]
- if Token.objects.filter(key=token).exists():
- user_id = Token.objects.filter(key=token).first().user_id
- user= User.objects.get(id=user_id)
- return (user, token)
- return None
- else:
- raise exceptions.AuthenticationFailed("用户信息认证失败")
-
-
- except Exception as error:
- print(error)
- raise exceptions.AuthenticationFailed("用户信息认证失败")
|