| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258 |
- from flask import Blueprint, current_app, jsonify, request
- from loguru import logger
- from werkzeug.exceptions import BadRequest
- from database.database import get_session
- from services.analytics.auditoria_service import (
- find_by_ip,
- find_by_keyword,
- find_by_response_code,
- find_denied_access,
- find_social_media_activity,
- get_all_usernames,
- get_daily_activity,
- get_top_ips_by_data,
- get_top_urls_by_data,
- get_top_users_by_data,
- get_top_users_by_requests,
- get_total_data_consumed,
- get_user_activity_summary,
- )
- from services.auth.auth_service import admin_required
- from services.notifications.notifications import (
- delete_all_notifications,
- delete_notification,
- get_all_notifications,
- mark_notifications_read,
- )
- from services.system.metrics_service import MetricsService
- from services.system.system_service import reload_squid, restart_squid
- api_bp = Blueprint("api", __name__)
- REQUIRED_FIELDS = {
- "user_summary": ["username"],
- "daily_activity": ["start_date", "end_date"],
- "keyword_search": ["keyword"],
- "social_media_activity": ["social_media_sites"],
- "ip_activity": ["ip_address"],
- "response_code_search": ["response_code"],
- "total_data_consumed": ["start_date", "end_date"],
- }
- AUDIT_HANDLERS = {
- "user_summary": lambda db, d: get_user_activity_summary(
- db, d["username"], d.get("start_date"), d.get("end_date")
- ),
- "top_users_data": lambda db, d: get_top_users_by_data(
- db, d.get("start_date"), d.get("end_date")
- ),
- "top_urls_data": lambda db, d: get_top_urls_by_data(
- db, d.get("start_date"), d.get("end_date")
- ),
- "top_users_requests": lambda db, d: get_top_users_by_requests(
- db, d.get("start_date"), d.get("end_date")
- ),
- "top_ips_data": lambda db, d: get_top_ips_by_data(
- db, d.get("start_date"), d.get("end_date")
- ),
- "daily_activity": lambda db, d: get_daily_activity(
- db, d["start_date"], d.get("username")
- ),
- "denied_access": lambda db, d: find_denied_access(
- db, d.get("start_date"), d.get("end_date"), d.get("username")
- ),
- "keyword_search": lambda db, d: find_by_keyword(
- db, d.get("start_date"), d.get("end_date"), d["keyword"], d.get("username")
- ),
- "social_media_activity": lambda db, d: find_social_media_activity(
- db,
- d.get("start_date"),
- d.get("end_date"),
- d["social_media_sites"],
- d.get("username"),
- ),
- "ip_activity": lambda db, d: find_by_ip(
- db, d.get("start_date"), d.get("end_date"), d["ip_address"]
- ),
- "response_code_search": lambda db, d: find_by_response_code(
- db,
- d.get("start_date"),
- d.get("end_date"),
- int(d["response_code"]),
- d.get("username"),
- ),
- "total_data_consumed": lambda db, d: get_total_data_consumed(
- db, d["start_date"], d["end_date"]
- ),
- }
- @api_bp.route("/metrics/today")
- def get_today_metrics():
- try:
- results = MetricsService.get_metrics_today()
- return jsonify(results)
- except Exception as e:
- logger.error(f"Error retrieving today's metrics: {e}")
- return jsonify([])
- @api_bp.route("/metrics/24hours")
- def get_24hours_metrics():
- try:
- results = MetricsService.get_metrics_last_24_hours()
- return jsonify(results)
- except Exception as e:
- logger.error(f"Error retrieving 24 hours metrics: {e}")
- return jsonify([])
- @api_bp.route("/metrics/latest")
- def get_latest_metric():
- try:
- result = MetricsService.get_latest_metric()
- return jsonify(result) if result else jsonify({})
- except Exception as e:
- logger.error(f"Error retrieving latest metric: {e}")
- return jsonify({})
- @api_bp.route("/all-users", methods=["GET"])
- def api_get_all_users():
- db = get_session()
- try:
- users = get_all_usernames(db)
- return jsonify(users)
- except Exception as e:
- logger.exception("Error retrieving all users")
- try:
- show_details = bool(current_app.debug)
- except RuntimeError:
- show_details = False
- resp = {"error": "Internal server error"}
- if show_details:
- resp["details"] = str(e)
- return jsonify(resp), 500
- finally:
- db.close()
- @api_bp.route("/run-audit", methods=["POST"])
- def api_run_audit():
- data = request.get_json()
- if not data:
- return jsonify({"error": "Invalid JSON body"}), 400
- audit_type = data.get("audit_type")
- if audit_type not in AUDIT_HANDLERS:
- return jsonify({"error": "Invalid audit type"}), 400
- db = get_session()
- try:
- validate_required_fields(audit_type, data)
- result = AUDIT_HANDLERS[audit_type](db, data)
- return jsonify(result)
- except BadRequest as e:
- logger.warning(f"Bad request in audit API: {e}")
- return jsonify({"error": "Bad request"}), 400
- except ValueError:
- return jsonify({"error": "Invalid numeric value"}), 400
- except Exception:
- logger.exception("Audit API error")
- return jsonify({"error": "Internal server error"}), 500
- finally:
- db.close()
- # API para notificaciones del sistema
- @api_bp.route("/notifications", methods=["GET"])
- def api_get_notifications():
- try:
- page = request.args.get("page", 1, type=int)
- per_page = request.args.get("per_page", 20, type=int)
- return jsonify(get_all_notifications(page=page, per_page=per_page))
- except Exception as e:
- logger.error(f"Error getting notifications: {e}")
- return jsonify({"unread_count": 0, "notifications": [], "pagination": {}})
- @api_bp.route("/notifications/mark-read", methods=["POST"])
- def api_mark_notifications_read():
- try:
- data = request.get_json()
- notification_ids = data.get("notification_ids", data.get("ids", []))
- mark_notifications_read(notification_ids)
- return jsonify(
- {"success": True, "unread_count": get_all_notifications()["unread_count"]}
- )
- except Exception as e:
- logger.exception("Error marking notifications as read")
- try:
- show_details = bool(current_app.debug)
- except RuntimeError:
- show_details = False
- resp = {"success": False, "error": "Internal server error"}
- if show_details:
- resp["details"] = str(e)
- return jsonify(resp), 500
- @api_bp.route("/notifications/<int:notification_id>", methods=["DELETE"])
- def api_delete_notification(notification_id):
- try:
- delete_notification(notification_id)
- return jsonify(
- {"success": True, "unread_count": get_all_notifications()["unread_count"]}
- )
- except Exception as e:
- logger.error(f"Error deleting notification: {e}")
- return jsonify({"success": False, "error": "Internal server error"}), 500
- @api_bp.route("/notifications/delete-all", methods=["DELETE"])
- def api_delete_all_notifications():
- try:
- delete_all_notifications()
- return jsonify({"success": True, "unread_count": 0})
- except Exception as e:
- logger.error(f"Error deleting all notifications: {e}")
- return jsonify({"success": False, "error": "Internal server error"}), 500
- @api_bp.route("/restart-squid", methods=["POST"])
- @admin_required
- def api_restart_squid():
- success, message, details = restart_squid()
- status_code = 200 if success else 500
- response = {"success": success, "message": message}
- if details:
- response["details"] = details
- return jsonify(response), status_code
- @api_bp.route("/reload-squid", methods=["POST"])
- @admin_required
- def api_reload_squid():
- success, message, details = reload_squid()
- status_code = 200 if success else 500
- response = {"success": success, "message": message}
- if details:
- response["details"] = details
- return jsonify(response), status_code
- def validate_required_fields(audit_type, data):
- required = REQUIRED_FIELDS.get(audit_type, [])
- missing = [field for field in required if not data.get(field)]
- if missing:
- raise BadRequest(f"Missing required fields: {', '.join(missing)}")
|