Files
leocrm/app/plugins/builtins/permissions/public_routes.py
T

120 lines
4.2 KiB
Python
Raw Normal View History

"""Public share routes — token-based access to shared files, no auth required."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.core.storage import get_storage_backend
from app.plugins.builtins.dms.contracts import DmsContract
from app.plugins.builtins.permissions.models import ShareLink
DmsFile = DmsContract.DmsFile
router = APIRouter(prefix="/api/v1/public/share", tags=["public-share"])
@router.get("/{token}", status_code=status.HTTP_200_OK)
async def get_share_info(token: str, db: AsyncSession = Depends(get_db)):
"""Get share link info by token (public, no auth required).
Returns file metadata without requiring authentication.
If the share link has a password, the client must provide it via POST.
"""
share = await _get_share_link(db, token)
file = await _get_file(db, share.file_id, share.tenant_id)
return {
"file_name": file.name,
"file_size": file.size_bytes,
"mime_type": file.mime_type,
"access_level": share.access_level,
"requires_password": share.password_hash is not None,
"expires_at": share.expires_at.isoformat() if share.expires_at else None,
}
@router.post("/{token}/verify", status_code=status.HTTP_200_OK)
async def verify_share_password(
token: str,
password: str,
db: AsyncSession = Depends(get_db),
):
"""Verify password for a password-protected share link."""
share = await _get_share_link(db, token)
if share.password_hash is None:
return {"valid": True}
from app.core.auth import verify_password
if not verify_password(password, share.password_hash):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={"detail": "Invalid password", "code": "invalid_password"},
)
return {"valid": True}
@router.get("/{token}/download", status_code=status.HTTP_200_OK)
async def download_shared_file(token: str, db: AsyncSession = Depends(get_db)):
"""Download file via share link token (public, no auth required)."""
share = await _get_share_link(db, token)
file = await _get_file(db, share.file_id, share.tenant_id)
storage = get_storage_backend()
if not await storage.exists(file.storage_path):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "File not found on disk", "code": "file_missing"},
)
stream = await storage.get_stream(file.storage_path)
return StreamingResponse(
stream,
media_type=file.mime_type,
headers={
"Content-Disposition": f'attachment; filename="{file.name}"',
"Content-Length": str(file.size_bytes),
},
)
async def _get_share_link(db: AsyncSession, token: str) -> ShareLink:
"""Get share link by token and validate expiry."""
result = await db.execute(
select(ShareLink).where(ShareLink.token == token)
)
share = result.scalar_one_or_none()
if share is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "Share link not found", "code": "share_not_found"},
)
if share.expires_at is not None and share.expires_at < datetime.now(UTC):
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail={"detail": "Share link expired", "code": "share_expired"},
)
return share
async def _get_file(db: AsyncSession, file_id: uuid.UUID, tenant_id: uuid.UUID) -> DmsFile:
"""Get file by ID within tenant scope."""
result = await db.execute(
select(DmsFile)
.where(DmsFile.id == file_id)
.where(DmsFile.tenant_id == tenant_id)
.where(DmsFile.deleted_at.is_(None))
)
file = result.scalar_one_or_none()
if file is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "File not found", "code": "file_not_found"},
)
return file