From 6db3bb00d8defc4f1638a3fa77ddcbfb6af80745 Mon Sep 17 00:00:00 2001 From: Richard Hitier Date: Mon, 29 Mar 2021 12:10:53 +0200 Subject: [PATCH] New role_required decorator --- app/auth/routes.py | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) 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