# Django HTTP Login # # Douglas Thrift # # $Id$ import base64 from django.contrib.auth import authenticate, login from django.http import HttpResponse from functools import wraps, update_wrapper def http_user_passes_test(test_func, login_realm = ''): def decorate(view_func): return _CheckLogin(view_func, test_func, login_realm) return decorate def http_login_required(function=None, login_realm = ''): actual_decorator = http_user_passes_test(lambda u: u.is_authenticated(), login_realm = login_realm) if function is not None: return actual_decorator(function) return actual_decorator def http_permission_required(perm, login_realm = ''): return http_user_passes_test(lambda u: u.has_perm(perm), login_realm = login_realm) def http_permissions_required(perms, login_realm = ''): return http_user_passes_test(lambda u: u.has_perms(perms), login_realm = login_realm) class _CheckLogin(object): def __init__(self, view_func, test_func, login_realm = ''): self.view_func = view_func self.test_func = test_func self.login_realm = login_realm update_wrapper(self, view_func) def __get__(self, obj, cls = None): view_func = self.view_func.__get__(obj, cls) return _CheckLogin(view_func, self.test_func, self.login_realm) def __call__(self, request, *args, **kwargs): if 'HTTP_AUTHORIZATION' in request.META: type, authorization = request.META['HTTP_AUTHORIZATION'].split(' ', 1) if type.lower() == 'basic': username, password = base64.b64decode(authorization).split(':', 1) user = authenticate(username = username, password = password) if user is not None and user.is_active: login(request, user) if self.test_func(request.user): return self.view_func(request, *args, **kwargs) response = HttpResponse('\n\n401 Authorization Required\n\n

Authorization Required

\n

This server could not verify that you\nare authorized to access the document\nrequested. Either you supplied the wrong\ncredentials (e.g., bad password), or your\nbrowser doesn\'t understand how to supply\nthe credentials required.

\n
\n%s\n' % request.META['SERVER_SIGNATURE'], status = 401) response['WWW-Authenticate'] = 'Basic realm="%s"' % self.login_realm return response