Files
leocrm/app/plugins/builtins/permissions/public_routes.py
T
Agent Zero cfb4c5ae8b
Check Cross-Plugin Imports / check (push) Has been cancelled
Phase 5.1-5.4: PWA, Public Plugin Endpoints, Contacts Embedding, Search Coverage
5.1 Public Plugin Endpoints:
- PluginRouteDef.is_public field in manifest.py
- main.py: public routes mounted without auth dependency
- permissions/public_routes.py: token-based share link access (info, verify, download)
- permissions/plugin.py: public share route registered with is_public=True

5.2 PWA:
- vite.config.ts: VitePWA plugin configured (autoUpdate, workbox, runtime caching)
- frontend/public/manifest.json: PWA manifest with icons
- index.html: theme-color, manifest link, apple-touch-icon, apple-mobile-web-app meta
- Build generates sw.js + workbox (90 precache entries)

5.3 Contacts Embedding:
- contact.py: embedding column (Vector(768)) added to Contact model
- Migration 0002_embeddings.sql already exists (adds embedding + HNSW index)
- ContactSearchProvider already queries embedding column

5.4 Search Coverage:
- 5 new search providers: task, contactperson, tag, conversation, user
- All providers implement FTS search with tenant_id + deleted_at filters
- TagSearchProvider also supports vector search (384-dim embedding)
- provider_registry.py: all 5 new providers auto-registered
- Total: 10 search providers (was 5)
2026-08-04 14:49:35 +02:00

118 lines
4.1 KiB
Python

"""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.permissions.models import ShareLink
from app.plugins.builtins.dms.models import File as 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