| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- """
- Shared helpers for admin route modules.
- Centralizes repetitive patterns: flash+redirect, debug detection,
- form field parsing, JSON error responses, and config_manager access.
- """
- import re
- from flask import current_app, flash, jsonify, redirect, request, url_for
- from loguru import logger
- from utils.admin import SquidConfigManager
- # ---------------------------------------------------------------------------
- # Config manager accessor (replaces global mutable)
- # ---------------------------------------------------------------------------
- def get_config_manager() -> SquidConfigManager:
- """Return the shared :class:`SquidConfigManager` instance.
- Stored on ``current_app`` so it lives for the app's lifetime without
- needing a module-level mutable global.
- """
- cm = getattr(current_app, "_squid_config_manager", None)
- if cm is None:
- cm = SquidConfigManager()
- current_app._squid_config_manager = cm
- return cm
- def reload_config_manager() -> SquidConfigManager:
- """Force-reload the :class:`SquidConfigManager` (e.g. after split)."""
- cm = SquidConfigManager()
- current_app._squid_config_manager = cm
- logger.info("Config manager reloaded")
- return cm
- # ---------------------------------------------------------------------------
- # Flash + Redirect helper
- # ---------------------------------------------------------------------------
- def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
- """Flash a message and redirect to *endpoint* in a single call."""
- flash(message, "success" if success else "error")
- return redirect(url_for(endpoint, **kwargs))
- # ---------------------------------------------------------------------------
- # Debug mode helper
- # ---------------------------------------------------------------------------
- def is_debug() -> bool:
- """Return ``True`` when the Flask app is running in debug mode.
- Safely handles the case where no application context is active.
- """
- try:
- return bool(current_app.debug)
- except RuntimeError:
- return False
- # ---------------------------------------------------------------------------
- # Form field parsing helpers
- # ---------------------------------------------------------------------------
- def get_int_form_field(name: str) -> int | None:
- """Parse an integer from ``request.form[name]``.
- Returns ``None`` when the value is missing or not a valid integer.
- """
- try:
- return int(request.form.get(name))
- except (ValueError, TypeError):
- return None
- # ---------------------------------------------------------------------------
- # JSON error response helpers
- # ---------------------------------------------------------------------------
- def _contains_stack_trace_error_hint(text: str) -> bool:
- """Detect indicators of stack traces or exception text."""
- normalized = text.lower()
- suspects = ("traceback", "stack trace", "stack_trace", "stacktrace")
- if any(token in normalized for token in suspects):
- return True
- exception_pattern = r"\b[A-Za-z_][A-Za-z0-9_.]*(?:Error|Exception):"
- return re.search(exception_pattern, text) is not None
- def _sanitize_error_details(details: str) -> str:
- return "[REDACTED; check logs]"
- def sanitize_error_page_message(message: str) -> str:
- """Sanitize user-facing error page message to avoid leaking diagnostic traces."""
- if _contains_stack_trace_error_hint(message):
- return "Unexpected internal failure"
- return message
- def json_error(message: str, status_code: int = 400, *, details: str | None = None):
- """Build a standard JSON error response.
- When the app is in debug mode and *details* is provided, the details
- are included in the payload.
- """
- resp = {
- "status": "error",
- "message": _sanitize_response_value("message", message),
- }
- if is_debug() and details:
- resp["details"] = _sanitize_error_details(details)
- return jsonify(resp), status_code
- def _sanitize_response_value(key: str, value):
- """Sanitize a single response payload value."""
- forbidden = {"stack", "stack_trace", "trace", "traceback", "exception", "error"}
- if key.lower() in forbidden:
- return "[REDACTED]"
- if isinstance(value, Exception):
- return "[REDACTED]"
- if isinstance(value, str) and _contains_stack_trace_error_hint(value):
- return "[REDACTED]"
- if isinstance(value, dict):
- return _sanitize_response_payload(value)
- if isinstance(value, (list, tuple)):
- sanitized_sequence = [_sanitize_response_value("", item) for item in value]
- return type(value)(sanitized_sequence)
- return value
- def _sanitize_response_payload(payload: dict) -> dict:
- """Remove sensitive fields that may expose stack traces or exception info."""
- if not payload:
- return {}
- sanitized = {}
- for key, value in payload.items():
- sanitized[key] = _sanitize_response_value(key, value)
- return sanitized
- def json_success(message: str, *, extra: dict | None = None):
- """Build a standard JSON success response."""
- resp = {
- "status": "success",
- "message": _sanitize_response_value("message", message),
- }
- if extra:
- for key, value in extra.items():
- if key == "unread_count" and type(value) is int:
- resp[key] = value
- else:
- resp[key] = "[REDACTED]"
- return jsonify(resp)
- # ---------------------------------------------------------------------------
- # Flash error with debug details
- # ---------------------------------------------------------------------------
- def flash_error_with_details(user_message: str, exception: Exception | None = None):
- """Flash an error message; include exception details in debug mode."""
- if is_debug() and exception is not None:
- flash(f"{user_message}: {exception}", "error")
- else:
- flash(user_message, "error")
|