Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import base64
- from aspen import Response
- def inbound_responder(*args, **kwargs):
- """ see BasicAuth object for args; they're passed through """
- auth = BasicAuth(*args, **kwargs)
- def _(request):
- request.auth = BAWrapper(auth, request)
- authed, response = auth.authorized(request):
- if not authed:
- raise response
- return request
- return _
- class BAWrapper(object):
- def __init__(self, basicauth, request):
- self.auth = basicauth
- self.request = request
- def authorized(self):
- return self.auth.authorized(request)
- def userName(self):
- return self.auth.userName(request)
- def logout(self):
- return self.auth.logout(request)
- class BasicAuth(object):
- def __init__(self, get_password, html=None, realm='protected'):
- failhtml = html or '''Not Authorized. <a href="#">Try again.</a>'''
- self.get_password = get_password
- self.fail_response = Response(401, failhtml, { 'WWW-Authenticate': 'Basic realm="%s"' % realm })
- def authorized(self, request):
- header = request.headers.get('Authorization', '')
- if not header.startswith('Basic'):
- # no auth header at all
- return False, fail_response
- userpass = base64.b64decode(header[len('Basic '):])
- if not ':' in userpass:
- # malformed user:pass
- return False, fail_response
- user, passwd = userpass.split(':',1)
- if self.get_password(user) != passwd:
- # wrong password
- # TODO: add a max attempts per timespan to slow down bot attacks
- return False, fail_response
- return True, None
- def userName(self, request):
- header = request.headers.get('Authorization', '')
- if not header.startswith('Basic'):
- return None
- userpass = base64.b64decode(header[len('Basic '):])
- if not ':' in userpass:
- return None
- user, passwd = userpass.split(':',1)
- return user
- def logout(self, request):
- return self.fail_response
Add Comment
Please, Sign In to add comment