1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# 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 .. import forms
from ..auth import DUMMY_USER, 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.
:return: 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.
:return: 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)
)
user_exists = user is not None
if user is None:
user = DUMMY_USER
if (
form.password.data is None
or not user.check_password(form.password.data)
or not user_exists
):
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.
:return: Redirect response to the application index.
"""
logout_user()
return redirect(url_for("root.index"))
|