Created
November 1, 2013 13:09
-
-
Save nicksnell/7265184 to your computer and use it in GitHub Desktop.
Dead simple HTTP Auth decorator for django. Just add @http_basic_auth(username='...some user...', password='...some pass...') round the view
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
| from django.http import HttpResponse, HttpResponseForbidden | |
| def _auth_request(realm): | |
| response = HttpResponse() | |
| response.status_code = 401 | |
| response['WWW-Authenticate'] = 'Basic realm="%s"' % realm | |
| return response | |
| def http_basic_auth(username=None, password=None, realm='Authorization required'): | |
| """HTTP Basic Auth for a view""" | |
| def wrapper(fn, *args, **kwargs): | |
| def _decorator(request, *args, **kwargs): | |
| if not request.META.has_key('HTTP_AUTHORIZATION'): | |
| return _auth_request(realm) | |
| authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1) | |
| if authmeth.lower() == 'basic': | |
| auth = auth.strip().decode('base64') | |
| auth_username, auth_password = auth.split(':', 1) | |
| if (username == auth_username and password == auth_password): | |
| return fn(request, *args, **kwargs) | |
| return _auth_request(realm) | |
| return _decorator | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment