tokenAuthentication.py 1.0 KB

12345678910111213141516171819202122232425
  1. from rest_framework.authentication import BaseAuthentication
  2. from rest_framework import exceptions
  3. from rest_framework.authtoken.models import Token
  4. from django.contrib.sessions.backends.db import SessionStore
  5. import time
  6. from api.models import User
  7. class TokenAuthentication(BaseAuthentication):
  8. def authenticate(self, request):
  9. try:
  10. auth_header = request.headers.get('Authorization', '')
  11. if auth_header.startswith('Token '):
  12. token = auth_header.split(' ')[1]
  13. if Token.objects.filter(key=token).exists():
  14. user_id = Token.objects.filter(key=token).first().user_id
  15. user= User.objects.get(id=user_id)
  16. return (user, token)
  17. return None
  18. else:
  19. raise exceptions.AuthenticationFailed("用户信息认证失败")
  20. except Exception as error:
  21. print(error)
  22. raise exceptions.AuthenticationFailed("用户信息认证失败")