Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from functools import wraps
- from werkzeug import check_password
- # A bunch of your Flask app's code here
- # . . .
- proxy_user = None
- def check_auth(user_id, user_pass):
- """
- Checks database via SQLAlchemy to check if credentials
- are valid. If valid, returns a tuple containing (True,
- User). Otherwise, returns tuple (False, None).
- """
- try:
- user_id = int(user_id)
- user_pass = str(user_pass)
- except:
- return False, None
- loaded_user = User.query.filter_by(id=user_id).first()
- if loaded_user is None:
- return False, None
- # Assuming you use werkzeug to hash your passwords
- ret_boolean = check_password(str(loaded_user.pwdhash), user_pass)
- return ret_boolean, loaded_user
- def requires_auth(f):
- """
- Decorator for methods to enforce authorization before
- proceding to the wrapped function. Sets a global
- proxy_user object to the current authorized user.
- """
- # Wrapped function has access to proxy_user
- @wraps(f)
- def decorated(*args, **kwargs):
- global proxy_user #declaration required to look up to global scope
- auth = request.authorization
- if not auth:
- return needAuthentication()
- authenticated, proxy_user = check_auth(auth.username, auth.password)
- if not authenticated:
- return needAuthentication(msg='Authentication failed.')
- return f(*args, **kwargs)
- return decorated
- @app.route("/greet")
- @requires_auth
- def greet():
- global proxy_user
- return "Hello, %r" % proxy_user.name
Add Comment
Please, Sign In to add comment