api_routes.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. from flask import Blueprint, jsonify, request
  2. from flask_babel import gettext as _
  3. from loguru import logger
  4. from werkzeug.exceptions import BadRequest
  5. from database.database import get_session
  6. from routes.admin.helpers import get_config_manager, json_error, json_success
  7. from services.analytics.auditoria_service import (
  8. get_all_usernames,
  9. run_audit_operation,
  10. )
  11. from services.auth.auth_service import api_admin_required
  12. from services.notifications.notifications import (
  13. delete_all_notifications,
  14. delete_notification,
  15. get_all_notifications,
  16. mark_notifications_read,
  17. )
  18. from services.squid.connection_reset_service import reset_client_connections
  19. from services.squid.user_restrictions_service import (
  20. block_user,
  21. get_user_status,
  22. throttle_user,
  23. unblock_user,
  24. unthrottle_user,
  25. )
  26. from services.system.metrics_service import MetricsService
  27. from services.system.system_service import reload_squid, restart_squid
  28. api_bp = Blueprint("api", __name__)
  29. REQUIRED_FIELDS = {
  30. "user_summary": ["username"],
  31. "daily_activity": ["start_date", "end_date"],
  32. "keyword_search": ["keyword"],
  33. "social_media_activity": ["social_media_sites"],
  34. "ip_activity": ["ip_address"],
  35. "response_code_search": ["response_code"],
  36. "total_data_consumed": ["start_date", "end_date"],
  37. }
  38. @api_bp.route("/metrics/today")
  39. def get_today_metrics():
  40. try:
  41. results = MetricsService.get_metrics_today()
  42. return jsonify(results)
  43. except Exception as e:
  44. logger.error(f"Error retrieving today's metrics: {e}")
  45. return jsonify([])
  46. @api_bp.route("/metrics/24hours")
  47. def get_24hours_metrics():
  48. try:
  49. results = MetricsService.get_metrics_last_24_hours()
  50. return jsonify(results)
  51. except Exception as e:
  52. logger.error(f"Error retrieving 24 hours metrics: {e}")
  53. return jsonify([])
  54. @api_bp.route("/metrics/latest")
  55. def get_latest_metric():
  56. try:
  57. result = MetricsService.get_latest_metric()
  58. return jsonify(result) if result else jsonify({})
  59. except Exception as e:
  60. logger.error(f"Error retrieving latest metric: {e}")
  61. return jsonify({})
  62. @api_bp.route("/all-users", methods=["GET"])
  63. def api_get_all_users():
  64. db = get_session()
  65. try:
  66. users = get_all_usernames(db)
  67. return jsonify(users)
  68. except Exception:
  69. logger.exception("Error retrieving all users")
  70. return jsonify({"error": _("Internal server error")}), 500
  71. finally:
  72. db.close()
  73. @api_bp.route("/run-audit", methods=["POST"])
  74. def api_run_audit():
  75. data = request.get_json()
  76. if not data:
  77. return jsonify({"error": _("Invalid JSON body")}), 400
  78. audit_type = data.get("audit_type")
  79. db = get_session()
  80. try:
  81. validate_required_fields(audit_type, data)
  82. result = run_audit_operation(db, audit_type, data)
  83. return jsonify(result)
  84. except BadRequest as e:
  85. logger.warning(f"Bad request in audit API: {e}")
  86. return jsonify({"error": _("Bad request")}), 400
  87. except ValueError:
  88. return jsonify({"error": _("Invalid numeric value")}), 400
  89. except Exception:
  90. logger.exception("Audit API error")
  91. return jsonify({"error": _("Internal server error")}), 500
  92. finally:
  93. db.close()
  94. # API para notificaciones del sistema
  95. @api_bp.route("/notifications", methods=["GET"])
  96. def api_get_notifications():
  97. try:
  98. page = request.args.get("page", 1, type=int)
  99. per_page = request.args.get("per_page", 20, type=int)
  100. return jsonify(get_all_notifications(page=page, per_page=per_page))
  101. except Exception as e:
  102. logger.error(f"Error getting notifications: {e}")
  103. return jsonify({"unread_count": 0, "notifications": [], "pagination": {}})
  104. @api_bp.route("/notifications/mark-read", methods=["POST"])
  105. def api_mark_notifications_read():
  106. try:
  107. data = request.get_json()
  108. notification_ids = data.get("notification_ids", data.get("ids", []))
  109. mark_notifications_read(notification_ids)
  110. return jsonify(
  111. {"success": True, "unread_count": get_all_notifications()["unread_count"]}
  112. )
  113. except Exception:
  114. logger.exception("Error marking notifications as read")
  115. return jsonify({"success": False, "error": _("Internal server error")}), 500
  116. @api_bp.route("/notifications/<int:notification_id>", methods=["DELETE"])
  117. def api_delete_notification(notification_id):
  118. try:
  119. delete_notification(notification_id)
  120. return json_success(
  121. "Notification deleted",
  122. extra={"unread_count": get_all_notifications()["unread_count"]},
  123. )
  124. except Exception:
  125. logger.exception("Error deleting notification")
  126. return json_error("Internal server error", 500)
  127. @api_bp.route("/notifications/delete-all", methods=["DELETE"])
  128. def api_delete_all_notifications():
  129. try:
  130. delete_all_notifications()
  131. return json_success("All notifications deleted", extra={"unread_count": 0})
  132. except Exception:
  133. logger.exception("Error deleting all notifications")
  134. return json_error("Internal server error", 500)
  135. @api_bp.route("/restart-squid", methods=["POST"])
  136. @api_admin_required
  137. def api_restart_squid():
  138. success, message, _details = restart_squid()
  139. if success:
  140. return json_success(message)
  141. return json_error(
  142. message or "Could not restart squid",
  143. 500,
  144. )
  145. @api_bp.route("/reload-squid", methods=["POST"])
  146. @api_admin_required
  147. def api_reload_squid():
  148. success, message, _details = reload_squid()
  149. if success:
  150. return json_success(message)
  151. return json_error(
  152. message or "Could not reload squid",
  153. 500,
  154. )
  155. def validate_required_fields(audit_type, data):
  156. required = REQUIRED_FIELDS.get(audit_type, [])
  157. missing = [field for field in required if not data.get(field)]
  158. if missing:
  159. raise BadRequest(f"Missing required fields: {', '.join(missing)}")
  160. # ---------------------------------------------------------------------------
  161. # Connections: block / throttle actions
  162. # ---------------------------------------------------------------------------
  163. @api_bp.route("/connections/status", methods=["GET"])
  164. @api_admin_required
  165. def api_connection_status():
  166. ip = request.args.get("ip", "").strip()
  167. if not ip:
  168. return json_error("Se requiere el parámetro 'ip'", 400)
  169. db = get_session()
  170. try:
  171. status = get_user_status(ip, db)
  172. return jsonify({"status": "success", **status})
  173. except Exception:
  174. logger.exception("Error getting connection status")
  175. return json_error("Error interno", 500)
  176. finally:
  177. db.close()
  178. @api_bp.route("/connections/block", methods=["POST"])
  179. @api_admin_required
  180. def api_block_user():
  181. data = request.get_json(silent=True) or {}
  182. username = str(data.get("username", "")).strip()
  183. ip = str(data.get("ip", "")).strip()
  184. if not username or not ip:
  185. return json_error("Se requieren los campos 'username' e 'ip'", 400)
  186. db = get_session()
  187. try:
  188. cm = get_config_manager()
  189. success, message = block_user(username, ip, db, cm)
  190. if success:
  191. reload_squid()
  192. return json_success(message)
  193. return json_error(message, 409)
  194. except Exception:
  195. logger.exception("Error blocking user")
  196. return json_error("Error interno al bloquear el usuario", 500)
  197. finally:
  198. db.close()
  199. @api_bp.route("/connections/unblock", methods=["POST"])
  200. @api_admin_required
  201. def api_unblock_user():
  202. data = request.get_json(silent=True) or {}
  203. username = str(data.get("username", "")).strip()
  204. ip = str(data.get("ip", "")).strip()
  205. if not username or not ip:
  206. return json_error("Se requieren los campos 'username' e 'ip'", 400)
  207. db = get_session()
  208. try:
  209. cm = get_config_manager()
  210. success, message = unblock_user(username, ip, db, cm)
  211. if success:
  212. reload_squid()
  213. return json_success(message)
  214. return json_error(message, 409)
  215. except Exception:
  216. logger.exception("Error unblocking user")
  217. return json_error("Error interno al desbloquear el usuario", 500)
  218. finally:
  219. db.close()
  220. @api_bp.route("/connections/throttle", methods=["POST"])
  221. @api_admin_required
  222. def api_throttle_user():
  223. data = request.get_json(silent=True) or {}
  224. username = str(data.get("username", "")).strip()
  225. ip = str(data.get("ip", "")).strip()
  226. try:
  227. pool_number = int(data.get("pool_number"))
  228. except (TypeError, ValueError):
  229. return json_error("El campo 'pool_number' debe ser un entero", 400)
  230. if not username or not ip:
  231. return json_error(
  232. "Se requieren los campos 'username', 'ip' y 'pool_number'", 400
  233. )
  234. db = get_session()
  235. try:
  236. cm = get_config_manager()
  237. success, message = throttle_user(username, ip, pool_number, db, cm)
  238. if success:
  239. reload_squid()
  240. return json_success(message)
  241. return json_error(message, 409)
  242. except Exception:
  243. logger.exception("Error throttling user")
  244. return json_error("Error interno al reducir la velocidad", 500)
  245. finally:
  246. db.close()
  247. @api_bp.route("/connections/unthrottle", methods=["POST"])
  248. @api_admin_required
  249. def api_unthrottle_user():
  250. data = request.get_json(silent=True) or {}
  251. username = str(data.get("username", "")).strip()
  252. ip = str(data.get("ip", "")).strip()
  253. if not username or not ip:
  254. return json_error("Se requieren los campos 'username' e 'ip'", 400)
  255. db = get_session()
  256. try:
  257. cm = get_config_manager()
  258. success, message = unthrottle_user(username, ip, db, cm)
  259. if success:
  260. reload_squid()
  261. return json_success(message)
  262. return json_error(message, 409)
  263. except Exception:
  264. logger.exception("Error unthrottling user")
  265. return json_error("Error interno al restaurar la velocidad", 500)
  266. finally:
  267. db.close()
  268. @api_bp.route("/connections/reset", methods=["POST"])
  269. @api_admin_required
  270. def api_reset_client_connections():
  271. data = request.get_json(silent=True) or {}
  272. ip = str(data.get("ip", "")).strip()
  273. # print(f"=== DEBUG api_reset_client_connections: data={data!r}, ip={ip!r}")
  274. if not ip:
  275. return json_error("Se requiere el campo 'ip'", 400)
  276. success, message, details = reset_client_connections(ip)
  277. if success:
  278. return json_success(message)
  279. return json_error(message, 501 if "soportado" in message else 409, details=details)
  280. @api_bp.route("/delay-pools", methods=["GET"])
  281. @api_admin_required
  282. def api_list_delay_pools():
  283. try:
  284. cm = get_config_manager()
  285. pools = cm.get_delay_pools()
  286. return jsonify({"status": "success", "pools": pools})
  287. except Exception:
  288. logger.exception("Error listing delay pools")
  289. return json_error("Error interno al listar delay pools", 500)