Files
leocrm/app/plugins/builtins/permissions/public_routes.py
T
Agent Zero 0eb6d7621e
Check Cross-Plugin Imports / check (push) Has been cancelled
fix(security): 16 mittlere Probleme behoben (P18-P33)
P18: require_permission zu forgejo_error_reporter und ai_ui_control routes hinzugefügt
P19: Cross-Tenant Permission-Cache-Invalidierung bei Rollenänderungen
P20: Session/Permission-Cache-Invalidierung bei Gruppen-Änderungen
P21: ENTITY_MODELS Registry um fehlende Plugin-Modelle erweitert
P22: Entity-Links prüfen verknüpfte Entity-Permissions
P23: authStore persist Middleware entfernt (kein localStorage mehr)
P24: 5xx Retry nur noch für GET-Requests
P25: KI-Kommentar in address.py (bekannte Inkonsistenz)
P26: DeletionLog in EntityHistory gemerged (action=delete)
P27: KI-Kommentar in entity_policy.py (ABAC nicht aktiv genutzt)
P28: db.commit() aus bulk_permission_service entfernt
P29: CSV-Export in export_service.py ausgelagert
P30: plugins.py Business-Logik in plugin_install_service.py ausgelagert
P31: KI-Kommentar in session.py (Dual-System dokumentiert)
P32: Migration 0115: crm_platform_admin Role droppen
P33: Cross-Plugin Imports über contracts.py behoben (10 Violations → 0)
2026-08-06 13:23:58 +02:00

119 lines
4.2 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.contracts import DmsContract
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