File: //proc/thread-self/root/home/arjun/projects/buyercall/buyercall/blueprints/user/decorators.py
from functools import wraps
from flask import flash, redirect
from flask.helpers import url_for
from flask.json import jsonify
from flask_babel import gettext as _
from flask_login import current_user
from buyercall.lib.util_rest import api_jsonify
def anonymous_required(url='/settings'):
"""
Redirect a user to a specified location if they are already signed in.
:param url: URL to be redirected to if invalid
:type url: str
:return: Function
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.is_authenticated:
return redirect(url)
return f(*args, **kwargs)
return decorated_function
return decorator
def role_required(*roles):
"""
Does a user have permission to view this page?
:param *roles: 1 or more allowed roles
:return: Function
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.is_authenticated:
if current_user.role not in roles:
flash(_('You do not have permission to do that.'), 'danger')
return redirect('/')
else:
flash(_('You do not have permission to do that.'), 'danger')
return redirect(url_for('user.login'))
return f(*args, **kwargs)
return decorated_function
return decorator
def api_role_required(*roles):
"""
Does a user have permission to view this page?
:param *roles: 1 or more allowed roles
:return: Function
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.is_authenticated:
if current_user.role not in roles:
status_code = 403
success = False
message = f"You do not have permission to access this resource."
return api_jsonify({}, status_code, message, success)
else:
status_code = 403
success = False
message = f"You do not have permission to access this resource."
return api_jsonify({}, status_code, message, success)
return f(*args, **kwargs)
return decorated_function
return decorator