# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Configure user authentication and session loading.""" import hashlib import secrets from functools import cache from hmac import compare_digest from urllib.parse import urlsplit from flask import request from flask_limiter.util import get_remote_address from flask_login import LoginManager from werkzeug.security import generate_password_hash from .extensions import db from .models import User from .validation import is_control_character login_manager = LoginManager() login_manager.login_view = "webmentions.login" # pyright: ignore[reportAttributeAccessIssue] MIN_PASSWORD_LENGTH = 8 @cache def dummy_password_hash() -> str: """Lazily generate a reusable hash for unknown login usernames. The hash is calculated once and reused so missing accounts follow a comparable password-check path. :returns: Reusable password hash for timing-safe unknown-user authentication. """ return generate_password_hash(secrets.token_urlsafe()) def validate_new_password(password: str) -> None: """Validate newly chosen passwords without arbitrary composition rules. Allow Unicode, whitespace-only passwords, and arbitrarily long passphrases, but reject empty passwords and control characters. :param password: Proposed new password to validate. :raises ValueError: If the password is empty, too short, or contains control characters. """ if not password: raise ValueError("Password must not be empty.") if len(password) < MIN_PASSWORD_LENGTH: raise ValueError( f"Password must be at least {MIN_PASSWORD_LENGTH} characters long." ) if any(is_control_character(char) for char in password): raise ValueError("Password must not contain control characters.") @login_manager.user_loader def load_user_from_session_id(session_id: object) -> User | None: """Load a user from the database by identifier. :param session_id: Database ID and password-hash fingerprint stored in the session. :returns: Matching user, or ``None`` if no user exists with the identifier. """ if not isinstance(session_id, str): return None user_id, _, _ = session_id.partition(":") if not (user_id.isascii() and user_id.isdecimal() and len(user_id) <= 19): return None user = db.session.get(User, int(user_id)) if user is None or not compare_digest(session_id.encode(), user.get_id().encode()): return None return user def login_username_rate_limit_key() -> str: """Group usernames across IPs without exposing plaintext to rate-limit storage. :returns: Hashed username rate-limit key, or an IP-specific key if no username was submitted. """ username = request.form.get("username", "").strip().casefold() if not username: return f"missing-username:{get_remote_address()}" digest = hashlib.sha256(username.encode("utf-8")).hexdigest() return f"username:{digest}" def is_safe_next_url(next_url: str) -> bool: """Allow redirects only to paths on this site. :param next_url: Requested post-login redirect path. :returns: ``True`` if the redirect is a safe site-local path. """ if "\\" in next_url or not next_url.startswith("/") or next_url.startswith("//"): return False try: target = urlsplit(next_url) except ValueError: return False return ( not target.netloc and target.path.startswith("/") and not target.path.startswith("//") )