45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
from fastapi import APIRouter, Query, HTTPException
|
|
from fastapi.responses import FileResponse
|
|
from jose import jwt, JWTError
|
|
from database.mysql import SessionLocal, get_database_settings
|
|
from pathlib import Path
|
|
|
|
router = APIRouter()
|
|
|
|
# === Configuração do token temporário ===
|
|
DB_SETTINGS = get_database_settings()
|
|
SECRET_KEY = getattr(DB_SETTINGS, "aeskey", None)
|
|
ALGORITHM = "HS256"
|
|
|
|
# Pasta base onde os arquivos são armazenados
|
|
STORAGE_DIR = Path("storage")
|
|
|
|
|
|
@router.get("/{file_id}/{file_path:path}")
|
|
def visualizar_arquivo(file_id: str, file_path: str, token: str = Query(...)):
|
|
"""
|
|
Valida o token e retorna o arquivo do storage, se autorizado.
|
|
Exemplo de URL:
|
|
/view/d7e8f9g0h1i2/100/57/documento.pdf?token=xxxx
|
|
"""
|
|
|
|
# --- 1. Valida token JWT ---
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
if payload["sub"] != file_id or payload["filename"] != file_path:
|
|
raise HTTPException(status_code=403, detail="Token inválido.")
|
|
except JWTError:
|
|
raise HTTPException(status_code=401, detail="Token expirado ou inválido.")
|
|
|
|
# --- 2. Monta caminho real no disco ---
|
|
full_path = STORAGE_DIR / file_path
|
|
|
|
# --- 3. Retorna arquivo, se existir ---
|
|
if not full_path.exists():
|
|
raise HTTPException(status_code=404, detail="Arquivo não encontrado.")
|
|
|
|
return FileResponse(
|
|
full_path,
|
|
media_type="application/pdf",
|
|
headers={"Content-Disposition": "inline"}, # abre no navegador
|
|
)
|