fix(): Ajustado endpoint de visualização de arquivo

This commit is contained in:
Kenio 2025-11-12 17:19:43 -03:00
parent 76bbc71fc6
commit c8a0cc7e48
2 changed files with 17 additions and 32 deletions

View file

@ -54,19 +54,6 @@ def generate_storage_hash() -> str:
# Função que gera o token temporário para acesso ao documento
# def generate_temporary_token(
# expires_minutes: int,
# secret_key: str,
# algorithm: str,
# ) -> str:
# """Gera um token JWT válido por poucos minutos."""
# expire = datetime.utcnow() + timedelta(minutes=expires_minutes)
# payload = {
# "exp": expire,
# }
# return jwt.encode(payload, secret_key, algorithm=algorithm)
def generate_temporary_token(
file_path: str,
expires_minutes: int,

View file

@ -16,47 +16,45 @@ ALGORITHM = "HS256"
STORAGE_DIR = Path("storage")
@router.get("/{hash}/{file_path:path}")
def visualizar_arquivo(hash: str, file_path: str, token: str = Query(...)):
@router.get("/{hash}/{file_name}")
def visualizar_arquivo(hash: str, file_name: str, token: str = Query(...)):
"""
Valida o token JWT e retorna o arquivo PDF, se autorizado.
URL esperada:
/view/<hash>/<caminho_relativo>?token=<jwt>
/view/<hash>/<file_name>?token=<jwt>
Exemplo real:
/view/d7e8f9g0h1i2/100/57/documento.pdf?token=xxxxx
/view/d7e8f9g0h1i2/documento.pdf?token=xxxxx
"""
try:
# Decodifica o token usando a chave e algoritmo definidos
# Decodifica o token
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
# Extrai os campos esperados do token
faixa_superior = payload.get("faixa_superior")
ato_id = payload.get("ato_id")
file_name = payload.get("file_name")
file_name_token = payload.get("file_name")
# Se algum campo essencial estiver faltando → token inválido
if not all([faixa_superior, ato_id, file_name]):
# Validação mínima do payload
if not all([faixa_superior, ato_id, file_name_token]):
raise HTTPException(status_code=400, detail="Token malformado.")
# Reconstrói o caminho esperado a partir do token
expected_path = f"{faixa_superior}/{ato_id}/{file_name}"
# Se o caminho do arquivo solicitado não bate com o token → bloqueia
if expected_path != file_path:
# Verifica se o nome do arquivo bate
if file_name_token != file_name:
raise HTTPException(
status_code=403, detail="Token não corresponde ao arquivo."
status_code=403, detail="Token não corresponde ao arquivo solicitado."
)
# Monta o caminho real do arquivo no storage
# (estrutura física oculta do cliente)
full_path = STORAGE_DIR / faixa_superior / ato_id / file_name_token
except JWTError:
raise HTTPException(status_code=401, detail="Token expirado ou inválido.")
# Monta o caminho físico no disco
full_path = STORAGE_DIR / file_path
# Garante que o arquivo exista fisicamente
if not full_path.exists():
raise HTTPException(status_code=404, detail="Arquivo não encontrado.")
# Retorna o arquivo inline (abre no navegador)
# Retorna o PDF inline no navegador
return FileResponse(
full_path,
media_type="application/pdf",