mirror of
https://github.com/wassname/flask-security.git
synced 2026-07-26 13:18:38 +08:00
Add auth_required decorator that allows multiple auth mechanisms
This commit is contained in:
@@ -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::
|
||||
|
||||
Reference in New Issue
Block a user