diff --git a/partitioncloud/__init__.py b/partitioncloud/__init__.py index 736be2b..5cdf7ff 100644 --- a/partitioncloud/__init__.py +++ b/partitioncloud/__init__.py @@ -3,9 +3,13 @@ Main file """ import os -from flask import Flask, render_template, request, send_file, g, redirect -from . import auth, albums, partition +from flask import Flask, g, redirect, render_template, request, send_file, flash +from werkzeug.security import generate_password_hash + +from . import albums, auth, partition +from .auth import admin_required +from .db import get_db app = Flask(__name__) @@ -27,5 +31,42 @@ def home(): return redirect("/albums/") +@app.route("/add-user", methods=["GET", "POST"]) +@admin_required +def add_user(): + """ + Ajouter un utilisateur en tant qu'administrateur + """ + if request.method == "POST": + username = request.form["username"] + password = request.form["password"] + db = get_db() + error = None + + if not username: + error = "Un nom d'utilisateur est requis." + elif not password: + error = "Un mot de passe est requis." + + if error is None: + try: + db.execute( + "INSERT INTO user (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)), + ) + db.commit() + except db.IntegrityError: + # The username was already taken, which caused the + # commit to fail. Show a validation error. + error = f"Le nom d'utilisateur {username} est déjà pris." + else: + # Success, go to the login page. + flash(f"Utilisateur {username} crée") + return redirect("/albums") + + flash(error) + return render_template("auth/register.html") + + if __name__ == "__main__": app.run(host="0.0.0.0") diff --git a/partitioncloud/auth.py b/partitioncloud/auth.py index 83fa1dd..8f1da28 100644 --- a/partitioncloud/auth.py +++ b/partitioncloud/auth.py @@ -13,6 +13,7 @@ from flask import ( request, session, url_for, + flash ) from werkzeug.security import check_password_hash, generate_password_hash @@ -28,6 +29,7 @@ def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: + flash("Vous devez être connecté pour accéder à cette page.") return redirect(url_for("auth.login")) return view(**kwargs) @@ -41,10 +43,12 @@ def admin_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: + flash("Vous devez être connecté pour accéder à cette page.") return redirect(url_for("auth.login")) user = User(session.get("user_id")) if user.access_level != 1: + flash("Droits insuffisants.") return redirect("/albums") return view(**kwargs)