captive_portal.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. """Admin routes for the captive-portal feature: settings and active sessions."""
  2. from urllib.parse import urlsplit
  3. from flask import flash, redirect, render_template, request, url_for
  4. from flask_babel import gettext as _
  5. from loguru import logger
  6. from services.auth.auth_service import admin_required
  7. from services.captive_portal import config_service, session_service
  8. from services.squid.captive_portal_config_service import (
  9. disable_captive_portal,
  10. enable_captive_portal,
  11. render_block,
  12. )
  13. from services.system import system_service
  14. from .helpers import flash_and_redirect, get_config_manager, get_int_form_field
  15. _SESSION_TTL_UNITS = {
  16. "minutes": 1,
  17. "hours": 60,
  18. "days": 1440,
  19. }
  20. def _session_ttl_parts(total_minutes: int) -> tuple[int, str]:
  21. """Return a readable value and unit for the stored minute value."""
  22. for unit, multiplier in (("days", 1440), ("hours", 60), ("minutes", 1)):
  23. if total_minutes % multiplier == 0:
  24. return total_minutes // multiplier, unit
  25. return total_minutes, "minutes"
  26. def _apply_squid_state(settings: dict) -> tuple[bool, str]:
  27. """(Re)apply the captive-portal directives to squid.conf per current settings."""
  28. cm = get_config_manager()
  29. if not settings["enabled"]:
  30. return disable_captive_portal(cm)
  31. login_url = f"{settings['portal_public_url'].rstrip('/')}/portal/login"
  32. return enable_captive_portal(
  33. cm,
  34. login_url=login_url,
  35. portal_public_url=settings["portal_public_url"],
  36. acl_ttl_seconds=settings["acl_ttl_seconds"],
  37. acl_negative_ttl_seconds=settings["acl_negative_ttl_seconds"],
  38. )
  39. def register_routes(bp):
  40. @bp.route("/captive-portal", methods=["GET"])
  41. @admin_required
  42. def captive_portal_config():
  43. settings = config_service.get_config()
  44. settings["session_ttl_value"], settings["session_ttl_unit"] = (
  45. _session_ttl_parts(settings["session_ttl_minutes"])
  46. )
  47. sessions = session_service.list_active_sessions()
  48. login_url = (
  49. f"{settings['portal_public_url'].rstrip('/')}/portal/login?redirect=%s"
  50. if settings["portal_public_url"]
  51. else "<PORTAL_PUBLIC_URL>/portal/login?redirect=%s"
  52. )
  53. config_preview = render_block(
  54. login_url=login_url,
  55. portal_public_url=settings["portal_public_url"],
  56. acl_ttl_seconds=settings["acl_ttl_seconds"],
  57. acl_negative_ttl_seconds=settings["acl_negative_ttl_seconds"],
  58. )
  59. return render_template(
  60. "admin/captive_portal.html",
  61. settings=settings,
  62. sessions=sessions,
  63. config_preview=config_preview,
  64. )
  65. @bp.route("/captive-portal/save", methods=["POST"])
  66. @admin_required
  67. def captive_portal_save():
  68. portal_public_url = request.form.get("portal_public_url", "").strip()
  69. if portal_public_url:
  70. try:
  71. parsed_url = urlsplit(portal_public_url)
  72. valid_url = (
  73. parsed_url.scheme in {"http", "https"}
  74. and parsed_url.hostname
  75. and parsed_url.username is None
  76. and parsed_url.password is None
  77. and not parsed_url.query
  78. and not parsed_url.fragment
  79. and not any(
  80. char.isspace() or ord(char) < 32 for char in portal_public_url
  81. )
  82. and len(portal_public_url) <= 512
  83. )
  84. parsed_port = parsed_url.port
  85. valid_url = valid_url and (
  86. parsed_port is None or 0 <= parsed_port <= 65535
  87. )
  88. except ValueError:
  89. valid_url = False
  90. if not valid_url:
  91. flash(
  92. _(
  93. "La URL pública debe ser una URL HTTP o HTTPS válida sin credenciales."
  94. ),
  95. "error",
  96. )
  97. return redirect(url_for("admin.captive_portal_config"))
  98. session_ttl_value = get_int_form_field("session_ttl_value")
  99. session_ttl_unit = request.form.get("session_ttl_unit", "").strip()
  100. if session_ttl_value is None and request.form.get("session_ttl_minutes"):
  101. session_ttl = get_int_form_field("session_ttl_minutes")
  102. elif session_ttl_unit in _SESSION_TTL_UNITS and session_ttl_value is not None:
  103. session_ttl = session_ttl_value * _SESSION_TTL_UNITS[session_ttl_unit]
  104. else:
  105. session_ttl = None
  106. acl_ttl = get_int_form_field("acl_ttl_seconds")
  107. acl_negative_ttl = get_int_form_field("acl_negative_ttl_seconds")
  108. if session_ttl is None or not 1 <= session_ttl <= 525600:
  109. flash(
  110. _(
  111. "La duración de la sesión debe ser un valor positivo y una unidad válida"
  112. ),
  113. "error",
  114. )
  115. return redirect(url_for("admin.captive_portal_config"))
  116. if (
  117. acl_ttl is None
  118. or not 0 <= acl_ttl <= 86400
  119. or acl_negative_ttl is None
  120. or not 0 <= acl_negative_ttl <= 86400
  121. ):
  122. flash(
  123. _("Los valores de TTL de la ACL deben ser enteros no negativos"),
  124. "error",
  125. )
  126. return redirect(url_for("admin.captive_portal_config"))
  127. settings = config_service.update_config(
  128. enabled=1 if request.form.get("enabled") == "on" else 0,
  129. portal_title=request.form.get("portal_title", "SquidStats Portal").strip(),
  130. portal_public_url=portal_public_url,
  131. session_ttl_minutes=session_ttl,
  132. acl_ttl_seconds=acl_ttl,
  133. acl_negative_ttl_seconds=acl_negative_ttl,
  134. )
  135. if settings["enabled"] and not settings["portal_public_url"]:
  136. flash(
  137. _("Debes definir la URL pública del portal antes de habilitarlo"),
  138. "error",
  139. )
  140. config_service.update_config(enabled=0)
  141. return redirect(url_for("admin.captive_portal_config"))
  142. ok, message = _apply_squid_state(settings)
  143. if not ok:
  144. logger.error("Error applying captive portal configuration: %s", message)
  145. config_service.update_config(enabled=0)
  146. return flash_and_redirect(False, message, "admin.captive_portal_config")
  147. reloaded, reload_message, _details = system_service.reload_squid()
  148. if not reloaded:
  149. logger.warning(
  150. "Squid reload after captive portal update failed: %s", reload_message
  151. )
  152. message = (
  153. _("Configuración guardada, pero Squid no pudo recargarse: %s")
  154. % reload_message
  155. )
  156. return flash_and_redirect(False, message, "admin.captive_portal_config")
  157. return flash_and_redirect(True, message, "admin.captive_portal_config")
  158. @bp.route("/captive-portal/sessions/revoke", methods=["POST"])
  159. @admin_required
  160. def captive_portal_revoke_session():
  161. ip = request.form.get("ip", "").strip()
  162. ok, message = session_service.revoke_session(ip)
  163. return flash_and_redirect(ok, message, "admin.captive_portal_config")