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