Last active
April 5, 2016 12:14
-
-
Save aklos/3f50a62efc84397dc0f0f296719424fd to your computer and use it in GitHub Desktop.
Basic auth decorator in django views
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 datetime | |
| import json | |
| from django.contrib.auth.decorators import login_required | |
| from django.core.serializers.json import DjangoJSONEncoder | |
| from django.http import HttpResponse, HttpResponseForbidden | |
| from django.contrib import auth | |
| from django.contrib.auth import authenticate, login | |
| # The basic auth decorator | |
| def login_or_basic_auth_required(view): | |
| def _decorator(request, *args, **kwargs): | |
| if request.META.has_key('HTTP_AUTHORIZATION'): | |
| auth_method, credentials = request.META['HTTP_AUTHORIZATION'].split(' ', 1) | |
| if auth_method.lower() == 'basic': | |
| credentials = credentials.strip().decode('base64') | |
| username, password = credentials.split(':', 1) | |
| user = auth.authenticate(username=username, password=password) | |
| if user is not None and user.is_active: | |
| # Correct password, and the user is marked "active" | |
| return view(request, *args, **kwargs) | |
| else: | |
| return HttpResponseForbidden('Incorrect user credentials.') | |
| response = HttpResponse() | |
| response.status_code = 401 | |
| response['WWW-Authenticate'] = 'Basic' | |
| return response | |
| else: | |
| if request.user.is_authenticated(): | |
| return view(request, *args, **kwargs) | |
| else: | |
| return HttpResponseForbidden('Incorrect user credentials') | |
| return _decorator | |
| # A simple test view | |
| @login_or_basic_auth_required | |
| def test(request): | |
| test_data = { | |
| 'string': 'some string', | |
| 'date': datetime.datetime.today(), | |
| 'integer': 1, | |
| 'bool': True, | |
| 'array': ['a', 'b', 'c'] | |
| } | |
| data = json.dumps(['authenticated and receiving data!', test_data], cls=DjangoJSONEncoder) | |
| return HttpResponse(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment