feat(comments): v2 — HTMX, Turnstile, reactions, design refresh
- Extract comment templates into reusable partials (_comment.html, _comment_form.html, _comment_list.html, _reply_form.html, etc.) - Add HTMX progressive enhancement: inline form submission with partial responses, delta polling for live updates, form reset on success, success/moderation toast feedback - Integrate Cloudflare Turnstile for invisible bot protection: server-side token validation with hostname check, fail-closed on errors/timeouts, feature-flagged via TURNSTILE_SECRET_KEY env var - Auto-approve comments that pass Turnstile; keep manual approval as fallback when Turnstile is disabled (model default stays False) - Add CommentReaction model with UniqueConstraint for session-based anonymous reactions (heart/thumbs-up), toggle support, separate rate-limit bucket (20/min) - Add comment poll endpoint (GET /comments/poll/<id>/?after_id=N) for HTMX delta polling without duplicates - Update CSP middleware to allow challenges.cloudflare.com in script-src, connect-src, and frame-src - Self-host htmx.min.js (v2.0.4) to minimize CSP surface area - Add django-htmx middleware and requests to dependencies - Add Unapprove bulk action to Wagtail admin for moderation - Extend PII purge command to anonymize reaction session_key - Design refresh: neon glow avatars, solid hover shadows, gradient section header, cyan reply borders, grid-pattern empty state, neon-pink focus glow on form inputs - Add turnstile_site_key to template context via context processor - 18 new tests covering HTMX contracts, Turnstile success/failure/ timeout/hostname-mismatch, polling deltas, reaction toggle/dedup/ rate-limit, CSP headers, and PII purge extension Closes #43 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -5,7 +5,7 @@ from datetime import timedelta
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.comments.models import Comment
|
||||
from apps.comments.models import Comment, CommentReaction
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
@@ -29,3 +29,10 @@ class Command(BaseCommand):
|
||||
.update(author_email="", ip_address=None)
|
||||
)
|
||||
self.stdout.write(self.style.SUCCESS(f"Purged personal data for {purged} comment(s)."))
|
||||
|
||||
reactions_purged = (
|
||||
CommentReaction.objects.filter(created_at__lt=cutoff)
|
||||
.exclude(session_key="")
|
||||
.update(session_key="")
|
||||
)
|
||||
self.stdout.write(self.style.SUCCESS(f"Purged session keys for {reactions_purged} reaction(s)."))
|
||||
|
||||
27
apps/comments/migrations/0002_commentreaction.py
Normal file
27
apps/comments/migrations/0002_commentreaction.py
Normal file
@@ -0,0 +1,27 @@
|
||||
# Generated by Django 5.2.11 on 2026-03-03 22:49
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('comments', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='CommentReaction',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('reaction_type', models.CharField(choices=[('heart', '❤️'), ('plus_one', '👍')], max_length=20)),
|
||||
('session_key', models.CharField(max_length=64)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('comment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reactions', to='comments.comment')),
|
||||
],
|
||||
options={
|
||||
'constraints': [models.UniqueConstraint(fields=('comment', 'reaction_type', 'session_key'), name='unique_comment_reaction_per_session')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -23,3 +23,21 @@ class Comment(models.Model):
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Comment by {self.author_name}"
|
||||
|
||||
|
||||
class CommentReaction(models.Model):
|
||||
comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="reactions")
|
||||
reaction_type = models.CharField(max_length=20, choices=[("heart", "❤️"), ("plus_one", "👍")])
|
||||
session_key = models.CharField(max_length=64)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["comment", "reaction_type", "session_key"],
|
||||
name="unique_comment_reaction_per_session",
|
||||
)
|
||||
]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.reaction_type} on comment {self.comment_id}"
|
||||
|
||||
271
apps/comments/tests/test_v2.py
Normal file
271
apps/comments/tests/test_v2.py
Normal file
@@ -0,0 +1,271 @@
|
||||
"""Tests for Comments v2: HTMX, Turnstile, reactions, polling, CSP."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from django.core.cache import cache
|
||||
from django.core.management import call_command
|
||||
from django.test import override_settings
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.blog.models import ArticleIndexPage, ArticlePage
|
||||
from apps.blog.tests.factories import AuthorFactory
|
||||
from apps.comments.models import Comment, CommentReaction
|
||||
|
||||
|
||||
# ── Fixtures ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _article(home_page):
|
||||
"""Create a published article with comments enabled."""
|
||||
index = ArticleIndexPage(title="Articles", slug="articles")
|
||||
home_page.add_child(instance=index)
|
||||
author = AuthorFactory()
|
||||
article = ArticlePage(
|
||||
title="Test Article",
|
||||
slug="test-article",
|
||||
author=author,
|
||||
summary="summary",
|
||||
body=[("rich_text", "<p>body</p>")],
|
||||
)
|
||||
index.add_child(instance=article)
|
||||
article.save_revision().publish()
|
||||
return article
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def approved_comment(_article):
|
||||
return Comment.objects.create(
|
||||
article=_article,
|
||||
author_name="Alice",
|
||||
author_email="alice@example.com",
|
||||
body="Great article!",
|
||||
is_approved=True,
|
||||
)
|
||||
|
||||
|
||||
def _post_comment(client, article, extra=None, htmx=False):
|
||||
cache.clear()
|
||||
payload = {
|
||||
"article_id": article.id,
|
||||
"author_name": "Test",
|
||||
"author_email": "test@example.com",
|
||||
"body": "Hello world",
|
||||
"honeypot": "",
|
||||
}
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
headers = {}
|
||||
if htmx:
|
||||
headers["HTTP_HX_REQUEST"] = "true"
|
||||
return client.post("/comments/post/", payload, **headers)
|
||||
|
||||
|
||||
# ── HTMX Response Contracts ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_htmx_post_returns_partial_on_success(client, _article):
|
||||
"""HTMX POST with Turnstile disabled returns moderation notice partial."""
|
||||
resp = _post_comment(client, _article, htmx=True)
|
||||
assert resp.status_code == 200
|
||||
assert b"awaiting moderation" in resp.content
|
||||
assert "HX-Request" in resp["Vary"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(TURNSTILE_SECRET_KEY="test-secret")
|
||||
def test_htmx_post_returns_comment_partial_when_turnstile_passes(client, _article):
|
||||
"""HTMX POST with successful Turnstile returns comment partial for append."""
|
||||
with patch("apps.comments.views._verify_turnstile", return_value=True):
|
||||
resp = _post_comment(client, _article, extra={"cf-turnstile-response": "tok"}, htmx=True)
|
||||
assert resp.status_code == 200
|
||||
assert b"Hello world" in resp.content
|
||||
assert b"comment-" in resp.content
|
||||
comment = Comment.objects.get()
|
||||
assert comment.is_approved is True
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_htmx_post_returns_form_with_errors_on_invalid(client, _article):
|
||||
"""HTMX POST with invalid data returns form partial with HTTP 422."""
|
||||
cache.clear()
|
||||
resp = client.post(
|
||||
"/comments/post/",
|
||||
{"article_id": _article.id, "author_name": "T", "author_email": "t@t.com", "body": " ", "honeypot": ""},
|
||||
HTTP_HX_REQUEST="true",
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
assert "HX-Request" in resp["Vary"]
|
||||
assert Comment.objects.count() == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_non_htmx_post_still_redirects(client, _article):
|
||||
"""Non-HTMX POST continues to redirect (progressive enhancement)."""
|
||||
resp = _post_comment(client, _article)
|
||||
assert resp.status_code == 302
|
||||
assert resp["Location"].endswith("?commented=1")
|
||||
|
||||
|
||||
# ── Turnstile Integration ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(TURNSTILE_SECRET_KEY="test-secret")
|
||||
def test_turnstile_failure_keeps_comment_unapproved(client, _article):
|
||||
"""When Turnstile verification fails, comment stays unapproved."""
|
||||
with patch("apps.comments.views._verify_turnstile", return_value=False):
|
||||
_post_comment(client, _article, extra={"cf-turnstile-response": "bad-tok"})
|
||||
comment = Comment.objects.get()
|
||||
assert comment.is_approved is False
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_turnstile_disabled_keeps_comment_unapproved(client, _article):
|
||||
"""When TURNSTILE_SECRET_KEY is empty, comment stays unapproved."""
|
||||
_post_comment(client, _article)
|
||||
comment = Comment.objects.get()
|
||||
assert comment.is_approved is False
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(TURNSTILE_SECRET_KEY="test-secret", TURNSTILE_EXPECTED_HOSTNAME="nohypeai.com")
|
||||
def test_turnstile_hostname_mismatch_rejects(client, _article):
|
||||
"""Turnstile hostname mismatch keeps comment unapproved."""
|
||||
mock_resp = type("R", (), {"json": lambda self: {"success": True, "hostname": "evil.com"}})()
|
||||
with patch("apps.comments.views.http_requests.post", return_value=mock_resp):
|
||||
_post_comment(client, _article, extra={"cf-turnstile-response": "tok"})
|
||||
comment = Comment.objects.get()
|
||||
assert comment.is_approved is False
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(TURNSTILE_SECRET_KEY="test-secret")
|
||||
def test_turnstile_timeout_fails_closed(client, _article):
|
||||
"""Network error during Turnstile verification fails closed."""
|
||||
with patch("apps.comments.views.http_requests.post", side_effect=Exception("timeout")):
|
||||
_post_comment(client, _article, extra={"cf-turnstile-response": "tok"})
|
||||
comment = Comment.objects.get()
|
||||
assert comment.is_approved is False
|
||||
|
||||
|
||||
# ── Polling ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_comment_poll_returns_new_comments(_article, client, approved_comment):
|
||||
"""Poll endpoint returns only comments after the given ID."""
|
||||
resp = client.get(f"/comments/poll/{_article.id}/?after_id=0")
|
||||
assert resp.status_code == 200
|
||||
assert b"Alice" in resp.content
|
||||
|
||||
resp2 = client.get(f"/comments/poll/{_article.id}/?after_id={approved_comment.id}")
|
||||
assert resp2.status_code == 200
|
||||
assert b"Alice" not in resp2.content
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_comment_poll_no_duplicates(_article, client, approved_comment):
|
||||
"""Polling with current latest ID returns empty."""
|
||||
resp = client.get(f"/comments/poll/{_article.id}/?after_id={approved_comment.id}")
|
||||
assert b"comment-" not in resp.content
|
||||
|
||||
|
||||
# ── Reactions ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_react_creates_reaction(client, approved_comment):
|
||||
cache.clear()
|
||||
resp = client.post(
|
||||
f"/comments/{approved_comment.id}/react/",
|
||||
{"reaction_type": "heart"},
|
||||
HTTP_HX_REQUEST="true",
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert CommentReaction.objects.count() == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_react_toggle_removes_reaction(client, approved_comment):
|
||||
"""Second reaction of same type removes it (toggle)."""
|
||||
cache.clear()
|
||||
client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "heart"})
|
||||
client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "heart"})
|
||||
assert CommentReaction.objects.count() == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_react_different_types_coexist(client, approved_comment):
|
||||
cache.clear()
|
||||
client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "heart"})
|
||||
client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "plus_one"})
|
||||
assert CommentReaction.objects.count() == 2
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_react_invalid_type_returns_400(client, approved_comment):
|
||||
cache.clear()
|
||||
resp = client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "invalid"})
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_react_on_unapproved_comment_returns_404(client, _article):
|
||||
cache.clear()
|
||||
comment = Comment.objects.create(
|
||||
article=_article, author_name="B", author_email="b@b.com", body="x", is_approved=False,
|
||||
)
|
||||
resp = client.post(f"/comments/{comment.id}/react/", {"reaction_type": "heart"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(REACTION_RATE_LIMIT_PER_MINUTE=2)
|
||||
def test_react_rate_limit(client, approved_comment):
|
||||
cache.clear()
|
||||
for _ in range(2):
|
||||
client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "heart"})
|
||||
resp = client.post(f"/comments/{approved_comment.id}/react/", {"reaction_type": "plus_one"})
|
||||
assert resp.status_code == 429
|
||||
|
||||
|
||||
# ── CSP ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_csp_allows_turnstile(client, _article):
|
||||
"""CSP header includes Cloudflare Turnstile domains."""
|
||||
resp = client.get(_article.url)
|
||||
csp = resp.get("Content-Security-Policy", "")
|
||||
assert "challenges.cloudflare.com" in csp
|
||||
assert "frame-src" in csp
|
||||
|
||||
|
||||
# ── Purge Command Extension ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_purge_clears_reaction_session_keys(home_page):
|
||||
index = ArticleIndexPage(title="Articles", slug="articles")
|
||||
home_page.add_child(instance=index)
|
||||
author = AuthorFactory()
|
||||
article = ArticlePage(title="A", slug="a", author=author, summary="s", body=[("rich_text", "<p>b</p>")])
|
||||
index.add_child(instance=article)
|
||||
article.save_revision().publish()
|
||||
|
||||
comment = Comment.objects.create(
|
||||
article=article, author_name="X", author_email="x@x.com", body="y", is_approved=True,
|
||||
)
|
||||
reaction = CommentReaction.objects.create(
|
||||
comment=comment, reaction_type="heart", session_key="abc123",
|
||||
)
|
||||
CommentReaction.objects.filter(pk=reaction.pk).update(created_at=timezone.now() - timedelta(days=800))
|
||||
|
||||
call_command("purge_old_comment_data")
|
||||
reaction.refresh_from_db()
|
||||
assert reaction.session_key == ""
|
||||
@@ -1,7 +1,9 @@
|
||||
from django.urls import path
|
||||
|
||||
from apps.comments.views import CommentCreateView
|
||||
from apps.comments.views import CommentCreateView, comment_poll, comment_react
|
||||
|
||||
urlpatterns = [
|
||||
path("post/", CommentCreateView.as_view(), name="comment_post"),
|
||||
path("poll/<int:article_id>/", comment_poll, name="comment_poll"),
|
||||
path("<int:comment_id>/react/", comment_react, name="comment_react"),
|
||||
]
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests as http_requests
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.http import HttpResponse
|
||||
from django.db import IntegrityError
|
||||
from django.db.models import F, Prefetch
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.views import View
|
||||
from django.views.decorators.http import require_GET, require_POST
|
||||
|
||||
from apps.blog.models import ArticlePage
|
||||
from apps.comments.forms import CommentForm
|
||||
from apps.comments.models import Comment
|
||||
from apps.comments.models import Comment, CommentReaction
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def client_ip_from_request(request) -> str:
|
||||
@@ -22,11 +31,53 @@ def client_ip_from_request(request) -> str:
|
||||
return remote_addr
|
||||
|
||||
|
||||
def _is_htmx(request) -> bool:
|
||||
return request.headers.get("HX-Request") == "true"
|
||||
|
||||
|
||||
def _add_vary_header(response):
|
||||
response["Vary"] = "HX-Request"
|
||||
return response
|
||||
|
||||
|
||||
def _verify_turnstile(token: str, ip: str) -> bool:
|
||||
secret = getattr(settings, "TURNSTILE_SECRET_KEY", "")
|
||||
if not secret:
|
||||
return False
|
||||
try:
|
||||
resp = http_requests.post(
|
||||
"https://challenges.cloudflare.com/turnstile/v0/siteverify",
|
||||
data={"secret": secret, "response": token, "remoteip": ip},
|
||||
timeout=5,
|
||||
)
|
||||
result = resp.json()
|
||||
if not result.get("success"):
|
||||
return False
|
||||
expected_hostname = getattr(settings, "TURNSTILE_EXPECTED_HOSTNAME", "")
|
||||
if expected_hostname and result.get("hostname") != expected_hostname:
|
||||
logger.warning("Turnstile hostname mismatch: %s", result.get("hostname"))
|
||||
return False
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Turnstile verification failed")
|
||||
return False
|
||||
|
||||
|
||||
def _turnstile_enabled() -> bool:
|
||||
return bool(getattr(settings, "TURNSTILE_SECRET_KEY", ""))
|
||||
|
||||
|
||||
class CommentCreateView(View):
|
||||
def _render_article_with_errors(self, request, article, form):
|
||||
if _is_htmx(request):
|
||||
ctx = {"comment_form": form, "page": article}
|
||||
ctx["turnstile_site_key"] = getattr(settings, "TURNSTILE_SITE_KEY", "")
|
||||
resp = render(request, "comments/_comment_form.html", ctx, status=422)
|
||||
return _add_vary_header(resp)
|
||||
context = article.get_context(request)
|
||||
context["page"] = article
|
||||
context["comment_form"] = form
|
||||
context["turnstile_site_key"] = getattr(settings, "TURNSTILE_SITE_KEY", "")
|
||||
return render(request, "blog/article_page.html", context, status=200)
|
||||
|
||||
def post(self, request):
|
||||
@@ -45,9 +96,21 @@ class CommentCreateView(View):
|
||||
|
||||
if form.is_valid():
|
||||
if form.cleaned_data.get("honeypot"):
|
||||
if _is_htmx(request):
|
||||
return _add_vary_header(
|
||||
render(request, "comments/_comment_success.html", {"message": "Comment posted!"})
|
||||
)
|
||||
return redirect(f"{article.url}?commented=1")
|
||||
|
||||
# Turnstile verification
|
||||
turnstile_ok = False
|
||||
if _turnstile_enabled():
|
||||
token = request.POST.get("cf-turnstile-response", "")
|
||||
turnstile_ok = _verify_turnstile(token, ip)
|
||||
|
||||
comment = form.save(commit=False)
|
||||
comment.article = article
|
||||
comment.is_approved = turnstile_ok
|
||||
parent_id = form.cleaned_data.get("parent_id")
|
||||
if parent_id:
|
||||
comment.parent = Comment.objects.filter(pk=parent_id, article=article).first()
|
||||
@@ -58,7 +121,97 @@ class CommentCreateView(View):
|
||||
form.add_error(None, "Reply depth exceeds the allowed limit")
|
||||
return self._render_article_with_errors(request, article, form)
|
||||
comment.save()
|
||||
messages.success(request, "Your comment is awaiting moderation")
|
||||
|
||||
if _is_htmx(request):
|
||||
if comment.is_approved:
|
||||
resp = render(request, "comments/_comment.html", {
|
||||
"comment": comment, "page": article,
|
||||
"turnstile_site_key": getattr(settings, "TURNSTILE_SITE_KEY", ""),
|
||||
})
|
||||
else:
|
||||
resp = render(request, "comments/_comment_success.html", {
|
||||
"message": "Your comment has been posted and is awaiting moderation.",
|
||||
})
|
||||
return _add_vary_header(resp)
|
||||
|
||||
messages.success(
|
||||
request,
|
||||
"Comment posted!" if comment.is_approved else "Your comment is awaiting moderation",
|
||||
)
|
||||
return redirect(f"{article.url}?commented=1")
|
||||
|
||||
return self._render_article_with_errors(request, article, form)
|
||||
|
||||
|
||||
@require_GET
|
||||
def comment_poll(request, article_id):
|
||||
"""Return comments newer than after_id for HTMX polling."""
|
||||
article = get_object_or_404(ArticlePage, pk=article_id)
|
||||
after_id = request.GET.get("after_id", "0")
|
||||
try:
|
||||
after_id = int(after_id)
|
||||
except (ValueError, TypeError):
|
||||
after_id = 0
|
||||
|
||||
approved_replies = Comment.objects.filter(is_approved=True).select_related("parent")
|
||||
comments = (
|
||||
article.comments.filter(is_approved=True, parent__isnull=True, id__gt=after_id)
|
||||
.prefetch_related(Prefetch("replies", queryset=approved_replies))
|
||||
.order_by("created_at", "id")
|
||||
)
|
||||
|
||||
resp = render(request, "comments/_comment_list_inner.html", {
|
||||
"approved_comments": comments,
|
||||
"page": article,
|
||||
"turnstile_site_key": getattr(settings, "TURNSTILE_SITE_KEY", ""),
|
||||
})
|
||||
return _add_vary_header(resp)
|
||||
|
||||
|
||||
@require_POST
|
||||
def comment_react(request, comment_id):
|
||||
"""Toggle a reaction on a comment."""
|
||||
ip = client_ip_from_request(request)
|
||||
key = f"reaction-rate:{ip}"
|
||||
count = cache.get(key, 0)
|
||||
rate_limit = getattr(settings, "REACTION_RATE_LIMIT_PER_MINUTE", 20)
|
||||
if count >= rate_limit:
|
||||
return HttpResponse(status=429)
|
||||
cache.set(key, count + 1, timeout=60)
|
||||
|
||||
comment = get_object_or_404(Comment, pk=comment_id, is_approved=True)
|
||||
reaction_type = request.POST.get("reaction_type", "heart")
|
||||
if reaction_type not in ("heart", "plus_one"):
|
||||
return HttpResponse(status=400)
|
||||
|
||||
if not request.session.session_key:
|
||||
request.session.create()
|
||||
session_key = request.session.session_key
|
||||
|
||||
try:
|
||||
existing = CommentReaction.objects.filter(
|
||||
comment=comment, reaction_type=reaction_type, session_key=session_key
|
||||
).first()
|
||||
if existing:
|
||||
existing.delete()
|
||||
else:
|
||||
CommentReaction.objects.create(
|
||||
comment=comment, reaction_type=reaction_type, session_key=session_key
|
||||
)
|
||||
except IntegrityError:
|
||||
pass
|
||||
|
||||
counts = {}
|
||||
for rt in ("heart", "plus_one"):
|
||||
counts[rt] = comment.reactions.filter(reaction_type=rt).count()
|
||||
user_reacted = set(
|
||||
comment.reactions.filter(session_key=session_key).values_list("reaction_type", flat=True)
|
||||
)
|
||||
|
||||
if _is_htmx(request):
|
||||
resp = render(request, "comments/_reactions.html", {
|
||||
"comment": comment, "counts": counts, "user_reacted": user_reacted,
|
||||
})
|
||||
return _add_vary_header(resp)
|
||||
|
||||
return JsonResponse({"counts": counts, "user_reacted": list(user_reacted)})
|
||||
|
||||
@@ -41,6 +41,34 @@ class ApproveCommentBulkAction(SnippetBulkAction):
|
||||
) % {"count": num_parent_objects}
|
||||
|
||||
|
||||
class UnapproveCommentBulkAction(SnippetBulkAction):
|
||||
display_name = _("Unapprove")
|
||||
action_type = "unapprove"
|
||||
aria_label = _("Unapprove selected comments")
|
||||
template_name = "comments/confirm_bulk_unapprove.html"
|
||||
action_priority = 30
|
||||
models = [Comment]
|
||||
|
||||
def check_perm(self, snippet):
|
||||
if getattr(self, "can_change_items", None) is None:
|
||||
self.can_change_items = self.request.user.has_perm(get_permission_name("change", self.model))
|
||||
return self.can_change_items
|
||||
|
||||
@classmethod
|
||||
def execute_action(cls, objects, **kwargs):
|
||||
updated = kwargs["self"].model.objects.filter(pk__in=[obj.pk for obj in objects], is_approved=True).update(
|
||||
is_approved=False
|
||||
)
|
||||
return updated, 0
|
||||
|
||||
def get_success_message(self, num_parent_objects, num_child_objects):
|
||||
return ngettext(
|
||||
"%(count)d comment unapproved.",
|
||||
"%(count)d comments unapproved.",
|
||||
num_parent_objects,
|
||||
) % {"count": num_parent_objects}
|
||||
|
||||
|
||||
class CommentViewSet(SnippetViewSet):
|
||||
model = Comment
|
||||
queryset = Comment.objects.all()
|
||||
@@ -70,3 +98,4 @@ class CommentViewSet(SnippetViewSet):
|
||||
|
||||
register_snippet(CommentViewSet)
|
||||
hooks.register("register_bulk_action", ApproveCommentBulkAction)
|
||||
hooks.register("register_bulk_action", UnapproveCommentBulkAction)
|
||||
|
||||
Reference in New Issue
Block a user