Last active
August 29, 2015 14:28
-
-
Save mkouhei/425cfad2672fdab45a5a to your computer and use it in GitHub Desktop.
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
# -*- 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