55from django .conf import settings
66from base64 import b64decode
77
8+ __ALL__ = ['basic_auth_required' ]
9+
810
911def basic_auth_required (realm = 'default' ):
1012 def _helper (func ):
1113 @wraps (func )
1214 def _decorator (request , * args , ** kwargs ):
1315 allowed = False
16+ logging .info ('request is secure? {}' .format (request .is_secure ()))
1417 if settings .ALLOW_ANONYMOUS_POST :
1518 allowed = True
1619 elif 'HTTP_AUTHORIZATION' in request .META :
20+ if settings .REQUIRE_SECURE_AUTH and not request .is_secure ():
21+ return insecure_connection_response ()
1722 http_auth = request .META ['HTTP_AUTHORIZATION' ]
1823 authmeth , auth = http_auth .split (' ' , 1 )
1924 if authmeth .lower () == 'basic' :
20- authb = b64decode (auth .strip ())
21- auth = authb .decode ()
22- username , password = auth .split (':' , 1 )
25+ username , password = decode_basic_auth (auth )
2326 user = authenticate (username = username , password = password )
2427 if user is None :
2528 logging .info (
@@ -29,11 +32,25 @@ def _decorator(request, *args, **kwargs):
2932 return HttpResponseForbidden ()
3033 if allowed :
3134 return func (request , * args , ** kwargs )
32- res = HttpResponse ()
33- res .status_code = 401
34- res .reason_phrase = 'Unauthorized'
35- res ['WWW-Authenticate' ] = 'Basic realm="{}"' .format (realm )
36- return res
35+
36+ if settings .REQUIRE_SECURE_AUTH and not request .is_secure ():
37+ return insecure_connection_response ()
38+ else :
39+ res = HttpResponse ()
40+ res .status_code = 401
41+ res .reason_phrase = 'Unauthorized'
42+ res ['WWW-Authenticate' ] = 'Basic realm="{}"' .format (realm )
43+ return res
3744 return _decorator
3845
3946 return _helper
47+
48+
49+ def insecure_connection_response ():
50+ return HttpResponseForbidden ('Secure connection required' )
51+
52+
53+ def decode_basic_auth (auth ):
54+ authb = b64decode (auth .strip ())
55+ auth = authb .decode ()
56+ return auth .split (':' , 1 )
0 commit comments