source: Klonkt/src/routes/admin-sites.js@ abdcf33

main
Last change on this file since abdcf33 was abdcf33, checked in by Robin Genis <roboburr@…>, 2 months ago

chore(cleanup): remove the dead comments_moderation_mode column + handling

Native comments are gone; this column was set but never read. Removed from the site
INSERT (admin-sites create) and UPDATE (save) in lockstep (column + placeholder + value),
from ensurePrimarySite's seed INSERT, the ensureColumn in database.js, and the 3 unused
i18n keys (asite.comment_moderation / moderation_trust / moderation_moderate, x3 langs).
No DROP — the column stays in existing DBs as harmless dead data. require_login_to_comment
is kept (still used by PermissionsService).

  • Property mode set to 100644
File size: 13.9 KB
Line 
1/**
2 * Admin: Site management — Phase E.
3 *
4 * GET /admin/sites -> list all sites
5 * GET /admin/sites/new -> create form
6 * POST /admin/sites/create -> insert + redirect to edit
7 * GET /admin/sites/:slug/edit -> edit form
8 * POST /admin/sites/:slug/save -> update
9 * POST /admin/sites/:slug/delete-> delete (refuses if site has posts)
10 *
11 * God-only (requireGod middleware). Slug is immutable after create — too
12 * many things hang off it (URLs, manifest scope, federation). If you really
13 * need to rename: delete + re-create.
14 */
15
16import express from 'express';
17import path from 'path';
18import fs from 'fs';
19import { fileURLToPath } from 'url';
20import multer from 'multer';
21import { v4 as uuid } from 'uuid';
22import db from '../config/database.js';
23import { renderPage } from '../middleware/render.js';
24import { requireGod, requireAuth, requireSiteManagerBySlug } from '../middleware/auth.js';
25import ThemeService from '../services/ThemeService.js';
26import { listPlatforms, PLATFORMS } from '../services/PlatformIcons.js';
27import { toWebp } from '../services/ImageWebpService.js';
28
29const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
31// Profile photos share the avatar directory with user avatars — same physical
32// folder, same URL prefix. Filenames are uuid-prefixed so site photos and
33// user avatars never collide.
34const PHOTO_DIR = path.resolve(
35 process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
36);
37fs.mkdirSync(PHOTO_DIR, { recursive: true });
38
39const ALLOWED_PHOTO_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
40const MAX_PHOTO_BYTES = 5 * 1024 * 1024;
41const photoUpload = multer({
42 storage: multer.diskStorage({
43 destination: (req, file, cb) => cb(null, PHOTO_DIR),
44 filename: (req, file, cb) => {
45 const ext = path.extname(file.originalname || '').toLowerCase() || '.jpg';
46 cb(null, `site-${uuid()}${ext}`);
47 },
48 }),
49 limits: { fileSize: MAX_PHOTO_BYTES },
50 fileFilter: (req, file, cb) => {
51 const ext = path.extname(file.originalname || '').toLowerCase();
52 if (!ALLOWED_PHOTO_EXT.has(ext)) {
53 return cb(new Error('Alleen JPG/PNG/WebP/GIF toegestaan'));
54 }
55 cb(null, true);
56 },
57});
58
59/** Coerce req.body fields into the JSON profile_links array. */
60function buildProfileLinks(body) {
61 const platforms = body.profile_link_platform || [];
62 const urls = body.profile_link_url || [];
63 const arr = [];
64 const platformsArr = Array.isArray(platforms) ? platforms : [platforms];
65 const urlsArr = Array.isArray(urls) ? urls : [urls];
66 for (let i = 0; i < platformsArr.length; i++) {
67 const p = (platformsArr[i] || '').toString().trim();
68 const u = (urlsArr[i] || '').toString().trim();
69 if (!p || !u) continue;
70 if (!PLATFORMS[p]) continue;
71 if (!/^https?:\/\//i.test(u) && p !== 'email') continue;
72 if (p === 'email' && !/^mailto:|^[^\s@]+@[^\s@]+$/i.test(u)) continue;
73 arr.push({ platform: p, url: u });
74 }
75 return arr.length ? JSON.stringify(arr) : null;
76}
77
78const router = express.Router();
79
80// ==================== UPLOAD PROFILE PHOTO (JSON) ====================
81// POST /admin/sites/upload-photo → { ok: true, url: '/media/avatars/<filename>' }
82// Used by the admin-site-edit form's photo picker. The form itself still
83// holds the URL string in `profile_photo` — this endpoint just stores the
84// file and hands back a URL that the form can paste into the input field.
85router.post('/upload-photo', requireAuth, (req, res) => {
86 photoUpload.single('photo')(req, res, (err) => {
87 if (err) return res.status(400).json({ ok: false, error: err.message });
88 if (!req.file) return res.status(400).json({ ok: false, error: 'Geen bestand ontvangen' });
89 res.json({
90 ok: true,
91 url: `/media/avatars/${toWebp(req.file)}`,
92 size: req.file.size,
93 mime: req.file.mimetype,
94 });
95 });
96});
97
98const RESERVED_SITE_SLUGS = new Set([
99 'auth', 'admin', 'login', 'register', 'logout', 'archive', 'search',
100 'account', 'sites', 'comments', 'posts', 'media', 'audio',
101 'forum', 'tag', 'user', 'users', 'artiesten', 'leden', 'feed.xml', 'atom.xml', 'sitemap.xml',
102 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
103]);
104
105function siteEditableFields() {
106 return {
107 title: '',
108 description: '',
109 tagline: '',
110 language: 'nl',
111 palette: 'klonkt',
112 accent: '#e8b04b',
113 profile_photo: '',
114 profile_enabled: 1,
115 profile_name: '',
116 profile_bio: '',
117 is_public: 1,
118 robots_index: 1,
119 require_login_to_comment: 1,
120 enable_audio_player: 1,
121 comments_moderation_mode: 'moderate',
122 feed_view_default: 'grid',
123 feed_view_switch: 1,
124 show_search: 1,
125 show_archive_link: 1,
126 title_template: '{title} — {site}',
127 twitter: '',
128 canonical: '',
129 google_verification: '',
130 bing_verification: '',
131 pinterest_verification: '',
132 yandex_verification: '',
133 custom_css: '',
134 custom_head_html: '',
135 custom_foot_html: '',
136 };
137}
138
139/** Valid user-id for owner assignment, or null if empty/unknown. */
140function validOwnerId(raw) {
141 const id = (raw || '').toString().trim();
142 if (!id) return null;
143 return db.prepare('SELECT 1 FROM users WHERE id = ?').get(id) ? id : null;
144}
145
146/** Grant a user admin rights on a site (idempotent upsert). */
147function grantSiteAdmin(siteId, userId) {
148 db.prepare(`
149 INSERT INTO site_members (site_id, user_id, role) VALUES (?, ?, 'admin')
150 ON CONFLICT(site_id, user_id) DO UPDATE SET role = 'admin'
151 `).run(siteId, userId);
152}
153
154/** Candidate owners for the owner selector field (god-only). */
155function listOwnerCandidates() {
156 return db.prepare('SELECT id, username, role FROM users ORDER BY username').all();
157}
158
159// ==================== LIST ====================
160router.get('/', requireGod, (req, res) => {
161 const sites = db.prepare(`
162 SELECT s.id, s.slug, s.title, s.description, s.created_at,
163 s.is_public, s.robots_index, s.is_primary,
164 u.username AS owner_username,
165 (SELECT COUNT(*) FROM posts WHERE site_id = s.id) AS post_count
166 FROM sites s LEFT JOIN users u ON u.id = s.owner_id
167 ORDER BY s.is_primary DESC, s.created_at DESC
168 `).all();
169
170 renderPage(req, res, 'pages/admin-sites', {
171 pageTitle: 'Sites',
172 bodyClass: 'on-admin',
173 sites,
174 success: req.query.success || null,
175 error: req.query.error || null,
176 });
177});
178
179// ==================== NEW (form) ====================
180router.get('/new', requireGod, (req, res) => {
181 renderPage(req, res, 'pages/admin-site-edit', {
182 pageTitle: 'New site',
183 bodyClass: 'on-admin',
184 isNew: true,
185 // ?owner=<id> (from the users page: "give this user a Klonkt") is
186 // pre-selected; otherwise defaults to the creating god.
187 site: { slug: '', owner_id: validOwnerId(req.query.owner) || req.session.user.id, ...siteEditableFields() },
188 users: listOwnerCandidates(),
189 palettes: ThemeService.listPalettes(),
190 accents: ThemeService.listAccents(),
191 platforms: listPlatforms(),
192 parsedLinks: [],
193 error: null,
194 });
195});
196
197// ==================== CREATE ====================
198router.post('/create', requireGod, (req, res) => {
199 const slug = (req.body.slug || '').toString().toLowerCase().trim();
200 if (!/^[a-z0-9_-]{2,40}$/.test(slug)) {
201 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug: 2-40 chars, letters/numbers/underscore/dash'));
202 }
203 if (RESERVED_SITE_SLUGS.has(slug)) {
204 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('That slug is reserved'));
205 }
206 const existing = db.prepare('SELECT id FROM sites WHERE slug = ?').get(slug);
207 if (existing) {
208 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug already taken'));
209 }
210
211 const f = { ...siteEditableFields(), ...req.body };
212
213 // Owner: god may assign the site to a DIFFERENT user — this is the core of
214 // hub mode (each user their own self-managed Klonkt). Empty or invalid → the
215 // creating god themselves.
216 const ownerId = validOwnerId(req.body.owner_id) || req.session.user.id;
217
218 const siteId = uuid();
219 db.prepare(`
220 INSERT INTO sites (
221 id, slug, title, description, tagline, owner_id,
222 language, palette, accent, profile_photo,
223 is_public, robots_index, require_login_to_comment, enable_audio_player,
224 feed_view_default
225 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
226 `).run(
227 siteId, slug,
228 (f.title || slug).slice(0, 200),
229 (f.description || '').slice(0, 500),
230 (f.tagline || '').slice(0, 200),
231 ownerId,
232 f.language || 'nl',
233 f.palette || 'klonkt',
234 ThemeService.validateAccent(f.accent) || '#e8b04b',
235 f.profile_photo || null,
236 f.is_public ? 1 : 0,
237 f.robots_index ? 1 : 0,
238 f.require_login_to_comment ? 1 : 0,
239 (f.enable_audio_player !== undefined ? (f.enable_audio_player ? 1 : 0) : 1),
240 f.feed_view_default === 'timeline' ? 'timeline' : 'grid',
241 );
242
243 // The OWNER (not necessarily the creator) gets a site_members admin row → this
244 // lets them pass canAdminSite + requireSiteManager gates to manage their site.
245 grantSiteAdmin(siteId, ownerId);
246
247 res.redirect(`/admin/sites/${slug}/edit?success=` + encodeURIComponent('Site aangemaakt'));
248});
249
250// ==================== EDIT (form) ====================
251router.get('/:slug/edit', requireSiteManagerBySlug, (req, res) => {
252 const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(req.params.slug);
253 if (!site) return res.redirect('/admin/sites?error=Not+found');
254
255 let parsedLinks = [];
256 if (site.profile_links) {
257 try { parsedLinks = JSON.parse(site.profile_links) || []; } catch {}
258 }
259
260 renderPage(req, res, 'pages/admin-site-edit', {
261 pageTitle: `Edit: ${site.title}`,
262 bodyClass: 'on-admin',
263 isNew: false,
264 site,
265 users: listOwnerCandidates(),
266 palettes: ThemeService.listPalettes(),
267 accents: ThemeService.listAccents(),
268 platforms: listPlatforms(),
269 parsedLinks,
270 success: req.query.success || null,
271 error: req.query.error || null,
272 });
273});
274
275// ==================== SAVE ====================
276router.post('/:slug/save', requireSiteManagerBySlug, (req, res) => {
277 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
278 if (!site) return res.redirect('/admin/sites?error=Not+found');
279
280 const f = req.body;
281 const feedViewDef = f.feed_view_default === 'grid' ? 'grid' : 'timeline';
282 const profileLinksJson = buildProfileLinks(f);
283
284 // theme_override: only accept the three legal values. Empty string means
285 // "Auto" — defer to user's prefers-color-scheme on first paint.
286 const themeOverride = ['light', 'dark'].includes(f.theme_override) ? f.theme_override : '';
287
288 // accent: only accept colors from the curated ACCENTS list. Falls back to
289 // the orange default if the submitted value isn't recognised.
290 const accent = ThemeService.validateAccent(f.accent) || '#e8b04b';
291
292 db.prepare(`
293 UPDATE sites SET
294 title = ?, description = ?, tagline = ?, language = ?,
295 palette = ?, accent = ?, theme_override = ?, profile_photo = ?,
296 profile_enabled = ?,
297 profile_links = ?,
298 is_public = ?, robots_index = ?, require_login_to_comment = ?,
299 enable_audio_player = ?,
300 feed_view_default = ?, feed_view_switch = ?,
301 show_search = ?, show_archive_link = ?,
302 custom_css = ?, custom_head_html = ?, custom_foot_html = ?,
303 updated_at = CURRENT_TIMESTAMP
304 WHERE id = ?
305 `).run(
306 (f.title || '').slice(0, 200),
307 (f.description || '').slice(0, 500),
308 (f.tagline || '').slice(0, 200),
309 f.language || 'nl',
310 f.palette || 'klonkt',
311 accent,
312 themeOverride,
313 f.profile_photo || null,
314 f.profile_enabled ? 1 : 0,
315 profileLinksJson,
316 f.is_public ? 1 : 0,
317 f.robots_index ? 1 : 0,
318 f.require_login_to_comment ? 1 : 0,
319 f.enable_audio_player ? 1 : 0,
320 feedViewDef,
321 f.feed_view_switch ? 1 : 0,
322 f.show_search ? 1 : 0,
323 f.show_archive_link ? 1 : 0,
324 f.custom_css || null,
325 f.custom_head_html || null,
326 f.custom_foot_html || null,
327 site.id,
328 );
329
330 // (Re)assign owner — god ONLY. A site-owner editing their own site cannot
331 // change the owner (the field is not shown to non-god users either).
332 if (req.session.user.role === 'god') {
333 const newOwner = validOwnerId(req.body.owner_id);
334 if (newOwner) {
335 db.prepare('UPDATE sites SET owner_id = ? WHERE id = ?').run(newOwner, site.id);
336 grantSiteAdmin(site.id, newOwner);
337 }
338 }
339
340 res.redirect(`/admin/sites/${req.params.slug}/edit?success=` + encodeURIComponent('Opgeslagen'));
341});
342
343// ==================== MAKE PRIMARY ====================
344// God chooses which site is the primary/main site (the label/company site in hub;
345// in solo mode: the one site). Exactly one site is primary → clear all, then set this one.
346router.post('/:slug/make-primary', requireGod, (req, res) => {
347 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
348 if (!site) return res.redirect('/admin/sites?error=Niet+gevonden');
349 db.transaction(() => {
350 db.prepare('UPDATE sites SET is_primary = 0').run();
351 db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(site.id);
352 })();
353 res.redirect('/admin/sites?success=' + encodeURIComponent('Primaire site bijgewerkt'));
354});
355
356// ==================== DELETE ====================
357router.post('/:slug/delete', requireGod, (req, res) => {
358 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
359 if (!site) return res.redirect('/admin/sites?error=Not+found');
360
361 const postCount = db.prepare('SELECT COUNT(*) AS c FROM posts WHERE site_id = ?').get(site.id).c;
362 if (postCount > 0) {
363 return res.redirect('/admin/sites?error=' + encodeURIComponent(`Cannot delete: site has ${postCount} post(s). Delete posts first.`));
364 }
365
366 // Clean up site_members and audio_tracks (no posts to worry about).
367 db.prepare('DELETE FROM site_members WHERE site_id = ?').run(site.id);
368 db.prepare('DELETE FROM audio_tracks WHERE site_id = ?').run(site.id);
369 db.prepare('DELETE FROM sites WHERE id = ?').run(site.id);
370
371 res.redirect('/admin/sites?success=' + encodeURIComponent('Site deleted'));
372});
373
374export default router;
Note: See TracBrowser for help on using the repository browser.