Guest User

Untitled

a guest
Jan 15th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. from django.conf import settings
  2. from django.http import HttpResponse
  3. import hashlib
  4.  
  5. class BasicAuthMiddleware():
  6. def process_request(self, request):
  7. basic_auth_enabled = getattr(settings, 'BASIC_AUTH_ENABLED', False)
  8. expected_username = getattr(settings, 'BASIC_AUTH_USERNAME', None)
  9. expected_password = getattr(settings, 'BASIC_AUTH_PASSWORD', None)
  10. realm = getattr(settings, 'BASIC_AUTH_REALM', 'Restricted access')
  11. if not (basic_auth_enabled and expected_username and expected_password):
  12. return None
  13.  
  14. if request.META.has_key('HTTP_AUTHORIZATION'):
  15. username, password = self.basic_authenticate(request.META['HTTP_AUTHORIZATION'])
  16. if (username == expected_username and hashlib.sha1(password).hexdigest() == expected_password):
  17. return None
  18.  
  19. response = HttpResponse('<h1>Authorization Required</h1>')
  20. response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
  21. response.status_code = 401
  22. return response
  23.  
  24. def basic_authenticate(self, authentication):
  25. # Taken from paste.auth
  26. (authmeth, auth) = authentication.split(' ',1)
  27. if 'basic' != authmeth.lower():
  28. return (None, None)
  29. auth = auth.strip().decode('base64')
  30. username, password = auth.split(':',1)
  31. return (username, password)
Add Comment
Please, Sign In to add comment