Skip to content

Instantly share code, notes, and snippets.

@marteinn
Created March 8, 2020 09:53
Show Gist options
  • Save marteinn/34dd5372b52538bf6caa060424e7ebcd to your computer and use it in GitHub Desktop.
Save marteinn/34dd5372b52538bf6caa060424e7ebcd to your computer and use it in GitHub Desktop.
This is a Django Rest Framework authenticator to tastypie ApiKey
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