api_routes.py 11 KB

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