60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
"""routes/fichiers.py — API upload/download du module Fichiers (EXF-05 à EXF-08)."""
|
|
|
|
from flask import Blueprint, current_app, jsonify, request, send_file
|
|
|
|
from services import fichier_service
|
|
from services.auth_service import client_ip, current_user, is_admin, require_login
|
|
|
|
bp = Blueprint("fichiers", __name__, url_prefix="/api/fichiers")
|
|
|
|
|
|
def _db():
|
|
return current_app.config["DB"]
|
|
|
|
|
|
@bp.route("", methods=["GET"])
|
|
@require_login
|
|
def list_fichiers():
|
|
return jsonify(fichier_service.list_fichiers(_db()))
|
|
|
|
|
|
@bp.route("/upload", methods=["POST"])
|
|
@require_login
|
|
def upload():
|
|
user = current_user()
|
|
try:
|
|
fichier_id = fichier_service.handle_upload(
|
|
_db(), request.files.get("file"), user["sub"], client_ip()
|
|
)
|
|
except fichier_service.FileValidationError as exc:
|
|
return jsonify({"error": str(exc)}), 400
|
|
return jsonify({"id": fichier_id}), 201
|
|
|
|
|
|
@bp.route("/<int:fichier_id>/download", methods=["GET"])
|
|
@require_login
|
|
def download(fichier_id):
|
|
user = current_user()
|
|
try:
|
|
path, original_name = fichier_service.prepare_download(
|
|
_db(), fichier_id, user["sub"], is_admin(user), client_ip()
|
|
)
|
|
except FileNotFoundError:
|
|
return jsonify({"error": "not found"}), 404
|
|
except PermissionError:
|
|
return jsonify({"error": "forbidden"}), 403
|
|
return send_file(path, as_attachment=True, download_name=original_name)
|
|
|
|
|
|
@bp.route("/<int:fichier_id>", methods=["DELETE"])
|
|
@require_login
|
|
def delete(fichier_id):
|
|
user = current_user()
|
|
try:
|
|
fichier_service.delete_fichier(_db(), fichier_id, user["sub"], is_admin(user), client_ip())
|
|
except FileNotFoundError:
|
|
return jsonify({"error": "not found"}), 404
|
|
except PermissionError:
|
|
return jsonify({"error": "forbidden"}), 403
|
|
return jsonify({"status": "deleted"})
|