Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Created February 15, 2013 10:01
Show Gist options
  • Save iolloyd/4959467 to your computer and use it in GitHub Desktop.
Save iolloyd/4959467 to your computer and use it in GitHub Desktop.
auth.py
def get_user_by_email(email):
user = g.db.query(User).filter_by(email=email).first()
return user
def check_auth(email, password):
"""This function is called to check if a username /
password combination is valid.
"""
user = get_user_by_email(email)
if not user:
return False
session['user'] = user
return user.check_password(password)
def authenticate():
"""Send a 401 response to trigger auth."""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
"""Decorator method to specify auth entry points.
"""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
g.user = get_user_by_email(auth.username)
session['user'] = g.user
return f(*args, **kwargs)
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment