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
|
# 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 werkzeug.security import check_password_hash
from .. import forms
from ..auth import dummy_password_hash, is_safe_next_url, login_username_rate_limit_key
from ..extensions import db, limiter
from ..models import User
from .blueprint import webmentions_bp
@webmentions_bp.route("/")
def index() -> ResponseReturnValue:
"""Redirect to the received Webmentions view.
:returns: Redirect response to the received Webmentions view.
"""
return redirect(url_for("webmentions.received_list"))
@webmentions_bp.route("/login", methods=["GET", "POST"])
@limiter.limit(
lambda: current_app.config["LOGIN_USERNAME_RATE_LIMIT"],
key_func=login_username_rate_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("webmentions.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("webmentions.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("webmentions.index")
return redirect(next_url)
return render_template("login.html", form=form)
@webmentions_bp.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("webmentions.index"))
|