diff --git a/app/auth/routes.py b/app/auth/routes.py index d550ee9..9d125e9 100644 --- a/app/auth/routes.py +++ b/app/auth/routes.py @@ -1,8 +1,38 @@ +from functools import wraps + +from flask_login import current_user from flask import render_template, request, redirect, url_for, flash from flask_login import login_user, logout_user -from .models import User -from . import bp +from app.auth.models import User +from app.auth import bp + + +# +# Decorator used to protect routes by role +# inspired from https://flask.palletsprojects.com/en/master/patterns/viewdecorators/ +# +def role_required(role): + def decorator(f): + @wraps(f) + def decorated_function(*args, **kwargs): + # first check use is logged in + if not current_user or not current_user.is_authenticated: + flash("Vous devez vous authentifier", 'warning') + return redirect(url_for('auth.login')) + # then check role status + try: + is_authorised = current_user.has_role_or_higher(role) + except ValueError: + raise Exception("Unknowk role provided %s" % role) + if not is_authorised: + flash("Vous n'avez pas les autorisations pour accéder à cette page", 'dark') + return redirect(url_for('main.index')) + return f(*args, **kwargs) + + return decorated_function + + return decorator @bp.route('/login') -- libgit2 0.21.2