Created
May 22, 2012 04:37
-
-
Save pjz/2766604 to your computer and use it in GitHub Desktop.
aspen basic auth modle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment