| [7bc636b] | 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 |
|
|---|
| 16 | import express from 'express';
|
|---|
| 17 | import path from 'path';
|
|---|
| 18 | import fs from 'fs';
|
|---|
| 19 | import { fileURLToPath } from 'url';
|
|---|
| 20 | import multer from 'multer';
|
|---|
| 21 | import { v4 as uuid } from 'uuid';
|
|---|
| 22 | import db from '../config/database.js';
|
|---|
| 23 | import { renderPage } from '../middleware/render.js';
|
|---|
| [8cb1dc7] | 24 | import { requireGod, requireAuth, requireSiteManagerBySlug } from '../middleware/auth.js';
|
|---|
| [7bc636b] | 25 | import ThemeService from '../services/ThemeService.js';
|
|---|
| 26 | import { listPlatforms, PLATFORMS } from '../services/PlatformIcons.js';
|
|---|
| 27 |
|
|---|
| 28 | const __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.
|
|---|
| 33 | const PHOTO_DIR = path.resolve(
|
|---|
| 34 | process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
|
|---|
| 35 | );
|
|---|
| 36 | fs.mkdirSync(PHOTO_DIR, { recursive: true });
|
|---|
| 37 |
|
|---|
| 38 | const ALLOWED_PHOTO_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
|
|---|
| 39 | const MAX_PHOTO_BYTES = 5 * 1024 * 1024;
|
|---|
| 40 | const 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. */
|
|---|
| 59 | function 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 |
|
|---|
| 77 | const 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.
|
|---|
| [8cb1dc7] | 84 | router.post('/upload-photo', requireAuth, (req, res) => {
|
|---|
| [7bc636b] | 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 |
|
|---|
| 97 | const RESERVED_SITE_SLUGS = new Set([
|
|---|
| 98 | 'auth', 'admin', 'login', 'register', 'logout', 'archive', 'search',
|
|---|
| 99 | 'account', 'sites', 'comments', 'posts', 'media', 'audio', 'prutter',
|
|---|
| [a1c8cb8] | 100 | 'forum', 'tag', 'user', 'users', 'artiesten', 'leden', 'feed.xml', 'atom.xml', 'sitemap.xml',
|
|---|
| [7bc636b] | 101 | 'manifest.webmanifest', 'sw.js', 'favicon.ico', 'favicon.svg', 'assets',
|
|---|
| 102 | ]);
|
|---|
| 103 |
|
|---|
| 104 | function 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: 0,
|
|---|
| 119 | enable_audio_player: 1,
|
|---|
| 120 | enable_prutter: 1,
|
|---|
| [8ea3d0d] | 121 | comments_moderation_mode: 'moderate',
|
|---|
| 122 | feed_view_default: 'grid',
|
|---|
| [7bc636b] | 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 | // ==================== LIST ====================
|
|---|
| 140 | router.get('/', requireGod, (req, res) => {
|
|---|
| 141 | const sites = db.prepare(`
|
|---|
| 142 | SELECT s.id, s.slug, s.title, s.description, s.created_at,
|
|---|
| 143 | s.is_public, s.robots_index,
|
|---|
| 144 | u.username AS owner_username,
|
|---|
| 145 | (SELECT COUNT(*) FROM posts WHERE site_id = s.id) AS post_count
|
|---|
| 146 | FROM sites s LEFT JOIN users u ON u.id = s.owner_id
|
|---|
| 147 | ORDER BY s.created_at DESC
|
|---|
| 148 | `).all();
|
|---|
| 149 |
|
|---|
| 150 | renderPage(req, res, 'pages/admin-sites', {
|
|---|
| 151 | pageTitle: 'Sites',
|
|---|
| 152 | bodyClass: 'on-admin',
|
|---|
| 153 | sites,
|
|---|
| 154 | success: req.query.success || null,
|
|---|
| 155 | error: req.query.error || null,
|
|---|
| 156 | });
|
|---|
| 157 | });
|
|---|
| 158 |
|
|---|
| 159 | // ==================== NEW (form) ====================
|
|---|
| 160 | router.get('/new', requireGod, (req, res) => {
|
|---|
| 161 | renderPage(req, res, 'pages/admin-site-edit', {
|
|---|
| 162 | pageTitle: 'New site',
|
|---|
| 163 | bodyClass: 'on-admin',
|
|---|
| 164 | isNew: true,
|
|---|
| 165 | site: { slug: '', ...siteEditableFields() },
|
|---|
| 166 | palettes: ThemeService.listPalettes(),
|
|---|
| 167 | accents: ThemeService.listAccents(),
|
|---|
| 168 | platforms: listPlatforms(),
|
|---|
| 169 | parsedLinks: [],
|
|---|
| 170 | error: null,
|
|---|
| 171 | });
|
|---|
| 172 | });
|
|---|
| 173 |
|
|---|
| 174 | // ==================== CREATE ====================
|
|---|
| 175 | router.post('/create', requireGod, (req, res) => {
|
|---|
| 176 | const slug = (req.body.slug || '').toString().toLowerCase().trim();
|
|---|
| 177 | if (!/^[a-z0-9_-]{2,40}$/.test(slug)) {
|
|---|
| 178 | return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug: 2-40 chars, letters/numbers/underscore/dash'));
|
|---|
| 179 | }
|
|---|
| 180 | if (RESERVED_SITE_SLUGS.has(slug)) {
|
|---|
| 181 | return res.redirect('/admin/sites/new?error=' + encodeURIComponent('That slug is reserved'));
|
|---|
| 182 | }
|
|---|
| 183 | const existing = db.prepare('SELECT id FROM sites WHERE slug = ?').get(slug);
|
|---|
| 184 | if (existing) {
|
|---|
| 185 | return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug already taken'));
|
|---|
| 186 | }
|
|---|
| 187 |
|
|---|
| 188 | const f = { ...siteEditableFields(), ...req.body };
|
|---|
| 189 | const siteId = uuid();
|
|---|
| 190 | db.prepare(`
|
|---|
| 191 | INSERT INTO sites (
|
|---|
| 192 | id, slug, title, description, tagline, owner_id,
|
|---|
| 193 | language, palette, accent, profile_photo,
|
|---|
| [8ea3d0d] | 194 | is_public, robots_index, require_login_to_comment, enable_audio_player,
|
|---|
| 195 | feed_view_default, comments_moderation_mode
|
|---|
| 196 | ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|---|
| [7bc636b] | 197 | `).run(
|
|---|
| 198 | siteId, slug,
|
|---|
| 199 | (f.title || slug).slice(0, 200),
|
|---|
| 200 | (f.description || '').slice(0, 500),
|
|---|
| 201 | (f.tagline || '').slice(0, 200),
|
|---|
| 202 | req.session.user.id,
|
|---|
| 203 | f.language || 'nl',
|
|---|
| 204 | f.palette || 'sage',
|
|---|
| 205 | ThemeService.validateAccent(f.accent) || '#c2410c',
|
|---|
| 206 | f.profile_photo || null,
|
|---|
| 207 | f.is_public ? 1 : 0,
|
|---|
| 208 | f.robots_index ? 1 : 0,
|
|---|
| 209 | f.require_login_to_comment ? 1 : 0,
|
|---|
| 210 | (f.enable_audio_player !== undefined ? (f.enable_audio_player ? 1 : 0) : 1),
|
|---|
| [8ea3d0d] | 211 | f.feed_view_default === 'timeline' ? 'timeline' : 'grid',
|
|---|
| 212 | f.comments_moderation_mode === 'trust' ? 'trust' : 'moderate',
|
|---|
| [7bc636b] | 213 | );
|
|---|
| 214 |
|
|---|
| 215 | // The site_members entry lets the god/owner show up in canAdminSite checks.
|
|---|
| 216 | db.prepare(`
|
|---|
| 217 | INSERT INTO site_members (site_id, user_id, role) VALUES (?, ?, 'admin')
|
|---|
| 218 | `).run(siteId, req.session.user.id);
|
|---|
| 219 |
|
|---|
| 220 | res.redirect(`/admin/sites/${slug}/edit?success=` + encodeURIComponent('Site created'));
|
|---|
| 221 | });
|
|---|
| 222 |
|
|---|
| 223 | // ==================== EDIT (form) ====================
|
|---|
| [8cb1dc7] | 224 | router.get('/:slug/edit', requireSiteManagerBySlug, (req, res) => {
|
|---|
| [7bc636b] | 225 | const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(req.params.slug);
|
|---|
| 226 | if (!site) return res.redirect('/admin/sites?error=Not+found');
|
|---|
| 227 |
|
|---|
| 228 | let parsedLinks = [];
|
|---|
| 229 | if (site.profile_links) {
|
|---|
| 230 | try { parsedLinks = JSON.parse(site.profile_links) || []; } catch {}
|
|---|
| 231 | }
|
|---|
| 232 |
|
|---|
| 233 | renderPage(req, res, 'pages/admin-site-edit', {
|
|---|
| 234 | pageTitle: `Edit: ${site.title}`,
|
|---|
| 235 | bodyClass: 'on-admin',
|
|---|
| 236 | isNew: false,
|
|---|
| 237 | site,
|
|---|
| 238 | palettes: ThemeService.listPalettes(),
|
|---|
| 239 | accents: ThemeService.listAccents(),
|
|---|
| 240 | platforms: listPlatforms(),
|
|---|
| 241 | parsedLinks,
|
|---|
| 242 | success: req.query.success || null,
|
|---|
| 243 | error: req.query.error || null,
|
|---|
| 244 | });
|
|---|
| 245 | });
|
|---|
| 246 |
|
|---|
| 247 | // ==================== SAVE ====================
|
|---|
| [8cb1dc7] | 248 | router.post('/:slug/save', requireSiteManagerBySlug, (req, res) => {
|
|---|
| [7bc636b] | 249 | const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
|
|---|
| 250 | if (!site) return res.redirect('/admin/sites?error=Not+found');
|
|---|
| 251 |
|
|---|
| 252 | const f = req.body;
|
|---|
| 253 | const moderationMode = f.comments_moderation_mode === 'moderate' ? 'moderate' : 'trust';
|
|---|
| 254 | const feedViewDef = f.feed_view_default === 'grid' ? 'grid' : 'timeline';
|
|---|
| 255 | const profileLinksJson = buildProfileLinks(f);
|
|---|
| 256 |
|
|---|
| 257 | // theme_override: only accept the three legal values. Empty string means
|
|---|
| 258 | // "Auto" — defer to user's prefers-color-scheme on first paint.
|
|---|
| 259 | const themeOverride = ['light', 'dark'].includes(f.theme_override) ? f.theme_override : '';
|
|---|
| 260 |
|
|---|
| 261 | // accent: only accept colors from the curated ACCENTS list. Falls back to
|
|---|
| 262 | // the orange default if the submitted value isn't recognised.
|
|---|
| 263 | const accent = ThemeService.validateAccent(f.accent) || '#c2410c';
|
|---|
| 264 |
|
|---|
| 265 | db.prepare(`
|
|---|
| 266 | UPDATE sites SET
|
|---|
| 267 | title = ?, description = ?, tagline = ?, language = ?,
|
|---|
| 268 | palette = ?, accent = ?, theme_override = ?, profile_photo = ?,
|
|---|
| [2c246d4] | 269 | profile_enabled = ?,
|
|---|
| [7bc636b] | 270 | profile_links = ?,
|
|---|
| 271 | is_public = ?, robots_index = ?, require_login_to_comment = ?,
|
|---|
| 272 | enable_audio_player = ?, enable_prutter = ?,
|
|---|
| 273 | comments_moderation_mode = ?,
|
|---|
| 274 | feed_view_default = ?, feed_view_switch = ?,
|
|---|
| 275 | show_search = ?, show_archive_link = ?,
|
|---|
| 276 | title_template = ?, twitter = ?, canonical = ?,
|
|---|
| 277 | google_verification = ?, bing_verification = ?,
|
|---|
| 278 | pinterest_verification = ?, yandex_verification = ?,
|
|---|
| 279 | custom_css = ?, custom_head_html = ?, custom_foot_html = ?,
|
|---|
| 280 | updated_at = CURRENT_TIMESTAMP
|
|---|
| 281 | WHERE id = ?
|
|---|
| 282 | `).run(
|
|---|
| 283 | (f.title || '').slice(0, 200),
|
|---|
| 284 | (f.description || '').slice(0, 500),
|
|---|
| 285 | (f.tagline || '').slice(0, 200),
|
|---|
| 286 | f.language || 'nl',
|
|---|
| 287 | f.palette || 'sage',
|
|---|
| 288 | accent,
|
|---|
| 289 | themeOverride,
|
|---|
| 290 | f.profile_photo || null,
|
|---|
| 291 | f.profile_enabled ? 1 : 0,
|
|---|
| 292 | profileLinksJson,
|
|---|
| 293 | f.is_public ? 1 : 0,
|
|---|
| 294 | f.robots_index ? 1 : 0,
|
|---|
| 295 | f.require_login_to_comment ? 1 : 0,
|
|---|
| 296 | f.enable_audio_player ? 1 : 0,
|
|---|
| 297 | f.enable_prutter ? 1 : 0,
|
|---|
| 298 | moderationMode,
|
|---|
| 299 | feedViewDef,
|
|---|
| 300 | f.feed_view_switch ? 1 : 0,
|
|---|
| 301 | f.show_search ? 1 : 0,
|
|---|
| 302 | f.show_archive_link ? 1 : 0,
|
|---|
| 303 | (f.title_template || '{title} — {site}').slice(0, 200),
|
|---|
| 304 | (f.twitter || '').slice(0, 64) || null,
|
|---|
| 305 | (f.canonical || '').slice(0, 200) || null,
|
|---|
| 306 | (f.google_verification || '').slice(0, 200) || null,
|
|---|
| 307 | (f.bing_verification || '').slice(0, 200) || null,
|
|---|
| 308 | (f.pinterest_verification || '').slice(0, 200) || null,
|
|---|
| 309 | (f.yandex_verification || '').slice(0, 200) || null,
|
|---|
| 310 | f.custom_css || null,
|
|---|
| 311 | f.custom_head_html || null,
|
|---|
| 312 | f.custom_foot_html || null,
|
|---|
| 313 | site.id,
|
|---|
| 314 | );
|
|---|
| 315 |
|
|---|
| 316 | res.redirect(`/admin/sites/${req.params.slug}/edit?success=` + encodeURIComponent('Saved'));
|
|---|
| 317 | });
|
|---|
| 318 |
|
|---|
| 319 | // ==================== DELETE ====================
|
|---|
| 320 | router.post('/:slug/delete', requireGod, (req, res) => {
|
|---|
| 321 | const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
|
|---|
| 322 | if (!site) return res.redirect('/admin/sites?error=Not+found');
|
|---|
| 323 |
|
|---|
| 324 | const postCount = db.prepare('SELECT COUNT(*) AS c FROM posts WHERE site_id = ?').get(site.id).c;
|
|---|
| 325 | if (postCount > 0) {
|
|---|
| 326 | return res.redirect('/admin/sites?error=' + encodeURIComponent(`Cannot delete: site has ${postCount} post(s). Delete posts first.`));
|
|---|
| 327 | }
|
|---|
| 328 |
|
|---|
| 329 | // Clean up site_members and audio_tracks (no posts to worry about).
|
|---|
| 330 | db.prepare('DELETE FROM site_members WHERE site_id = ?').run(site.id);
|
|---|
| 331 | db.prepare('DELETE FROM audio_tracks WHERE site_id = ?').run(site.id);
|
|---|
| 332 | db.prepare('DELETE FROM sites WHERE id = ?').run(site.id);
|
|---|
| 333 |
|
|---|
| 334 | res.redirect('/admin/sites?success=' + encodeURIComponent('Site deleted'));
|
|---|
| 335 | });
|
|---|
| 336 |
|
|---|
| 337 | export default router;
|
|---|