Skip to content

Instantly share code, notes, and snippets.

@mkouhei
Last active August 29, 2015 14:28
Show Gist options
  • Save mkouhei/425cfad2672fdab45a5a to your computer and use it in GitHub Desktop.
Save mkouhei/425cfad2672fdab45a5a to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions, HTTP_HEADER_ENCODING
from django_auth_custom_example.models import CustomAuthToken
def get_authorization_header(request):
auth = request.META.get('HTTP_X_AUTH_TOKEN', b'')
if isinstance(auth, type('')):
auth = auth.encode(HTTP_HEADER_ENCODING)
return auth
class TokenAuthentication(BaseAuthentication):
model = CustomAuthToken
def authenticate(self, request):
auth = get_authorization_header(request)
if not auth:
return None
token = self.authenticate_credentials(auth)
return (token.user, token)
def authenticate_credentials(self, key):
try:
token = self.model.objects.get(token=key)
except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
if not token.user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted')
return token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment