api_routes.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from flask import Blueprint, current_app, jsonify, request
  2. from loguru import logger
  3. from werkzeug.exceptions import BadRequest
  4. from database.database import get_session
  5. from services.analytics.auditoria_service import (
  6. find_by_ip,
  7. find_by_keyword,
  8. find_by_response_code,
  9. find_denied_access,
  10. find_social_media_activity,
  11. get_all_usernames,
  12. get_daily_activity,
  13. get_top_ips_by_data,
  14. get_top_urls_by_data,
  15. get_top_users_by_data,
  16. get_top_users_by_requests,
  17. get_total_data_consumed,
  18. get_user_activity_summary,
  19. )
  20. from services.auth.auth_service import admin_required
  21. from services.notifications.notifications import (
  22. delete_all_notifications,
  23. delete_notification,
  24. get_all_notifications,
  25. mark_notifications_read,
  26. )
  27. from services.system.metrics_service import MetricsService
  28. from services.system.system_service import reload_squid, restart_squid
  29. api_bp = Blueprint("api", __name__)
  30. REQUIRED_FIELDS = {
  31. "user_summary": ["username"],
  32. "daily_activity": ["start_date", "end_date"],
  33. "keyword_search": ["keyword"],
  34. "social_media_activity": ["social_media_sites"],
  35. "ip_activity": ["ip_address"],
  36. "response_code_search": ["response_code"],
  37. "total_data_consumed": ["start_date", "end_date"],
  38. }
  39. AUDIT_HANDLERS = {
  40. "user_summary": lambda db, d: get_user_activity_summary(
  41. db, d["username"], d.get("start_date"), d.get("end_date")
  42. ),
  43. "top_users_data": lambda db, d: get_top_users_by_data(
  44. db, d.get("start_date"), d.get("end_date")
  45. ),
  46. "top_urls_data": lambda db, d: get_top_urls_by_data(
  47. db, d.get("start_date"), d.get("end_date")
  48. ),
  49. "top_users_requests": lambda db, d: get_top_users_by_requests(
  50. db, d.get("start_date"), d.get("end_date")
  51. ),
  52. "top_ips_data": lambda db, d: get_top_ips_by_data(
  53. db, d.get("start_date"), d.get("end_date")
  54. ),
  55. "daily_activity": lambda db, d: get_daily_activity(
  56. db, d["start_date"], d.get("username")
  57. ),
  58. "denied_access": lambda db, d: find_denied_access(
  59. db, d.get("start_date"), d.get("end_date"), d.get("username")
  60. ),
  61. "keyword_search": lambda db, d: find_by_keyword(
  62. db, d.get("start_date"), d.get("end_date"), d["keyword"], d.get("username")
  63. ),
  64. "social_media_activity": lambda db, d: find_social_media_activity(
  65. db,
  66. d.get("start_date"),
  67. d.get("end_date"),
  68. d["social_media_sites"],
  69. d.get("username"),
  70. ),
  71. "ip_activity": lambda db, d: find_by_ip(
  72. db, d.get("start_date"), d.get("end_date"), d["ip_address"]
  73. ),
  74. "response_code_search": lambda db, d: find_by_response_code(
  75. db,
  76. d.get("start_date"),
  77. d.get("end_date"),
  78. int(d["response_code"]),
  79. d.get("username"),
  80. ),
  81. "total_data_consumed": lambda db, d: get_total_data_consumed(
  82. db, d["start_date"], d["end_date"]
  83. ),
  84. }
  85. @api_bp.route("/metrics/today")
  86. def get_today_metrics():
  87. try:
  88. results = MetricsService.get_metrics_today()
  89. return jsonify(results)
  90. except Exception as e:
  91. logger.error(f"Error retrieving today's metrics: {e}")
  92. return jsonify([])
  93. @api_bp.route("/metrics/24hours")
  94. def get_24hours_metrics():
  95. try:
  96. results = MetricsService.get_metrics_last_24_hours()
  97. return jsonify(results)
  98. except Exception as e:
  99. logger.error(f"Error retrieving 24 hours metrics: {e}")
  100. return jsonify([])
  101. @api_bp.route("/metrics/latest")
  102. def get_latest_metric():
  103. try:
  104. result = MetricsService.get_latest_metric()
  105. return jsonify(result) if result else jsonify({})
  106. except Exception as e:
  107. logger.error(f"Error retrieving latest metric: {e}")
  108. return jsonify({})
  109. @api_bp.route("/all-users", methods=["GET"])
  110. def api_get_all_users():
  111. db = get_session()
  112. try:
  113. users = get_all_usernames(db)
  114. return jsonify(users)
  115. except Exception as e:
  116. logger.exception("Error retrieving all users")
  117. try:
  118. show_details = bool(current_app.debug)
  119. except RuntimeError:
  120. show_details = False
  121. resp = {"error": "Internal server error"}
  122. if show_details:
  123. resp["details"] = str(e)
  124. return jsonify(resp), 500
  125. finally:
  126. db.close()
  127. @api_bp.route("/run-audit", methods=["POST"])
  128. def api_run_audit():
  129. data = request.get_json()
  130. if not data:
  131. return jsonify({"error": "Invalid JSON body"}), 400
  132. audit_type = data.get("audit_type")
  133. if audit_type not in AUDIT_HANDLERS:
  134. return jsonify({"error": "Invalid audit type"}), 400
  135. db = get_session()
  136. try:
  137. validate_required_fields(audit_type, data)
  138. result = AUDIT_HANDLERS[audit_type](db, data)
  139. return jsonify(result)
  140. except BadRequest as e:
  141. logger.warning(f"Bad request in audit API: {e}")
  142. return jsonify({"error": "Bad request"}), 400
  143. except ValueError:
  144. return jsonify({"error": "Invalid numeric value"}), 400
  145. except Exception:
  146. logger.exception("Audit API error")
  147. return jsonify({"error": "Internal server error"}), 500
  148. finally:
  149. db.close()
  150. # API para notificaciones del sistema
  151. @api_bp.route("/notifications", methods=["GET"])
  152. def api_get_notifications():
  153. try:
  154. page = request.args.get("page", 1, type=int)
  155. per_page = request.args.get("per_page", 20, type=int)
  156. return jsonify(get_all_notifications(page=page, per_page=per_page))
  157. except Exception as e:
  158. logger.error(f"Error getting notifications: {e}")
  159. return jsonify({"unread_count": 0, "notifications": [], "pagination": {}})
  160. @api_bp.route("/notifications/mark-read", methods=["POST"])
  161. def api_mark_notifications_read():
  162. try:
  163. data = request.get_json()
  164. notification_ids = data.get("notification_ids", data.get("ids", []))
  165. mark_notifications_read(notification_ids)
  166. return jsonify(
  167. {"success": True, "unread_count": get_all_notifications()["unread_count"]}
  168. )
  169. except Exception as e:
  170. logger.exception("Error marking notifications as read")
  171. try:
  172. show_details = bool(current_app.debug)
  173. except RuntimeError:
  174. show_details = False
  175. resp = {"success": False, "error": "Internal server error"}
  176. if show_details:
  177. resp["details"] = str(e)
  178. return jsonify(resp), 500
  179. @api_bp.route("/notifications/<int:notification_id>", methods=["DELETE"])
  180. def api_delete_notification(notification_id):
  181. try:
  182. delete_notification(notification_id)
  183. return jsonify(
  184. {"success": True, "unread_count": get_all_notifications()["unread_count"]}
  185. )
  186. except Exception as e:
  187. logger.error(f"Error deleting notification: {e}")
  188. return jsonify({"success": False, "error": "Internal server error"}), 500
  189. @api_bp.route("/notifications/delete-all", methods=["DELETE"])
  190. def api_delete_all_notifications():
  191. try:
  192. delete_all_notifications()
  193. return jsonify({"success": True, "unread_count": 0})
  194. except Exception as e:
  195. logger.error(f"Error deleting all notifications: {e}")
  196. return jsonify({"success": False, "error": "Internal server error"}), 500
  197. @api_bp.route("/restart-squid", methods=["POST"])
  198. @admin_required
  199. def api_restart_squid():
  200. success, message, details = restart_squid()
  201. status_code = 200 if success else 500
  202. response = {"success": success, "message": message}
  203. if details:
  204. response["details"] = details
  205. return jsonify(response), status_code
  206. @api_bp.route("/reload-squid", methods=["POST"])
  207. @admin_required
  208. def api_reload_squid():
  209. success, message, details = reload_squid()
  210. status_code = 200 if success else 500
  211. response = {"success": success, "message": message}
  212. if details:
  213. response["details"] = details
  214. return jsonify(response), status_code
  215. def validate_required_fields(audit_type, data):
  216. required = REQUIRED_FIELDS.get(audit_type, [])
  217. missing = [field for field in required if not data.get(field)]
  218. if missing:
  219. raise BadRequest(f"Missing required fields: {', '.join(missing)}")