1
from django.utils.translation import ugettext as _
2
from django.http import HttpResponse
3
from django.contrib.auth import authenticate, login
4
from django.conf import settings
6
def simple_basic_auth_callback(request, user, *args, **kwargs):
8
Simple callback to automatically login the given user after a successful
14
def basic_auth_required(realm=None, test_func=None, callback_func=None):
16
This decorator should be used with views that need simple authentication
17
against Django's authentication framework.
19
The ``realm`` string is shown during the basic auth query.
21
It takes a ``test_func`` argument that is used to validate the given
22
credentials and return the decorated function if successful.
24
If unsuccessful the decorator will try to authenticate and checks if the
25
user has the ``is_active`` field set to True.
27
In case of a successful authentication the ``callback_func`` will be
28
called by passing the ``request`` and the ``user`` object. After that the
29
actual view function will be called.
31
If all of the above fails a "Authorization Required" message will be shown.
34
realm = getattr(settings, 'HTTP_AUTHENTICATION_REALM', _('Restricted Access'))
36
test_func = lambda u: u.is_authenticated()
38
def decorator(view_func):
39
def basic_auth(request, *args, **kwargs):
40
# Just return the original view because already logged in
41
if test_func(request.user):
42
return view_func(request, *args, **kwargs)
44
# Not logged in, look if login credentials are provided
45
if 'HTTP_AUTHORIZATION' in request.META:
46
auth_method, auth = request.META['HTTP_AUTHORIZATION'].split(' ',1)
47
if 'basic' == auth_method.lower():
48
auth = auth.strip().decode('base64')
49
username, password = auth.split(':',1)
50
user = authenticate(username=username, password=password)
53
if callback_func is not None and callable(callback_func):
54
callback_func(request, user, *args, **kwargs)
55
return view_func(request, *args, **kwargs)
57
response = HttpResponse(_('Authorization Required'), mimetype="text/plain")
58
response.status_code = 401
59
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm