Created
March 8, 2020 09:53
-
-
Save marteinn/34dd5372b52538bf6caa060424e7ebcd to your computer and use it in GitHub Desktop.
This is a Django Rest Framework authenticator to tastypie ApiKey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.translation import ugettext_lazy as _ | |
from rest_framework import exceptions | |
from rest_framework.authentication import TokenAuthentication | |
from tastypie.models import ApiKey | |
class ApiKeyAuthentication(TokenAuthentication): | |
model = ApiKey | |
keyword = 'ApiKey' | |
def authenticate_credentials(self, key): | |
try: | |
username, key = key.split(":") | |
except Exception: | |
raise exceptions.AuthenticationFailed(_('Invalid token.')) | |
model = self.get_model() | |
try: | |
token = model.objects.select_related('user').get( | |
user__username=username, key=key | |
) | |
except model.DoesNotExist: | |
raise exceptions.AuthenticationFailed(_('Invalid token.')) | |
if not token.user.is_active: | |
raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) | |
return (token.user, token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment