partitioncloud-server/partitioncloud/modules/auth.py

173 lines
4.8 KiB
Python
Raw Normal View History

2022-08-13 23:36:10 +02:00
#!/usr/bin/python3
"""
Authentification module
"""
import functools
2023-12-15 13:38:32 +01:00
from typing import Optional
2022-08-13 23:36:10 +02:00
2023-12-15 11:36:34 +01:00
from flask import (Blueprint, flash, g, redirect, render_template,
request, session, url_for, current_app)
2024-01-22 16:06:03 +01:00
from flask_babel import _
2023-12-15 11:36:34 +01:00
2022-08-13 23:36:10 +02:00
from werkzeug.security import check_password_hash, generate_password_hash
from .db import get_db
from .utils import User
2024-01-17 12:56:01 +01:00
from . import logging
2022-08-13 23:36:10 +02:00
bp = Blueprint("auth", __name__, url_prefix="/auth")
def login_required(view):
"""View decorator that redirects anonymous users to the login page."""
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
2024-01-22 16:06:03 +01:00
flash(_("Vous devez être connecté pour accéder à cette page."))
2022-08-13 23:36:10 +02:00
return redirect(url_for("auth.login"))
return view(**kwargs)
return wrapped_view
2023-06-25 09:24:44 +02:00
def anon_required(view):
"""View decorator that redirects authenticated users to the index."""
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is not None:
return redirect(url_for("albums.index"))
return view(**kwargs)
return wrapped_view
def admin_required(view):
"""View decorator that redirects anonymous users to the login page."""
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
2024-01-22 16:06:03 +01:00
flash(_("Vous devez être connecté pour accéder à cette page."))
return redirect(url_for("auth.login"))
2022-12-19 15:19:58 +01:00
user = User(user_id=session.get("user_id"))
if user.access_level != 1:
2024-01-22 16:06:03 +01:00
flash(_("Droits insuffisants."))
return redirect("/albums")
return view(**kwargs)
return wrapped_view
2022-08-13 23:36:10 +02:00
@bp.before_app_request
def load_logged_in_user():
"""If a user id is stored in the session, load the user object from
the database into ``g.user``."""
user_id = session.get("user_id")
if user_id is None:
g.user = None
else:
g.user = (
get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone()
)
2023-12-15 13:38:32 +01:00
def create_user(username: str, password: str) -> Optional[str]:
"""Adds a new user to the database"""
2024-01-15 18:53:57 +01:00
error = None
2023-12-15 13:38:32 +01:00
if not username:
2024-01-22 16:06:03 +01:00
error = _("Un nom d'utilisateur est requis.")
2023-12-15 13:38:32 +01:00
elif not password:
2024-01-22 16:06:03 +01:00
error = _("Un mot de passe est requis.")
2023-12-15 13:38:32 +01:00
try:
db = get_db()
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.
2024-01-22 16:06:03 +01:00
error = _("Le nom d'utilisateur %(username)s est déjà pris.", username=username)
2024-01-15 18:53:57 +01:00
return error # may be None
2023-12-15 13:38:32 +01:00
2022-08-13 23:36:10 +02:00
@bp.route("/register", methods=("GET", "POST"))
2023-06-25 09:24:44 +02:00
@anon_required
2022-08-13 23:36:10 +02:00
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
2023-06-24 16:05:05 +02:00
if current_app.config["DISABLE_REGISTER"]:
2024-01-22 16:06:03 +01:00
flash(_("L'enregistrement de nouveaux utilisateurs a été désactivé par l'administrateur."))
2023-06-24 16:05:05 +02:00
return redirect(url_for("auth.login"))
2022-08-13 23:36:10 +02:00
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
2023-12-15 13:38:32 +01:00
error = create_user(username, password)
if error is not None:
flash(error)
else:
2024-01-17 12:56:01 +01:00
user = User(name=username)
2024-01-22 16:06:03 +01:00
flash(_("Utilisateur créé avec succès. Vous pouvez vous connecter."))
2022-08-13 23:36:10 +02:00
2024-01-17 12:56:01 +01:00
logging.log(
[user.username, user.id, False],
logging.LogEntry.NEW_USER
)
2022-08-13 23:36:10 +02:00
return render_template("auth/register.html")
@bp.route("/login", methods=("GET", "POST"))
2023-06-25 09:24:44 +02:00
@anon_required
2022-08-13 23:36:10 +02:00
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
db = get_db()
error = None
user = db.execute(
"SELECT * FROM user WHERE username = ?", (username,)
).fetchone()
2023-06-24 15:37:43 +02:00
if (user is None) or not check_password_hash(user["password"], password):
2024-01-17 12:56:01 +01:00
logging.log([username], logging.LogEntry.FAILED_LOGIN)
2024-01-22 16:06:03 +01:00
error = _("Nom d'utilisateur ou mot de passe incorrect.")
2022-08-13 23:36:10 +02:00
if error is None:
# store the user id in a new session and return to the index
session.clear()
session["user_id"] = user["id"]
2024-01-17 12:56:01 +01:00
logging.log([username], logging.LogEntry.LOGIN)
2022-08-13 23:36:10 +02:00
return redirect(url_for("albums.index"))
flash(error)
return render_template("auth/login.html")
@bp.route("/logout")
def logout():
"""Clear the current session, including the stored user id."""
session.clear()
return redirect(url_for("auth.login"))