helpers.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. Shared helpers for admin route modules.
  3. Centralizes repetitive patterns: flash+redirect, debug detection,
  4. form field parsing, JSON error responses, and config_manager access.
  5. """
  6. from flask import current_app, flash, jsonify, redirect, request, url_for
  7. from loguru import logger
  8. from utils.admin import SquidConfigManager
  9. # ---------------------------------------------------------------------------
  10. # Config manager accessor (replaces global mutable)
  11. # ---------------------------------------------------------------------------
  12. def get_config_manager() -> SquidConfigManager:
  13. """Return the shared :class:`SquidConfigManager` instance.
  14. Stored on ``current_app`` so it lives for the app's lifetime without
  15. needing a module-level mutable global.
  16. """
  17. cm = getattr(current_app, "_squid_config_manager", None)
  18. if cm is None:
  19. cm = SquidConfigManager()
  20. current_app._squid_config_manager = cm
  21. return cm
  22. def reload_config_manager() -> SquidConfigManager:
  23. """Force-reload the :class:`SquidConfigManager` (e.g. after split)."""
  24. cm = SquidConfigManager()
  25. current_app._squid_config_manager = cm
  26. logger.info("Config manager reloaded")
  27. return cm
  28. # ---------------------------------------------------------------------------
  29. # Flash + Redirect helper
  30. # ---------------------------------------------------------------------------
  31. def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
  32. """Flash a message and redirect to *endpoint* in a single call."""
  33. flash(message, "success" if success else "error")
  34. return redirect(url_for(endpoint, **kwargs))
  35. # ---------------------------------------------------------------------------
  36. # Debug mode helper
  37. # ---------------------------------------------------------------------------
  38. def is_debug() -> bool:
  39. """Return ``True`` when the Flask app is running in debug mode.
  40. Safely handles the case where no application context is active.
  41. """
  42. try:
  43. return bool(current_app.debug)
  44. except RuntimeError:
  45. return False
  46. # ---------------------------------------------------------------------------
  47. # Form field parsing helpers
  48. # ---------------------------------------------------------------------------
  49. def get_int_form_field(name: str) -> int | None:
  50. """Parse an integer from ``request.form[name]``.
  51. Returns ``None`` when the value is missing or not a valid integer.
  52. """
  53. try:
  54. return int(request.form.get(name))
  55. except (ValueError, TypeError):
  56. return None
  57. # ---------------------------------------------------------------------------
  58. # JSON error response helpers
  59. # ---------------------------------------------------------------------------
  60. def _contains_stack_trace_error_hint(text: str) -> bool:
  61. """Detect indicators of stack traces or exception text."""
  62. normalized = text.lower()
  63. suspects = ("traceback", "exception", "stack", "stack_trace", "stacktrace", "error")
  64. return any(token in normalized for token in suspects)
  65. def _sanitize_error_details(details: str) -> str:
  66. return "[REDACTED; check logs]"
  67. def sanitize_error_page_message(message: str) -> str:
  68. """Sanitize user-facing error page message to avoid leaking diagnostic traces."""
  69. if _contains_stack_trace_error_hint(message):
  70. return "Unexpected internal failure"
  71. return message
  72. def json_error(message: str, status_code: int = 400, *, details: str | None = None):
  73. """Build a standard JSON error response.
  74. When the app is in debug mode and *details* is provided, the details
  75. are included in the payload.
  76. """
  77. resp = {"status": "error", "message": message}
  78. if is_debug() and details:
  79. resp["details"] = _sanitize_error_details(details)
  80. return jsonify(resp), status_code
  81. def _sanitize_response_value(key: str, value):
  82. """Sanitize a single response payload value."""
  83. forbidden = {"stack", "stack_trace", "trace", "traceback", "exception", "error"}
  84. if key.lower() in forbidden:
  85. return "[REDACTED]"
  86. if isinstance(value, Exception):
  87. return "[REDACTED]"
  88. if isinstance(value, str) and _contains_stack_trace_error_hint(value):
  89. return "[REDACTED]"
  90. if isinstance(value, dict):
  91. return _sanitize_response_payload(value)
  92. if isinstance(value, (list, tuple)):
  93. sanitized_sequence = [_sanitize_response_value("", item) for item in value]
  94. return type(value)(sanitized_sequence)
  95. return value
  96. def _sanitize_response_payload(payload: dict) -> dict:
  97. """Remove sensitive fields that may expose stack traces or exception info."""
  98. if not payload:
  99. return {}
  100. sanitized = {}
  101. for key, value in payload.items():
  102. sanitized[key] = _sanitize_response_value(key, value)
  103. return sanitized
  104. def json_success(message: str, *, extra: dict | None = None):
  105. """Build a standard JSON success response."""
  106. resp = {"status": "success", "message": message}
  107. if extra:
  108. resp.update(_sanitize_response_payload(extra))
  109. return jsonify(resp)
  110. # ---------------------------------------------------------------------------
  111. # Flash error with debug details
  112. # ---------------------------------------------------------------------------
  113. def flash_error_with_details(user_message: str, exception: Exception | None = None):
  114. """Flash an error message; include exception details in debug mode."""
  115. if is_debug() and exception is not None:
  116. flash(f"{user_message}: {exception}", "error")
  117. else:
  118. flash(user_message, "error")