Guest User

Untitled

a guest
Oct 12th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import base64
  2.  
  3. from aspen import Response
  4.  
  5.  
  6. def inbound_responder(*args, **kwargs):
  7. """ see BasicAuth object for args; they're passed through """
  8. auth = BasicAuth(*args, **kwargs)
  9. def _(request):
  10. request.auth = BAWrapper(auth, request)
  11. authed, response = auth.authorized(request):
  12. if not authed:
  13. raise response
  14. return request
  15. return _
  16.  
  17.  
  18. class BAWrapper(object):
  19. def __init__(self, basicauth, request):
  20. self.auth = basicauth
  21. self.request = request
  22.  
  23. def authorized(self):
  24. return self.auth.authorized(request)
  25.  
  26. def userName(self):
  27. return self.auth.userName(request)
  28.  
  29. def logout(self):
  30. return self.auth.logout(request)
  31.  
  32.  
  33.  
  34. class BasicAuth(object):
  35.  
  36. def __init__(self, get_password, html=None, realm='protected'):
  37. failhtml = html or '''Not Authorized. <a href="#">Try again.</a>'''
  38. self.get_password = get_password
  39. self.fail_response = Response(401, failhtml, { 'WWW-Authenticate': 'Basic realm="%s"' % realm })
  40.  
  41. def authorized(self, request):
  42. header = request.headers.get('Authorization', '')
  43. if not header.startswith('Basic'):
  44. # no auth header at all
  45. return False, fail_response
  46. userpass = base64.b64decode(header[len('Basic '):])
  47. if not ':' in userpass:
  48. # malformed user:pass
  49. return False, fail_response
  50. user, passwd = userpass.split(':',1)
  51. if self.get_password(user) != passwd:
  52. # wrong password
  53. # TODO: add a max attempts per timespan to slow down bot attacks
  54. return False, fail_response
  55. return True, None
  56.  
  57. def userName(self, request):
  58. header = request.headers.get('Authorization', '')
  59. if not header.startswith('Basic'):
  60. return None
  61. userpass = base64.b64decode(header[len('Basic '):])
  62. if not ':' in userpass:
  63. return None
  64. user, passwd = userpass.split(':',1)
  65. return user
  66.  
  67. def logout(self, request):
  68. return self.fail_response
Add Comment
Please, Sign In to add comment