Code

Ticket #3609: BasicAuthentication.diff

File BasicAuthentication.diff, 4.6 KB (added by pterk@…, 7 years ago)
Line 
1Index: django/contrib/admin/views/decorators.py
2===================================================================
3--- django/contrib/admin/views/decorators.py    (revision 4649)
4+++ django/contrib/admin/views/decorators.py    (working copy)
5@@ -2,6 +2,7 @@
6 from django.conf import settings
7 from django.contrib.auth.models import User
8 from django.contrib.auth import authenticate, login
9+from django.contrib.auth.middleware import basic_challenge
10 from django.shortcuts import render_to_response
11 from django.utils.translation import gettext_lazy
12 import base64, datetime, md5
13@@ -11,6 +12,8 @@
14 LOGIN_FORM_KEY = 'this_is_the_login_form'
15 
16 def _display_login_form(request, error_message=''):
17+    if getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
18+        return basic_challenge()
19     request.session.set_test_cookie()
20     if request.POST and request.POST.has_key('post_data'):
21         # User has failed login BUT has previously saved post data.
22Index: django/contrib/auth/middleware.py
23===================================================================
24--- django/contrib/auth/middleware.py   (revision 4649)
25+++ django/contrib/auth/middleware.py   (working copy)
26@@ -1,3 +1,40 @@
27+from django.conf import settings
28+from django.http import HttpResponse
29+
30+from django.contrib.auth import authenticate, login, logout
31+
32+def basic_challenge(realm = None):
33+    if realm is None:
34+        realm = getattr(settings, 'WWW_AUTHENTICATION_REALM', _('Restricted Access'))
35+    # TODO: Make a nice template for a 401 message?
36+    response =  HttpResponse(_('Authorization Required'), mimetype="text/plain")
37+    response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
38+    response.status_code = 401
39+    return response
40+
41+def basic_authenticate(authentication):
42+    # Taken from paste.auth
43+    (authmeth, auth) = authentication.split(' ',1)
44+    if 'basic' != authmeth.lower():
45+        return None
46+    auth = auth.strip().decode('base64')
47+    username, password = auth.split(':',1)
48+    return authenticate(username = username, password = password)
49+
50+class BasicAuthenticationMiddleware:
51+    def process_request(self, request):
52+        if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
53+            return None
54+        if not request.META.has_key('HTTP_AUTHORIZATION'):
55+            # If the user out of the session as well
56+            logout(request)
57+            return None
58+        user =  basic_authenticate(request.META['HTTP_AUTHORIZATION'])
59+        if user is None:
60+            return basic_challenge()
61+        else:
62+            login(request, user)
63+
64 class LazyUser(object):
65     def __get__(self, request, obj_type=None):
66         if not hasattr(request, '_cached_user'):
67Index: django/contrib/auth/views.py
68===================================================================
69--- django/contrib/auth/views.py        (revision 4649)
70+++ django/contrib/auth/views.py        (working copy)
71@@ -35,6 +35,12 @@
72     "Logs out the user and displays 'You are logged out' message."
73     from django.contrib.auth import logout
74     logout(request)
75+   
76+    # This 'works' as a way to log out users but it is confusing. You
77+    # log out and it asks for your credentials again?
78+    #if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
79+    #    from middleware import basic_challenge
80+    #    return basic_challenge()
81     if next_page is None:
82         return render_to_response(template_name, {'title': _('Logged out')}, context_instance=RequestContext(request))
83     else:
84Index: django/contrib/auth/decorators.py
85===================================================================
86--- django/contrib/auth/decorators.py   (revision 4649)
87+++ django/contrib/auth/decorators.py   (working copy)
88@@ -1,3 +1,5 @@
89+from django.conf import settings
90+
91 from django.contrib.auth import LOGIN_URL, REDIRECT_FIELD_NAME
92 from django.http import HttpResponseRedirect
93 from urllib import quote
94@@ -2,2 +4,4 @@
95 
96+from django.contrib.auth.middleware import basic_challenge
97+
98 def user_passes_test(test_func, login_url=LOGIN_URL):
99@@ -12,10 +16,12 @@
100         def _checklogin(request, *args, **kwargs):
101             if test_func(request.user):
102                 return view_func(request, *args, **kwargs)
103-            return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path())))
104+            if getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
105+                return basic_challenge()
106+            else:
107+                return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path())))
108         _checklogin.__doc__ = view_func.__doc__
109         _checklogin.__dict__ = view_func.__dict__
110-
111         return _checklogin
112     return _dec
113