From a9ecdcaa7d547411efc0933bb68c81be4643a868 Mon Sep 17 00:00:00 2001 From: Stef Date: Tue, 15 Apr 2025 10:58:52 +0200 Subject: [PATCH] Added decorator for admin --- app.py | 8 +++----- application/dash/views.py | 7 +++++++ application/decorators.py | 16 ++++++++++++++++ application/templates/base_template.html | 2 +- 4 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 application/decorators.py diff --git a/app.py b/app.py index 0141619..ddcf5de 100644 --- a/app.py +++ b/app.py @@ -1,15 +1,13 @@ from application import app from flask import redirect, url_for -from flask_login import current_user # type: ignore +from flask_login import current_user, login_required # type: ignore # home route @app.route("/") +@login_required def index(): - if current_user.is_authenticated: - return redirect(url_for("dash.index")) - else: - return redirect(url_for("auth.login")) + return redirect(url_for("dash.index")) # App deployment diff --git a/application/dash/views.py b/application/dash/views.py index 6f7468b..2725088 100644 --- a/application/dash/views.py +++ b/application/dash/views.py @@ -1,6 +1,7 @@ from flask import Blueprint, render_template from flask_login import login_required # type: ignore from application.dash.models import Service +from application.decorators import admin_required dash_blueprint = Blueprint("dash", __name__, template_folder="templates") @@ -12,3 +13,9 @@ dash_blueprint = Blueprint("dash", __name__, template_folder="templates") def index(): services = Service.query.all() # type: ignore return render_template("dashboard.html", services=services) + + +@dash_blueprint.route("/admin", methods=["GET", "POST"]) +# @admin_required +def admin(): + return render_template("admin.html") diff --git a/application/decorators.py b/application/decorators.py new file mode 100644 index 0000000..c38d108 --- /dev/null +++ b/application/decorators.py @@ -0,0 +1,16 @@ +from flask_login import current_user +from functools import wraps +from flask import redirect, url_for, flash + + +def admin_required(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if not current_user.is_authenticated: + return redirect(url_for("login")) + if not current_user.is_admin: + flash("Admins only!") + return redirect(url_for("index")) + return f(*args, **kwargs) + + return decorated_function diff --git a/application/templates/base_template.html b/application/templates/base_template.html index 8a77a90..b25a3cf 100644 --- a/application/templates/base_template.html +++ b/application/templates/base_template.html @@ -30,7 +30,7 @@ - {% if current_user.is_admin %} + {% if current_user.is_authenticated %}