Last active
January 20, 2018 01:37
-
-
Save ebarojas/79a3d4e5eb821b2a54b7e2629dc57d1b to your computer and use it in GitHub Desktop.
A simple snippet to authenticate user with API Token
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
# this will be a view accessed /apiauthview/?token=yourapitoken?redirect_url=/my_redirect_url/ | |
# You need django rest API extended users enabled for this | |
# For higher security, these tokens should be renewed each time a new request is made | |
from rest_framework.authentication import TokenAuthentication | |
# Authenticate a user with API Token | |
class APITokenAutoLogin(View): | |
def auth(self, request, *args, **kwargs): | |
# GET | |
token = request.GET.get('token', None) | |
# Allow a custom redirect_url | |
redirect_url = request.GET.get('redirect_url', "/my_default_view/") | |
# Check for API Token | |
token_auth = TokenAuthentication() | |
data = token_auth.authenticate_credentials(token) | |
# Redirect to Login Page | |
if data is None: | |
return HttpResponseRedirect('/accounts/login/') | |
# Login the user | |
if data[0] is not None and data[1] is not None: | |
# User info | |
user = data[0] | |
# Set Auth Backend - required in Django 1.8 | |
user.backend = 'allauth.account.auth_backends.AuthenticationBackend' | |
# Django Login as a user | |
login(request, user) | |
return HttpResponseRedirect(redirect_url, *args, **kwargs) | |
def get(self, request, *args, **kwargs): | |
return self.auth(request, *args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment