Guest User

Untitled

a guest
Apr 30th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import base64
  2. from django.http import HttpResponse
  3.  
  4. class http_auth_required(object):
  5. """
  6. A decorator to handle basic HTTP authentication. Takes a dictionary of
  7. username: password pairs to authenticate against.
  8. """
  9. def __init__(self, credentials):
  10. self.credentials = credentials
  11.  
  12. def __call__(self, view):
  13. def inner(request, *args, **kwargs):
  14. # header indicates login attempt
  15. if request.META.has_key('HTTP_AUTHORIZATION'):
  16. auth = request.META['HTTP_AUTHORIZATION'].split()
  17. if len(auth) == 2 and auth[0].lower() == 'basic':
  18. username, password = base64.b64decode(auth[1]).split(':')
  19. if self.credentials.has_key(username) and self.credentials[username] == password:
  20. request.META['REMOTE_USER'] = username
  21. return view(request, *args, **kwargs)
  22.  
  23. # The credentials are incorrect, or not provided; challenge for username/password
  24. response = HttpResponse()
  25. response.status_code = 401
  26. response['WWW-Authenticate'] = 'Basic realm="restricted"'
  27. return response
  28.  
  29. return inner
Add Comment
Please, Sign In to add comment