feat: projekte mit anderen benutzern teilen (backend)

Mitglieder mit Rolle "bearbeiten" oder "lesen"; nur der Besitzer
verwaltet das Projekt. Sichtbar sind eigene Clips und alle Clips in
eigenen oder geteilten Projekten, zentral in services/access.py. Beim
Entfernen oder Verlassen landen die eigenen Clips wieder bei "ohne
Projekt". Live-Ereignisse gehen an alle, die einen Clip sehen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 14:36:56 +01:00
1 parent cfa2a1d0ab
commit d3a52c25a7
18 files changed
+1043 -133

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
"""Who may see and change what.
A user sees their own clips plus every clip in a project they own or are a member of.
Clips outside projects are private. All visibility checks go through this module.
"""
import enum
from sqlalchemy import or_, select
from sqlalchemy.orm import Session
from app.models import Clip, MemberRole, Project, ProjectMember
class ProjectRole(enum.StrEnum):
OWNER = "owner"
EDIT = "edit"
READ = "read"
WRITE_ROLES = frozenset({ProjectRole.OWNER, ProjectRole.EDIT})
class ProjectNotFound(LookupError):
"""The project does not exist or is not visible to the user."""
class ReadOnly(PermissionError):
"""The user may see, but not change this."""
def accessible_project_ids(user_id: int):
"""Subquery of the ids of all projects the user owns or is a member of."""
return (
select(Project.id)
.where(Project.user_id == user_id)
.union(select(ProjectMember.project_id).where(ProjectMember.user_id == user_id))
)
def visible_clip(user_id: int):
"""SQL condition for clips the user may see."""
return or_(Clip.user_id == user_id, Clip.project_id.in_(accessible_project_ids(user_id)))
def project_role(db: Session, user_id: int, project_id: int) -> ProjectRole | None:
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
if owner_id is None:
return None
if owner_id == user_id:
return ProjectRole.OWNER
role = db.scalar(
select(ProjectMember.role).where(
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
)
)
return None if role is None else ProjectRole(MemberRole(role).value)
def require_project_write(db: Session, user_id: int, project_id: int) -> ProjectRole:
"""For putting clips into a project: owner or editor."""
role = project_role(db, user_id, project_id)
if role is None:
raise ProjectNotFound(project_id)
if role not in WRITE_ROLES:
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
return role
def can_write_clip(db: Session, user_id: int, clip: Clip) -> bool:
"""Own clips always; others' clips only in projects where the user may edit."""
if clip.user_id == user_id:
return True
if clip.project_id is None:
return False
return project_role(db, user_id, clip.project_id) in WRITE_ROLES
def require_clip_write(db: Session, user_id: int, clip: Clip) -> None:
if not can_write_clip(db, user_id, clip):
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
def project_audience(db: Session, project_id: int) -> set[int]:
"""Owner and members: everyone who sees the project."""
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
members = db.scalars(
select(ProjectMember.user_id).where(ProjectMember.project_id == project_id)
)
return ({owner_id} if owner_id is not None else set()) | set(members)
def clip_audience(db: Session, owner_id: int, project_id: int | None) -> set[int]:
"""Everyone who sees a clip: its owner, plus the project's audience."""
audience = {owner_id}
if project_id is not None:
audience |= project_audience(db, project_id)
return audience
+26 -20
View File
@@ -6,8 +6,8 @@ from sqlalchemy.orm import Session
from app.config import get_settings
from app.languages import LANGUAGES
from app.models import Clip, ClipKind, StoredFile, utcnow
from app.services.access import require_clip_write, require_project_write, visible_clip
from app.services.files import remove_from_disk
from app.services.projects import require_project
from app.services.users import UserError
# Changing only these fields does not count as an edit (no new updated_at)
@@ -50,9 +50,10 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
def _filters(user_id: int, project: int | str | None, query: str | None) -> list:
conditions = [Clip.user_id == user_id]
conditions = [visible_clip(user_id)]
if project == NO_PROJECT:
conditions.append(Clip.project_id.is_(None))
# Clips without project are always private
conditions += [Clip.user_id == user_id, Clip.project_id.is_(None)]
elif project is not None:
conditions.append(Clip.project_id == project)
needle = (query or "").strip().casefold()
@@ -76,7 +77,7 @@ def list_clips(
project: int | str | None = None,
query: str | None = None,
) -> tuple[list[Clip], int]:
"""Clips of the user, optionally only those of a project (or NO_PROJECT) matching a query."""
"""Visible clips, optionally only those of a project (or NO_PROJECT) matching a query."""
conditions = _filters(user_id, project, query)
items = db.scalars(
select(Clip)
@@ -90,7 +91,8 @@ def list_clips(
def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None:
return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
"""A clip the user may see (own or in a shared project), else None."""
return db.scalar(select(Clip).where(Clip.id == clip_id, visible_clip(user_id)))
def create_clip(
@@ -108,7 +110,7 @@ def create_clip(
raise UserError("Dateien werden über den Upload angelegt.")
title, language = _normalize(kind, title, content, language)
if project_id is not None:
require_project(db, user_id, project_id)
require_project_write(db, user_id, project_id)
clip = Clip(
user_id=user_id,
project_id=project_id,
@@ -130,7 +132,11 @@ def update_clip(
changes: dict[str, Any],
expected_version: int | None = None,
) -> Clip:
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict."""
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict.
The clip must be visible to the user (get_clip); write access is checked here.
"""
require_clip_write(db, user_id, clip)
# Early check so a stale client gets the conflict, not a follow-up validation error
if expected_version is not None and clip.version != expected_version:
raise ClipConflict(clip)
@@ -144,8 +150,8 @@ def update_clip(
language = changes.get("language", clip.language)
title, language = _normalize(kind, title, content, language)
project_id = changes.get("project_id", clip.project_id)
if "project_id" in changes and project_id is not None:
require_project(db, user_id, project_id)
if "project_id" in changes and project_id not in (None, clip.project_id):
require_project_write(db, user_id, project_id)
values: dict[str, Any] = {
"project_id": project_id,
@@ -160,7 +166,7 @@ def update_clip(
values["updated_at"] = utcnow()
# Conditional UPDATE keeps the version check atomic across concurrent requests
stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id)
stmt = update(Clip).where(Clip.id == clip.id)
if expected_version is not None:
stmt = stmt.where(Clip.version == expected_version)
result = db.execute(stmt.values(**values).execution_options(synchronize_session=False))
@@ -173,14 +179,14 @@ def update_clip(
return clip
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
storage_name = db.scalar(
select(StoredFile.storage_name).where(
StoredFile.clip_id == clip_id, StoredFile.user_id == user_id
)
)
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
def delete_clip(db: Session, user_id: int, clip: Clip) -> None:
"""Delete a visible clip; write access is checked here. Its file goes with it."""
require_clip_write(db, user_id, clip)
stored = db.execute(
select(StoredFile.user_id, StoredFile.storage_name).where(StoredFile.clip_id == clip.id)
).first()
db.execute(delete(Clip).where(Clip.id == clip.id))
db.commit()
if storage_name is not None:
remove_from_disk(user_id, storage_name)
return result.rowcount > 0
if stored is not None:
# Stored under the uploader, who may be another member of a shared project
remove_from_disk(stored.user_id, stored.storage_name)
+27 -12
View File
@@ -16,7 +16,12 @@ from sqlalchemy.orm import Session
from app.config import get_settings
from app.models import Clip, ClipKind, StoredFile, utcnow
from app.services.projects import require_project
from app.services.access import (
clip_audience,
require_clip_write,
require_project_write,
visible_clip,
)
from app.services.users import UserError
logger = logging.getLogger(__name__)
@@ -158,7 +163,7 @@ async def store_upload(
if title is not None and len(title) > 200:
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
if project_id is not None:
require_project(db, user_id, project_id)
require_project_write(db, user_id, project_id)
_check_limits(db, user_id, size)
settings = get_settings()
@@ -215,9 +220,11 @@ async def store_upload(
def get_file(db: Session, user_id: int, clip_id: int) -> StoredFile | None:
"""The file of a clip of this user, unless it has expired."""
"""The file of a clip the user may see, unless it has expired."""
stored = db.scalar(
select(StoredFile).where(StoredFile.clip_id == clip_id, StoredFile.user_id == user_id)
select(StoredFile)
.join(Clip, Clip.id == StoredFile.clip_id)
.where(StoredFile.clip_id == clip_id, visible_clip(user_id))
)
if stored is None or (stored.expires_at is not None and stored.expires_at <= utcnow()):
return None
@@ -228,10 +235,11 @@ def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip
"""Change how long a file is kept; counts as a change of the clip, not as an edit."""
if clip.file is None:
raise UserError("Dieser Clip ist keine Datei.")
require_clip_write(db, user_id, clip)
clip.file.expires_at = _expires_at(expires_days)
db.execute(
update(Clip)
.where(Clip.id == clip.id, Clip.user_id == user_id)
.where(Clip.id == clip.id)
.values(version=Clip.version + 1)
.execution_options(synchronize_session=False)
)
@@ -240,20 +248,27 @@ def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip
return clip
def delete_expired(db: Session) -> list[tuple[int, int]]:
"""Delete clips whose file has expired; returns (user_id, clip_id) for notifications."""
def delete_expired(db: Session) -> list[tuple[int, set[int]]]:
"""Delete clips whose file has expired; returns (clip_id, audience) for notifications."""
rows = db.execute(
select(StoredFile.user_id, StoredFile.clip_id, StoredFile.storage_name).where(
StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow()
select(
StoredFile.user_id.label("uploader_id"),
StoredFile.storage_name,
Clip.id,
Clip.user_id.label("owner_id"),
Clip.project_id,
)
.join(Clip, Clip.id == StoredFile.clip_id)
.where(StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow())
).all()
if not rows:
return []
db.execute(delete(Clip).where(Clip.id.in_([row.clip_id for row in rows])))
audiences = [(row.id, clip_audience(db, row.owner_id, row.project_id)) for row in rows]
db.execute(delete(Clip).where(Clip.id.in_([row.id for row in rows])))
db.commit()
for row in rows:
remove_from_disk(row.user_id, row.storage_name)
return [(row.user_id, row.clip_id) for row in rows]
remove_from_disk(row.uploader_id, row.storage_name)
return audiences
def remove_orphans(db: Session) -> int:
+170 -44
View File
@@ -1,18 +1,42 @@
import unicodedata
from dataclasses import dataclass
from sqlalchemy import delete, func, select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.models import PROJECT_COLORS, Clip, Project, utcnow
from app.services.users import UserError
from app.models import PROJECT_COLORS, Clip, MemberRole, Project, ProjectMember, User, utcnow
from app.services.access import (
ProjectNotFound,
ProjectRole,
accessible_project_ids,
project_role,
)
from app.services.users import UserError, normalize_username
NAME_MAX_LENGTH = 100
MAX_PROJECTS_PER_USER = 200
MAX_MEMBERS_PER_PROJECT = 50
__all__ = ["ProjectNotFound"]
class ProjectNotFound(LookupError):
"""The project does not exist or belongs to another user."""
@dataclass
class ProjectView:
"""A project as one particular user sees it."""
project: Project
role: ProjectRole
owner_name: str
clip_count: int
member_count: int
@dataclass
class Member:
user_id: int
username: str
role: ProjectRole
def _validate_name(name: str) -> tuple[str, str]:
@@ -36,41 +60,59 @@ def _duplicate() -> UserError:
return UserError("Ein Projekt mit diesem Namen gibt es schon.")
def list_projects(db: Session, user_id: int) -> list[tuple[Project, int]]:
"""Projects of the user, sorted by name, each with its number of clips."""
clip_count = (
select(func.count(Clip.id))
.where(Clip.project_id == Project.id, Clip.user_id == user_id)
def _clip_count():
return select(func.count(Clip.id)).where(Clip.project_id == Project.id).scalar_subquery()
def _member_count():
return (
select(func.count(ProjectMember.id))
.where(ProjectMember.project_id == Project.id)
# Only Project comes from the outer query; ProjectMember is counted here
.correlate(Project)
.scalar_subquery()
)
def list_projects(db: Session, user_id: int) -> list[ProjectView]:
"""Own and shared projects, sorted by name, with clip counts of all members."""
rows = db.execute(
select(Project, clip_count)
.where(Project.user_id == user_id)
select(Project, User.username, _clip_count(), _member_count(), ProjectMember.role)
.join(User, User.id == Project.user_id)
.outerjoin(
ProjectMember,
(ProjectMember.project_id == Project.id) & (ProjectMember.user_id == user_id),
)
.where(Project.id.in_(accessible_project_ids(user_id)))
.order_by(Project.name_key, Project.id)
)
return [(project, count) for project, count in rows]
def get_project(db: Session, user_id: int, project_id: int) -> Project | None:
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
def require_project(db: Session, user_id: int, project_id: int) -> Project:
project = get_project(db, user_id, project_id)
if project is None:
raise ProjectNotFound(project_id)
return project
def count_clips(db: Session, user_id: int, project_id: int) -> int:
return (
db.scalar(
select(func.count(Clip.id)).where(
Clip.user_id == user_id, Clip.project_id == project_id
)
return [
ProjectView(
project=project,
role=ProjectRole.OWNER if project.user_id == user_id else ProjectRole(role),
owner_name=owner_name,
clip_count=clips,
member_count=members,
)
or 0
)
for project, owner_name, clips, members, role in rows
]
def view_project(db: Session, user_id: int, project_id: int) -> ProjectView | None:
"""One project as the user sees it, or None if it is not visible to them."""
role = project_role(db, user_id, project_id)
if role is None:
return None
project, owner_name, clips, members = db.execute(
select(Project, User.username, _clip_count(), _member_count())
.join(User, User.id == Project.user_id)
.where(Project.id == project_id)
).one()
return ProjectView(project, role, owner_name, clips, members)
def get_owned_project(db: Session, user_id: int, project_id: int) -> Project | None:
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
def create_project(db: Session, user_id: int, *, name: str, color: str = "blue") -> Project:
@@ -106,18 +148,102 @@ def update_project(
return project
def _detach_clips(db: Session, project_id: int, owner_id: int | None = None) -> list[int]:
"""Move clips out of a project (all, or those of one user); returns their ids.
Versions are bumped so open editors holding the old project notice the change.
"""
conditions = [Clip.project_id == project_id]
if owner_id is not None:
conditions.append(Clip.user_id == owner_id)
ids = list(db.scalars(select(Clip.id).where(*conditions)))
if ids:
db.execute(
update(Clip)
.where(Clip.id.in_(ids))
.values(project_id=None, version=Clip.version + 1)
.execution_options(synchronize_session=False)
)
return ids
def delete_project(db: Session, user_id: int, project_id: int) -> bool:
"""Delete a project; its clips stay and move to "no project"."""
# Bump versions so open editors holding the old project notice the change
db.execute(
update(Clip)
.where(Clip.user_id == user_id, Clip.project_id == project_id)
.values(project_id=None, version=Clip.version + 1)
.execution_options(synchronize_session=False)
)
result = db.execute(delete(Project).where(Project.id == project_id, Project.user_id == user_id))
if result.rowcount == 0:
db.rollback()
"""Delete an own project; all clips in it stay and move to their owners' "no project"."""
if get_owned_project(db, user_id, project_id) is None:
return False
_detach_clips(db, project_id)
db.execute(delete(Project).where(Project.id == project_id))
db.commit()
return True
# --- Members --------------------------------------------------------------------
def list_members(db: Session, project: Project) -> list[Member]:
"""Owner first, then members by name."""
owner = db.get(User, project.user_id)
rows = db.execute(
select(User.id, User.username, ProjectMember.role)
.join(ProjectMember, ProjectMember.user_id == User.id)
.where(ProjectMember.project_id == project.id)
.order_by(User.username)
)
members = [Member(uid, name, ProjectRole(MemberRole(role).value)) for uid, name, role in rows]
return [Member(owner.id, owner.username, ProjectRole.OWNER), *members]
def _member_role(role: str) -> MemberRole:
try:
return MemberRole(role)
except ValueError:
raise UserError("Unbekannte Rolle.") from None
def add_member(db: Session, project: Project, username: str, role: str) -> User:
member_role = _member_role(role)
user = db.scalar(
select(User).where(User.username == normalize_username(username), User.is_active)
)
if user is None:
raise UserError("Diesen Benutzer gibt es nicht.")
if user.id == project.user_id:
raise UserError("Das Projekt gehört dir bereits.")
count = db.scalar(
select(func.count(ProjectMember.id)).where(ProjectMember.project_id == project.id)
)
if (count or 0) >= MAX_MEMBERS_PER_PROJECT:
raise UserError(f"Höchstens {MAX_MEMBERS_PER_PROJECT} Mitglieder pro Projekt.")
db.add(ProjectMember(project_id=project.id, user_id=user.id, role=member_role))
try:
db.commit()
except IntegrityError:
db.rollback()
raise UserError(f"{user.username} ist schon Mitglied.") from None
return user
def set_member_role(db: Session, project: Project, user_id: int, role: str) -> bool:
result = db.execute(
update(ProjectMember)
.where(ProjectMember.project_id == project.id, ProjectMember.user_id == user_id)
.values(role=_member_role(role))
)
db.commit()
return result.rowcount > 0
def remove_member(db: Session, project_id: int, user_id: int) -> list[int] | None:
"""Remove a member (or let them leave). Their clips in the project go back to their
own "no project". Returns the ids of those clips, or None if they were no member."""
result = db.execute(
delete(ProjectMember).where(
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
)
)
if result.rowcount == 0:
db.rollback()
return None
moved = _detach_clips(db, project_id, owner_id=user_id)
db.commit()
return moved