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

main
Last change on this file since 5f7dba2 was 6623453, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

Admin: dedicated SEO page (/admin/seo) for advanced SEO

The <head> already consumed a rich SEO set (title_template, canonical,
default_description, og_image_default, og_locale, author, *_verification,
facebook_app_id, publisher_*/schema_type for JSON-LD), but many fields
had nowhere to be edited. New god-only page manages the full set for the
primary site, accessible via a 🔎 SEO button in /admin.

The old hidden SEO block in Appearance has been removed (+ its columns
from the appearance-save so saving no longer zeroes them out) and replaced
with a link to the new page — single source of truth.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@â€Ļ>

  • Property mode set to 100644
File size: 14.2 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';
27
28const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
30// Profile photos share the avatar directory with user avatars — same physical
31// folder, same URL prefix. Filenames are uuid-prefixed so site photos and
32// user avatars never collide.
33const PHOTO_DIR = path.resolve(
34 process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
35);
36fs.mkdirSync(PHOTO_DIR, { recursive: true });
37
38const ALLOWED_PHOTO_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
39const MAX_PHOTO_BYTES = 5 * 1024 * 1024;
40const photoUpload = multer({
41 storage: multer.diskStorage({
42 destination: (req, file, cb) => cb(null, PHOTO_DIR),
43 filename: (req, file, cb) => {
44 const ext = path.extname(file.originalname || '').toLowerCase() || '.jpg';
45 cb(null, `site-${uuid()}${ext}`);
46 },
47 }),
48 limits: { fileSize: MAX_PHOTO_BYTES },
49 fileFilter: (req, file, cb) => {
50 const ext = path.extname(file.originalname || '').toLowerCase();
51 if (!ALLOWED_PHOTO_EXT.has(ext)) {
52 return cb(new Error('Alleen JPG/PNG/WebP/GIF toegestaan'));
53 }
54 cb(null, true);
55 },
56});
57
58/** Coerce req.body fields into the JSON profile_links array. */
59function buildProfileLinks(body) {
60 const platforms = body.profile_link_platform || [];
61 const urls = body.profile_link_url || [];
62 const arr = [];
63 const platformsArr = Array.isArray(platforms) ? platforms : [platforms];
64 const urlsArr = Array.isArray(urls) ? urls : [urls];
65 for (let i = 0; i < platformsArr.length; i++) {
66 const p = (platformsArr[i] || '').toString().trim();
67 const u = (urlsArr[i] || '').toString().trim();
68 if (!p || !u) continue;
69 if (!PLATFORMS[p]) continue;
70 if (!/^https?:\/\//i.test(u) && p !== 'email') continue;
71 if (p === 'email' && !/^mailto:|^[^\s@]+@[^\s@]+$/i.test(u)) continue;
72 arr.push({ platform: p, url: u });
73 }
74 return arr.length ? JSON.stringify(arr) : null;
75}
76
77const router = express.Router();
78
79// ==================== UPLOAD PROFILE PHOTO (JSON) ====================
80// POST /admin/sites/upload-photo → { ok: true, url: '/media/avatars/<filename>' }
81// Used by the admin-site-edit form's photo picker. The form itself still
82// holds the URL string in `profile_photo` — this endpoint just stores the
83// file and hands back a URL that the form can paste into the input field.
84router.post('/upload-photo', requireAuth, (req, res) => {
85 photoUpload.single('photo')(req, res, (err) => {
86 if (err) return res.status(400).json({ ok: false, error: err.message });
87 if (!req.file) return res.status(400).json({ ok: false, error: 'Geen bestand ontvangen' });
88 res.json({
89 ok: true,
90 url: `/media/avatars/${req.file.filename}`,
91 size: req.file.size,
92 mime: req.file.mimetype,
93 });
94 });
95});
96
97const RESERVED_SITE_SLUGS = new Set([
98 'auth', 'admin', 'login', 'register', 'logout', 'archive', 'search',
99 'account', 'sites', 'comments', 'posts', 'media', 'audio', 'prutter',
100 'forum', 'tag', 'user', 'users', 'artiesten', 'leden', 'feed.xml', 'atom.xml', 'sitemap.xml',
101 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
102]);
103
104function siteEditableFields() {
105 return {
106 title: '',
107 description: '',
108 tagline: '',
109 language: 'nl',
110 palette: 'sage',
111 accent: '#c2410c',
112 profile_photo: '',
113 profile_enabled: 1,
114 profile_name: '',
115 profile_bio: '',
116 is_public: 1,
117 robots_index: 1,
118 require_login_to_comment: 1,
119 enable_audio_player: 1,
120 enable_prutter: 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/** Geldige user-id voor owner-toewijzing, of null bij leeg/onbekend. */
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/** Geef een user admin-rechten op een 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/** Kandidaat-owners voor het owner-keuzeveld (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> (vanaf de gebruikers-pagina: "geef deze user een Klonkt") wordt
186 // voorgeselecteerd; anders de aanmakende 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 mag de site aan een ANDERE gebruiker toewijzen — dit is de kern
214 // van hub-modus (elke gebruiker z'n eigen, zelf te beheren Klonkt). Leeg of
215 // ongeldig → de aanmakende god zelf.
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, comments_moderation_mode
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 || 'sage',
234 ThemeService.validateAccent(f.accent) || '#c2410c',
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 f.comments_moderation_mode === 'trust' ? 'trust' : 'moderate',
242 );
243
244 // De OWNER (niet per se de aanmaker) krijgt een site_members-admin-rij → zo komt
245 // 'ie door canAdminSite + de requireSiteManager-gates en beheert 'ie z'n site.
246 grantSiteAdmin(siteId, ownerId);
247
248 res.redirect(`/admin/sites/${slug}/edit?success=` + encodeURIComponent('Site aangemaakt'));
249});
250
251// ==================== EDIT (form) ====================
252router.get('/:slug/edit', requireSiteManagerBySlug, (req, res) => {
253 const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(req.params.slug);
254 if (!site) return res.redirect('/admin/sites?error=Not+found');
255
256 let parsedLinks = [];
257 if (site.profile_links) {
258 try { parsedLinks = JSON.parse(site.profile_links) || []; } catch {}
259 }
260
261 renderPage(req, res, 'pages/admin-site-edit', {
262 pageTitle: `Edit: ${site.title}`,
263 bodyClass: 'on-admin',
264 isNew: false,
265 site,
266 users: listOwnerCandidates(),
267 palettes: ThemeService.listPalettes(),
268 accents: ThemeService.listAccents(),
269 platforms: listPlatforms(),
270 parsedLinks,
271 success: req.query.success || null,
272 error: req.query.error || null,
273 });
274});
275
276// ==================== SAVE ====================
277router.post('/:slug/save', requireSiteManagerBySlug, (req, res) => {
278 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
279 if (!site) return res.redirect('/admin/sites?error=Not+found');
280
281 const f = req.body;
282 const moderationMode = f.comments_moderation_mode === 'moderate' ? 'moderate' : 'trust';
283 const feedViewDef = f.feed_view_default === 'grid' ? 'grid' : 'timeline';
284 const profileLinksJson = buildProfileLinks(f);
285
286 // theme_override: only accept the three legal values. Empty string means
287 // "Auto" — defer to user's prefers-color-scheme on first paint.
288 const themeOverride = ['light', 'dark'].includes(f.theme_override) ? f.theme_override : '';
289
290 // accent: only accept colors from the curated ACCENTS list. Falls back to
291 // the orange default if the submitted value isn't recognised.
292 const accent = ThemeService.validateAccent(f.accent) || '#c2410c';
293
294 db.prepare(`
295 UPDATE sites SET
296 title = ?, description = ?, tagline = ?, language = ?,
297 palette = ?, accent = ?, theme_override = ?, profile_photo = ?,
298 profile_enabled = ?,
299 profile_links = ?,
300 is_public = ?, robots_index = ?, require_login_to_comment = ?,
301 enable_audio_player = ?, enable_prutter = ?,
302 comments_moderation_mode = ?,
303 feed_view_default = ?, feed_view_switch = ?,
304 show_search = ?, show_archive_link = ?,
305 custom_css = ?, custom_head_html = ?, custom_foot_html = ?,
306 updated_at = CURRENT_TIMESTAMP
307 WHERE id = ?
308 `).run(
309 (f.title || '').slice(0, 200),
310 (f.description || '').slice(0, 500),
311 (f.tagline || '').slice(0, 200),
312 f.language || 'nl',
313 f.palette || 'sage',
314 accent,
315 themeOverride,
316 f.profile_photo || null,
317 f.profile_enabled ? 1 : 0,
318 profileLinksJson,
319 f.is_public ? 1 : 0,
320 f.robots_index ? 1 : 0,
321 f.require_login_to_comment ? 1 : 0,
322 f.enable_audio_player ? 1 : 0,
323 f.enable_prutter ? 1 : 0,
324 moderationMode,
325 feedViewDef,
326 f.feed_view_switch ? 1 : 0,
327 f.show_search ? 1 : 0,
328 f.show_archive_link ? 1 : 0,
329 f.custom_css || null,
330 f.custom_head_html || null,
331 f.custom_foot_html || null,
332 site.id,
333 );
334
335 // Owner (her)toewijzen — ALLEEN god. Een site-owner die z'n eigen site bewerkt
336 // kan de eigenaar niet wijzigen (het veld wordt voor niet-god ook niet getoond).
337 if (req.session.user.role === 'god') {
338 const newOwner = validOwnerId(req.body.owner_id);
339 if (newOwner) {
340 db.prepare('UPDATE sites SET owner_id = ? WHERE id = ?').run(newOwner, site.id);
341 grantSiteAdmin(site.id, newOwner);
342 }
343 }
344
345 res.redirect(`/admin/sites/${req.params.slug}/edit?success=` + encodeURIComponent('Opgeslagen'));
346});
347
348// ==================== MAAK PRIMAIR ====================
349// God kiest welke site de primaire/hoofd-site is (de label-/bedrijfssite in hub;
350// in solo dÊ site). Precies ÊÊn site is primair → eerst alles uit, dan deze aan.
351router.post('/:slug/make-primary', requireGod, (req, res) => {
352 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
353 if (!site) return res.redirect('/admin/sites?error=Niet+gevonden');
354 db.transaction(() => {
355 db.prepare('UPDATE sites SET is_primary = 0').run();
356 db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(site.id);
357 })();
358 res.redirect('/admin/sites?success=' + encodeURIComponent('Primaire site bijgewerkt'));
359});
360
361// ==================== DELETE ====================
362router.post('/:slug/delete', requireGod, (req, res) => {
363 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
364 if (!site) return res.redirect('/admin/sites?error=Not+found');
365
366 const postCount = db.prepare('SELECT COUNT(*) AS c FROM posts WHERE site_id = ?').get(site.id).c;
367 if (postCount > 0) {
368 return res.redirect('/admin/sites?error=' + encodeURIComponent(`Cannot delete: site has ${postCount} post(s). Delete posts first.`));
369 }
370
371 // Clean up site_members and audio_tracks (no posts to worry about).
372 db.prepare('DELETE FROM site_members WHERE site_id = ?').run(site.id);
373 db.prepare('DELETE FROM audio_tracks WHERE site_id = ?').run(site.id);
374 db.prepare('DELETE FROM sites WHERE id = ?').run(site.id);
375
376 res.redirect('/admin/sites?success=' + encodeURIComponent('Site deleted'));
377});
378
379export default router;
Note: See TracBrowser for help on using the repository browser.