from __future__ import annotations from urllib.parse import urlsplit from flask import Blueprint, flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user, logout_user from app.auth.forms import LoginForm from app.models import Account bp = Blueprint("auth", __name__, url_prefix="/auth") @bp.route("/login", methods=["GET", "POST"]) def login(): if current_user.is_authenticated: return redirect(url_for("main.dashboard")) form = LoginForm() if form.validate_on_submit(): username = form.username.data.strip().lower() account = Account.query.filter_by(username=username).first() if account and account.active and account.check_password(form.password.data): login_user(account, remember=form.remember.data) next_url = request.args.get("next") if not next_url or urlsplit(next_url).netloc: next_url = url_for("main.dashboard") return redirect(next_url) flash("Invalid username or password.", "danger") return render_template("auth/login.html", form=form) @bp.post("/logout") @login_required def logout(): logout_user() flash("You have been signed out.", "info") return redirect(url_for("auth.login"))