auth.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from rest_framework import authentication
  2. from rest_framework import exceptions
  3. from drf_temptoken import utils
  4. from drf_temptoken.models import TempToken
  5. class TempTokenAuthentication(authentication.BaseAuthentication):
  6. def authenticate(self, request):
  7. query = request.GET
  8. header = request.META.get(f'HTTP_{utils.TMP_TOKEN_AUTH_HEADER}'.upper())
  9. param = utils.get_query_param()
  10. if not header and not param:
  11. return None
  12. header_prefix = utils.get_header_prefix()
  13. value = query.get(param)
  14. has_prefix = header and header_prefix in header
  15. if not has_prefix and not value:
  16. return None
  17. if value:
  18. key = value
  19. else:
  20. _, key = header.split(header_prefix)
  21. try:
  22. token = TempToken.objects.get(key=key)
  23. except TempToken.DoesNotExist:
  24. raise exceptions.AuthenticationFailed('No such token')
  25. if token.expired:
  26. token.delete()
  27. raise exceptions.AuthenticationFailed('Token has expired')
  28. user = token.user
  29. return (user, None)