Guest User

Untitled

a guest
May 2nd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. class AuthMiddleware(object):
  2.  
  3. def __init__(self, wrap_app):
  4. self.wrap_app = wrap_app
  5.  
  6. def __call__(self, environ, start_response):
  7. if not self.authorized(environ.get('HTTP_AUTHORIZATION')):
  8. # Essentially self.auth_required is a WSGI application
  9. # that only knows how to respond with 401...
  10. return self.auth_required(environ, start_response)
  11. # But if everything is okay, then pass everything through
  12. # to the application we are wrapping...
  13. return self.wrap_app(environ, start_response)
  14.  
  15. def authorized(self, auth_header):
  16. if not auth_header:
  17. # If they didn't give a header, they better login...
  18. return False
  19. # .split(None, 1) means split in two parts on whitespace:
  20. auth_type, encoded_info = auth_header.split(None, 1)
  21. assert auth_type.lower() == 'basic'
  22. unencoded_info = encoded_info.decode('base64')
  23. username, password = unencoded_info.split(':', 1)
  24. return self.check_password(username, password)
  25.  
  26. def check_password(self, username, password):
  27. # Not very high security authentication...
  28. return username == password
  29.  
  30. def auth_required(self, environ, start_response):
  31. start_response('401 Authentication Required',
  32. [('Content-type', 'text/html'),
  33. ('WWW-Authenticate', 'Basic realm="this realm"')])
  34. return ["""
  35. <html>
  36. <head><title>Authentication Required</title></head>
  37. <body>
  38. <h1>Authentication Required</h1>
  39. If you can't get in, then stay out.
  40. </body>
Add Comment
Please, Sign In to add comment