source: Klonkt/src/routes/comments.js@ 55bc7f9

main
Last change on this file since 55bc7f9 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 5.3 KB
Line 
1/**
2 * Comments — phase G v1.
3 *
4 * POST /comments -> create a comment on a post (auth required)
5 * POST /comments/:id/delete -> delete (own, or god/site-admin)
6 *
7 * Threading: 1 level deep (top-level + replies). Replies-of-replies fold up
8 * into the same parent (UI keeps it shallow).
9 *
10 * Status: auto-approved for logged-in users (trust mode). The schema's
11 * `status` column stays so we can switch to moderation later without changing
12 * shape. Anonymous comments (require_login_to_comment = 0 + no user) come
13 * later — for now we always require login.
14 */
15
16import express from 'express';
17import { v4 as uuid } from 'uuid';
18import db from '../config/database.js';
19import { requireAuth } from '../middleware/auth.js';
20import PermissionsService from '../services/PermissionsService.js';
21import { notify } from '../services/NotificationService.js';
22
23const router = express.Router();
24
25// Limits
26const MAX_LEN = 4000;
27const MIN_LEN = 1;
28
29router.post('/', requireAuth, (req, res) => {
30 const site = res.locals.site;
31 if (!site) return res.status(404).send('Site required');
32
33 const postSlug = (req.body.post_slug || '').trim();
34 const rawContent = (req.body.content || '').trim();
35 const parentId = (req.body.parent_comment_id || '').trim() || null;
36
37 if (!postSlug) return res.status(400).send('post_slug required');
38 if (rawContent.length < MIN_LEN) return res.status(400).send('Comment cannot be empty');
39 if (rawContent.length > MAX_LEN) return res.status(413).send(`Comment too long (max ${MAX_LEN} chars)`);
40
41 const post = db.prepare(
42 'SELECT id, slug, title, author_id FROM posts WHERE site_id = ? AND slug = ? AND status = ?'
43 ).get(site.id, postSlug, 'published');
44 if (!post) return res.status(404).send('Post not found');
45
46 if (!PermissionsService.canComment(req.session.user, site, post)) {
47 return res.status(403).send('Comments not allowed');
48 }
49
50 // Validate parent (must belong to this post; collapses replies-of-replies
51 // up to the top-level parent so we never go deeper than 1)
52 let resolvedParent = null;
53 let parentAuthorId = null;
54 if (parentId) {
55 const parent = db.prepare(
56 'SELECT id, parent_comment_id, author_id FROM comments WHERE id = ? AND post_id = ?'
57 ).get(parentId, post.id);
58 if (!parent) return res.status(400).send('Invalid parent comment');
59 resolvedParent = parent.parent_comment_id || parent.id;
60 parentAuthorId = parent.author_id; // recipient of the "reply" notification
61 }
62
63 // Status depends on the site's moderation mode.
64 // 'trust' = auto-approve immediately (default).
65 // 'moderate' = pending until an admin reviews in /admin/comments.
66 // Author is the post author or god → always trusted (no point gatekeeping yourself).
67 const isTrustedAuthor = req.session.user.role === 'god'
68 || req.session.user.id === post.author_id;
69 const status = (site.comments_moderation_mode === 'moderate' && !isTrustedAuthor)
70 ? 'pending'
71 : 'approved';
72
73 const commentId = uuid();
74 db.prepare(`
75 INSERT INTO comments (id, post_id, author_id, parent_comment_id, content, status)
76 VALUES (?, ?, ?, ?, ?, ?)
77 `).run(commentId, post.id, req.session.user.id, resolvedParent, rawContent, status);
78
79 // Notification (only for visible comments): reply → author of the parent comment;
80 // top-level comment → author of the post. notify() skips self-notifications.
81 if (status === 'approved') {
82 const url = `${res.locals.siteUrlBase || ''}/${post.slug}#comment-${commentId}`;
83 const actorId = req.session.user.id;
84 const actorName = req.session.user.username;
85 if (parentId) {
86 notify({ userId: parentAuthorId, actorId, actorName, type: 'reply', postSlug: post.slug, postTitle: post.title, url });
87 } else {
88 notify({ userId: post.author_id, actorId, actorName, type: 'comment', postSlug: post.slug, postTitle: post.title, url });
89 }
90 }
91
92 // Where to land after submit:
93 // approved → scroll to the new comment
94 // pending → comments anchor + ?pending=1 query so post page can flash a notice
95 const target = status === 'approved'
96 ? `${res.locals.siteUrlBase || ''}/${post.slug}#comment-${commentId}`
97 : `${res.locals.siteUrlBase || ''}/${post.slug}?pending=1#comments`;
98 if (req.headers['hx-request']) {
99 res.setHeader('HX-Redirect', target);
100 return res.send('OK');
101 }
102 res.redirect(target);
103});
104
105router.post('/:id/delete', requireAuth, (req, res) => {
106 const site = res.locals.site;
107 if (!site) return res.status(404).send('Site required');
108
109 const comment = db.prepare(`
110 SELECT c.id, c.author_id, c.post_id, p.slug AS post_slug
111 FROM comments c JOIN posts p ON p.id = c.post_id
112 WHERE c.id = ? AND p.site_id = ?
113 `).get(req.params.id, site.id);
114
115 if (!comment) return res.status(404).send('Not found');
116 if (!PermissionsService.canDeleteComment(req.session.user, comment, site)) {
117 return res.status(403).send('No permission');
118 }
119
120 // Delete the comment plus any replies that hung off it
121 db.prepare('DELETE FROM comments WHERE id = ? OR parent_comment_id = ?')
122 .run(req.params.id, req.params.id);
123
124 if (req.headers['hx-request']) {
125 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${comment.post_slug}#comments`);
126 return res.send('OK');
127 }
128 res.redirect(`${res.locals.siteUrlBase || ''}/${comment.post_slug}#comments`);
129});
130
131export default router;
Note: See TracBrowser for help on using the repository browser.