# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Authentication and session routes.""" import sqlalchemy as sa from flask import current_app, flash, redirect, render_template, request, url_for from flask.typing import ResponseReturnValue from flask_login import current_user, login_required, login_user, logout_user from werkzeug.security import check_password_hash from .. import forms from ..auth import dummy_password_hash, is_safe_next_url, login_username_limit_key from ..extensions import db, limiter from ..models import User from .blueprint import root_page @root_page.route("/") def index() -> ResponseReturnValue: """Redirect to the received Webmentions view. :returns: Redirect response to the received Webmentions view. """ return redirect(url_for("root.received")) @root_page.route("/login", methods=["GET", "POST"]) @limiter.limit( lambda: current_app.config["LOGIN_USERNAME_RATE_LIMIT"], key_func=login_username_limit_key, methods=["POST"], error_message="Too many login attempts. Please try again later.", ) @limiter.limit( lambda: current_app.config["LOGIN_RATE_LIMIT"], methods=["POST"], error_message="Too many login attempts. Please try again later.", ) def login() -> ResponseReturnValue: """Authenticate a user and start a login session. Authenticated users are redirected to the application index. After a successful login, the user is redirected to the requested local URL when provided. :returns: Rendered login page or redirect response. """ if current_user.is_authenticated: return redirect(url_for("root.index")) form = forms.LoginForm() if form.validate_on_submit(): user = db.session.scalar( sa.select(User).where(User.username == form.username.data) ) password_hash = user.password_hash if user else dummy_password_hash() password_ok = check_password_hash(password_hash, form.password.data or "") if user is None or not password_ok: flash("Invalid username or password", "danger") return redirect(url_for("root.login")) login_user(user) next_url = request.args.get("next") if not next_url or not is_safe_next_url(next_url): next_url = url_for("root.index") return redirect(next_url) return render_template("login.html", form=form) @root_page.route("/logout", methods=("POST",)) @login_required def logout() -> ResponseReturnValue: """End the current user's login session. :returns: Redirect response to the application index. """ logout_user() return redirect(url_for("root.index"))