# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Configure user authentication and session loading.""" import hashlib import secrets 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 .extensions import db from .models import User from .validation import is_control_character AUTH = LoginManager() AUTH.login_view = "root.login" # pyright: ignore[reportAttributeAccessIssue] MIN_PASSWORD_LENGTH = 8 DUMMY_USER = User(username=secrets.token_urlsafe()) DUMMY_USER.password = secrets.token_urlsafe() def validate_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. """ 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.") @AUTH.user_loader def load_user(session_id: str) -> User | None: """Load a user from the database by identifier. :param session_id: Database ID and password-hash fingerprint stored in the session. :return: Matching user, or ``None`` if no user exists with the identifier. """ try: user_id, fingerprint = session_id.split(":", 1) if ( not user_id.isascii() or not user_id.isdecimal() or len(user_id) > 19 or len(fingerprint) != 64 or any(char not in "0123456789abcdef" for char in fingerprint) ): return None user = db.session.get(User, int(user_id)) except AttributeError, TypeError, ValueError: return None if user is None: return None if not compare_digest(session_id, user.get_id()): return None return user def login_username_limit_key() -> str: """Group usernames across IPs without exposing plaintext to rate-limit storage.""" 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.""" 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.scheme and not target.netloc and target.path.startswith("/") and not target.path.startswith("//") )