Commit 6db3bb00d8defc4f1638a3fa77ddcbfb6af80745
1 parent
42c07429
Exists in
master
and in
4 other branches
New role_required decorator
Showing
1 changed file
with
32 additions
and
2 deletions
Show diff stats
app/auth/routes.py
1 | +from functools import wraps | |
2 | + | |
3 | +from flask_login import current_user | |
1 | 4 | from flask import render_template, request, redirect, url_for, flash |
2 | 5 | from flask_login import login_user, logout_user |
3 | -from .models import User | |
4 | 6 | |
5 | -from . import bp | |
7 | +from app.auth.models import User | |
8 | +from app.auth import bp | |
9 | + | |
10 | + | |
11 | +# | |
12 | +# Decorator used to protect routes by role | |
13 | +# inspired from https://flask.palletsprojects.com/en/master/patterns/viewdecorators/ | |
14 | +# | |
15 | +def role_required(role): | |
16 | + def decorator(f): | |
17 | + @wraps(f) | |
18 | + def decorated_function(*args, **kwargs): | |
19 | + # first check use is logged in | |
20 | + if not current_user or not current_user.is_authenticated: | |
21 | + flash("Vous devez vous authentifier", 'warning') | |
22 | + return redirect(url_for('auth.login')) | |
23 | + # then check role status | |
24 | + try: | |
25 | + is_authorised = current_user.has_role_or_higher(role) | |
26 | + except ValueError: | |
27 | + raise Exception("Unknowk role provided %s" % role) | |
28 | + if not is_authorised: | |
29 | + flash("Vous n'avez pas les autorisations pour accéder à cette page", 'dark') | |
30 | + return redirect(url_for('main.index')) | |
31 | + return f(*args, **kwargs) | |
32 | + | |
33 | + return decorated_function | |
34 | + | |
35 | + return decorator | |
6 | 36 | |
7 | 37 | |
8 | 38 | @bp.route('/login') | ... | ... |