|
| 1 | +from flask import Blueprint, send_file, request, jsonify |
| 2 | +from flask_jwt_extended import jwt_required, get_jwt_identity |
| 3 | +from utils.db import db |
| 4 | +from models.scan_history import ScanHistory |
| 5 | +from models.user import User |
| 6 | +from services.report_service import generate_csv_for_scan, send_csv_report_email |
| 7 | + |
| 8 | +report_bp = Blueprint("reports", __name__) |
| 9 | + |
| 10 | +@report_bp.route("/reports/<int:scan_id>/csv", methods=["GET"]) |
| 11 | +@jwt_required() |
| 12 | +def download_report_csv(scan_id: int): |
| 13 | + user_id = int(get_jwt_identity()) |
| 14 | + scan: ScanHistory = db.session.get(ScanHistory, scan_id) |
| 15 | + if not scan: |
| 16 | + return jsonify({"error": "scan not found"}), 404 |
| 17 | + |
| 18 | + user = db.session.get(User, user_id) |
| 19 | + if (scan.user_id != user_id) and (user.role != "admin"): |
| 20 | + return jsonify({"error": "forbidden"}), 403 |
| 21 | + |
| 22 | + try: |
| 23 | + csv_path, csv_filename = generate_csv_for_scan(scan_id) |
| 24 | + |
| 25 | + if request.args.get("email", "false").lower() == "true": |
| 26 | + subject = f"SafeOps — Rapport CSV ({scan.scan_type})" |
| 27 | + executed_at = ((scan.scan_result or {}).get("meta", {}) or {}).get("executed_at", scan.created_at.isoformat() if getattr(scan, "created_at", None) else "") |
| 28 | + body = f"Bonjour {user.name},\n\nVeuillez trouver ci-joint le rapport CSV de votre scan.\nExécuté le : {executed_at}\n" |
| 29 | + send_csv_report_email(user.email, subject, body, csv_path, csv_filename) |
| 30 | + |
| 31 | + return send_file(csv_path, mimetype="text/csv", as_attachment=True, download_name=csv_filename) |
| 32 | + except Exception as e: |
| 33 | + return jsonify({"error": str(e)}), 500 |
0 commit comments