Created
August 28, 2015 23:02
-
-
Save mykwillis/15f78ae70414deade4b4 to your computer and use it in GitHub Desktop.
A Django authenticator that supports Stormpath API keys being used in BASIC HTTP Authentication
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
import logging | |
from django.contrib.auth import get_user_model | |
from stormpath.api_auth import ApiRequestAuthenticator | |
import base64 | |
from stormpath.error import Error | |
from django_stormpath.backends import StormpathBackend | |
log = logging.getLogger(__name__) | |
def get_application(): | |
"""Helper function. Needed for easier testing""" | |
from django_stormpath.models import APPLICATION | |
return APPLICATION | |
class StormpathApiBackend(StormpathBackend): | |
"""Allows the use of API keys for user authentication""" | |
def _stormpath_api_authenticate(self, username, password): | |
authenticator = ApiRequestAuthenticator(get_application()) | |
try: | |
value = username + ':' + password | |
value = base64.b64encode(value.encode('utf-8')).decode('ascii') | |
headers = { | |
'Authorization': 'Basic ' + value | |
} | |
result = authenticator.authenticate(headers) | |
return result.account | |
except Error as e: | |
log.debug(e) | |
return None | |
def authenticate(self, username=None, password=None, **kwargs): | |
"""The authenticate method takes credentials as keyword arguments, | |
usually username/email and password. | |
Returns a user model if the Stormpath authentication was successful or | |
None otherwise. It expects three variable to be defined in Django | |
settings: \n | |
STORMPATH_ID = "apiKeyId" \n | |
STORMPATH_SECRET = "apiKeySecret" \n | |
STORMPATH_APPLICATION = | |
"https://api.stormpath.com/v1/applications/APP_UID" | |
""" | |
if username is None: | |
UserModel = get_user_model() | |
username = kwargs.get(UserModel.USERNAME_FIELD) | |
account = self._stormpath_api_authenticate(username, password) | |
if account is None: | |
return None | |
return self._create_or_get_user(account) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to add to the
AUTHENTICATION_BACKENDS
setting in your projectsettings.py