From bbed019ca560f3d31a88c682adcb9a5526b639ed Mon Sep 17 00:00:00 2001 From: apahomov Date: Mon, 14 Jan 2013 15:45:18 +0400 Subject: [PATCH] Add auth_required decorator that allows multiple auth mechanisms --- flask_security/decorators.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/flask_security/decorators.py b/flask_security/decorators.py index 930df56..5e6ecd9 100644 --- a/flask_security/decorators.py +++ b/flask_security/decorators.py @@ -115,6 +115,35 @@ def auth_token_required(fn): return decorated +def auth_required(*auth_methods): + """ + Decorator that protects enpoints through multiple mechanisms + Example:: + + @app.route('/dashboard') + @auth_required('token', 'session') + def dashboard(): + return 'Dashboard' + + :param auth_methods: Specified mechanisms. + """ + login_mechanisms = { + 'token': lambda: _check_token(), + 'basic': lambda: _check_http_auth(), + 'session': lambda: current_user.is_authenticated() + } + + def wrapper(fn): + @wraps(fn) + def decorated_view(*args, **kwargs): + mechanisms = [login_mechanisms.get(method) for method in auth_methods] + if any(mechanisms): + return fn(*args, **kwargs) + return _get_unauthorized_response() + return decorated_view + return wrapper + + def roles_required(*roles): """Decorator which specifies that a user must have all the specified roles. Example::