Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.conf import settings
- from django.http import HttpResponse
- import hashlib
- class BasicAuthMiddleware():
- def process_request(self, request):
- basic_auth_enabled = getattr(settings, 'BASIC_AUTH_ENABLED', False)
- expected_username = getattr(settings, 'BASIC_AUTH_USERNAME', None)
- expected_password = getattr(settings, 'BASIC_AUTH_PASSWORD', None)
- realm = getattr(settings, 'BASIC_AUTH_REALM', 'Restricted access')
- if not (basic_auth_enabled and expected_username and expected_password):
- return None
- if request.META.has_key('HTTP_AUTHORIZATION'):
- username, password = self.basic_authenticate(request.META['HTTP_AUTHORIZATION'])
- if (username == expected_username and hashlib.sha1(password).hexdigest() == expected_password):
- return None
- response = HttpResponse('<h1>Authorization Required</h1>')
- response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
- response.status_code = 401
- return response
- def basic_authenticate(self, authentication):
- # Taken from paste.auth
- (authmeth, auth) = authentication.split(' ',1)
- if 'basic' != authmeth.lower():
- return (None, None)
- auth = auth.strip().decode('base64')
- username, password = auth.split(':',1)
- return (username, password)
Add Comment
Please, Sign In to add comment