Files
surveybox/surveybox/forms/comments.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

191 lines
5.8 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Kommentare zu Formularen, auf Wunsch moderiert.
- Moderiert: Ein neuer oder geänderter Kommentar ist erst sichtbar, wenn ein
Verwalter ihn freischaltet. Der Autor sieht ihn vorher mit Hinweis.
- Öffentlich: sofort sichtbar.
- Anonym veröffentlicht: Andere sehen keinen Namen; Verwalter schon.
Gäste (ohne Konto) erkennt Surveybox an einem Zufallswert im Cookie; in der
Datenbank steht nur dessen Schlüssel-Hash.
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from datetime import UTC, datetime
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from surveybox.models import Comment, CommentStatus, Form, UserAccount
from surveybox.security.tokens import derive_key, keyed_hash
MAX_BODY = 2000
MAX_NAME = 80
LIMIT_PER_HOUR = 10
class CommentError(ValueError):
def __init__(self, code: str) -> None:
super().__init__(code)
self.code = code
@dataclass(frozen=True)
class Viewer:
user_id: int | None
guest_hash: bytes | None
manager: bool
@dataclass
class ShownComment:
comment: Comment
author: str # leer bei anonym für andere
own: bool
pending: bool
def guest_cookie_name(form: Form) -> str:
return f"sb_comment_{form.id}"
def guest_hash(secret_key: str, form: Form, cookie_value: str | None) -> bytes | None:
if not cookie_value or len(cookie_value) > 64:
return None
return keyed_hash(derive_key(secret_key, "comment-guest"), f"{form.id}:{cookie_value}")
def _clean_body(body: str) -> str:
text = body.replace("\r\n", "\n").strip()
if not text:
raise CommentError("comment_empty")
if len(text) > MAX_BODY:
raise CommentError("comment_too_long")
return text
def _is_own(comment: Comment, viewer: Viewer) -> bool:
if viewer.user_id is not None and comment.user_id == viewer.user_id:
return True
return viewer.guest_hash is not None and comment.author_token == viewer.guest_hash
def recent_count(db: Session, form: Form, viewer: Viewer) -> int:
since = datetime.now(UTC).timestamp() - 3600
stmt = select(func.count()).select_from(Comment).where(
Comment.form_id == form.id,
Comment.created_at >= datetime.fromtimestamp(since, UTC),
)
if viewer.user_id is not None:
stmt = stmt.where(Comment.user_id == viewer.user_id)
elif viewer.guest_hash is not None:
stmt = stmt.where(Comment.author_token == viewer.guest_hash)
else:
return 0
return int(db.scalar(stmt) or 0)
def create(
db: Session, form: Form, viewer: Viewer, body: str, guest_name: str = ""
) -> Comment:
if form.comments_mode == "off":
raise CommentError("comments_off")
text = _clean_body(body)
name = " ".join(guest_name.split())[:MAX_NAME]
if viewer.user_id is None and (not name or viewer.guest_hash is None):
raise CommentError("comment_name_missing")
if recent_count(db, form, viewer) >= LIMIT_PER_HOUR:
raise CommentError("comment_limit")
comment = Comment(
form_id=form.id,
user_id=viewer.user_id,
guest_name=name if viewer.user_id is None else None,
author_token=viewer.guest_hash if viewer.user_id is None else None,
body=text,
status=CommentStatus.PENDING
if form.comments_mode == "moderated" and not viewer.manager
else CommentStatus.PUBLISHED,
)
db.add(comment)
db.flush()
return comment
def find(db: Session, form: Form, public_id: str) -> Comment | None:
try:
pid = uuid.UUID(public_id)
except ValueError:
return None
return db.scalar(select(Comment).where(Comment.public_id == pid, Comment.form_id == form.id))
def edit(form: Form, comment: Comment, viewer: Viewer, body: str) -> None:
if not _is_own(comment, viewer):
raise CommentError("comment_not_own")
comment.body = _clean_body(body)
comment.updated_at = datetime.now(UTC)
if form.comments_mode == "moderated" and not viewer.manager:
comment.status = CommentStatus.PENDING
def delete(db: Session, comment: Comment, viewer: Viewer) -> None:
if not (viewer.manager or _is_own(comment, viewer)):
raise CommentError("comment_not_own")
db.delete(comment)
def publish(comment: Comment) -> None:
comment.status = CommentStatus.PUBLISHED
def _author(comment: Comment, names: dict[int, str]) -> str:
if comment.author_deleted:
from surveybox.i18n import gettext
return gettext("Deleted user")
if comment.user_id is not None:
return names.get(comment.user_id, "")
return comment.guest_name or ""
def visible(db: Session, form: Form, viewer: Viewer) -> list[ShownComment]:
"""Was der Betrachter sieht: freigeschaltete und eigene; Verwalter alles."""
rows = list(
db.scalars(
select(Comment).where(Comment.form_id == form.id).order_by(Comment.created_at)
)
)
user_ids = {c.user_id for c in rows if c.user_id is not None}
names = (
dict(db.execute(
select(UserAccount.id, UserAccount.display_name).where(UserAccount.id.in_(user_ids))
).all())
if user_ids
else {}
)
shown: list[ShownComment] = []
for comment in rows:
own = _is_own(comment, viewer)
pending = comment.status == CommentStatus.PENDING
if pending and not (own or viewer.manager):
continue
author = _author(comment, names)
if form.comments_anonymous and not viewer.manager and not own:
author = ""
shown.append(ShownComment(comment, author, own, pending))
return shown
def pending_count(db: Session, form: Form) -> int:
return int(
db.scalar(
select(func.count()).select_from(Comment).where(
Comment.form_id == form.id, Comment.status == CommentStatus.PENDING
)
)
or 0
)