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

main
Last change on this file since 07775b7 was 07775b7, checked in by roboburr <roboburr@…>, 3 months ago

tenancy: Appearance page back link is mode-aware (solo -> Admin instead of Sites)

In solo there is no Sites list, so the "back" button on site-edit (Appearance)
pointed to a non-existent context. Now: solo -> /admin (Admin), hub -> /admin/sites.
Title shows "Appearance:" instead of "Edit:".

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

  • Property mode set to 100644
File size: 12.3 KB
RevLine 
[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
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 } from '../middleware/auth.js';
[07775b7]25import { getTenancy } from '../services/SettingsService.js';
[7bc636b]26import ThemeService from '../services/ThemeService.js';
27import { listPlatforms, PLATFORMS } from '../services/PlatformIcons.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', requireGod, (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/${req.file.filename}`,
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', 'prutter',
101 'forum', 'tag', 'users', '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: 'sage',
112 accent: '#c2410c',
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: 0,
120 enable_audio_player: 1,
121 enable_prutter: 1,
122 feed_view_default: 'timeline',
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 ====================
140router.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) ====================
160router.get('/new', requireGod, (req, res) => {
161 renderPage(req, res, 'pages/admin-site-edit', {
162 pageTitle: 'New site',
163 bodyClass: 'on-admin',
[07775b7]164 tenancy: getTenancy(),
[7bc636b]165 isNew: true,
166 site: { slug: '', ...siteEditableFields() },
167 palettes: ThemeService.listPalettes(),
168 accents: ThemeService.listAccents(),
169 platforms: listPlatforms(),
170 parsedLinks: [],
171 error: null,
172 });
173});
174
175// ==================== CREATE ====================
176router.post('/create', requireGod, (req, res) => {
177 const slug = (req.body.slug || '').toString().toLowerCase().trim();
178 if (!/^[a-z0-9_-]{2,40}$/.test(slug)) {
179 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug: 2-40 chars, letters/numbers/underscore/dash'));
180 }
181 if (RESERVED_SITE_SLUGS.has(slug)) {
182 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('That slug is reserved'));
183 }
184 const existing = db.prepare('SELECT id FROM sites WHERE slug = ?').get(slug);
185 if (existing) {
186 return res.redirect('/admin/sites/new?error=' + encodeURIComponent('Slug already taken'));
187 }
188
189 const f = { ...siteEditableFields(), ...req.body };
190 const siteId = uuid();
191 db.prepare(`
192 INSERT INTO sites (
193 id, slug, title, description, tagline, owner_id,
194 language, palette, accent, profile_photo,
195 is_public, robots_index, require_login_to_comment, enable_audio_player
196 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
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),
211 );
212
213 // The site_members entry lets the god/owner show up in canAdminSite checks.
214 db.prepare(`
215 INSERT INTO site_members (site_id, user_id, role) VALUES (?, ?, 'admin')
216 `).run(siteId, req.session.user.id);
217
218 res.redirect(`/admin/sites/${slug}/edit?success=` + encodeURIComponent('Site created'));
219});
220
221// ==================== EDIT (form) ====================
222router.get('/:slug/edit', requireGod, (req, res) => {
223 const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(req.params.slug);
224 if (!site) return res.redirect('/admin/sites?error=Not+found');
225
226 let parsedLinks = [];
227 if (site.profile_links) {
228 try { parsedLinks = JSON.parse(site.profile_links) || []; } catch {}
229 }
230
231 renderPage(req, res, 'pages/admin-site-edit', {
232 pageTitle: `Edit: ${site.title}`,
233 bodyClass: 'on-admin',
[07775b7]234 tenancy: getTenancy(),
[7bc636b]235 isNew: false,
236 site,
237 palettes: ThemeService.listPalettes(),
238 accents: ThemeService.listAccents(),
239 platforms: listPlatforms(),
240 parsedLinks,
241 success: req.query.success || null,
242 error: req.query.error || null,
243 });
244});
245
246// ==================== SAVE ====================
247router.post('/:slug/save', requireGod, (req, res) => {
248 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
249 if (!site) return res.redirect('/admin/sites?error=Not+found');
250
251 const f = req.body;
252 const moderationMode = f.comments_moderation_mode === 'moderate' ? 'moderate' : 'trust';
253 const feedViewDef = f.feed_view_default === 'grid' ? 'grid' : 'timeline';
254 const profileLinksJson = buildProfileLinks(f);
255
256 // theme_override: only accept the three legal values. Empty string means
257 // "Auto" — defer to user's prefers-color-scheme on first paint.
258 const themeOverride = ['light', 'dark'].includes(f.theme_override) ? f.theme_override : '';
259
260 // accent: only accept colors from the curated ACCENTS list. Falls back to
261 // the orange default if the submitted value isn't recognised.
262 const accent = ThemeService.validateAccent(f.accent) || '#c2410c';
263
264 db.prepare(`
265 UPDATE sites SET
266 title = ?, description = ?, tagline = ?, language = ?,
267 palette = ?, accent = ?, theme_override = ?, profile_photo = ?,
268 profile_enabled = ?, profile_name = ?, profile_bio = ?,
269 profile_links = ?,
270 is_public = ?, robots_index = ?, require_login_to_comment = ?,
271 enable_audio_player = ?, enable_prutter = ?,
272 comments_moderation_mode = ?,
273 feed_view_default = ?, feed_view_switch = ?,
274 show_search = ?, show_archive_link = ?,
275 title_template = ?, twitter = ?, canonical = ?,
276 google_verification = ?, bing_verification = ?,
277 pinterest_verification = ?, yandex_verification = ?,
278 custom_css = ?, custom_head_html = ?, custom_foot_html = ?,
279 updated_at = CURRENT_TIMESTAMP
280 WHERE id = ?
281 `).run(
282 (f.title || '').slice(0, 200),
283 (f.description || '').slice(0, 500),
284 (f.tagline || '').slice(0, 200),
285 f.language || 'nl',
286 f.palette || 'sage',
287 accent,
288 themeOverride,
289 f.profile_photo || null,
290 f.profile_enabled ? 1 : 0,
291 (f.profile_name || '').slice(0, 100) || null,
292 (f.profile_bio || '').slice(0, 500) || null,
293 profileLinksJson,
294 f.is_public ? 1 : 0,
295 f.robots_index ? 1 : 0,
296 f.require_login_to_comment ? 1 : 0,
297 f.enable_audio_player ? 1 : 0,
298 f.enable_prutter ? 1 : 0,
299 moderationMode,
300 feedViewDef,
301 f.feed_view_switch ? 1 : 0,
302 f.show_search ? 1 : 0,
303 f.show_archive_link ? 1 : 0,
304 (f.title_template || '{title} — {site}').slice(0, 200),
305 (f.twitter || '').slice(0, 64) || null,
306 (f.canonical || '').slice(0, 200) || null,
307 (f.google_verification || '').slice(0, 200) || null,
308 (f.bing_verification || '').slice(0, 200) || null,
309 (f.pinterest_verification || '').slice(0, 200) || null,
310 (f.yandex_verification || '').slice(0, 200) || null,
311 f.custom_css || null,
312 f.custom_head_html || null,
313 f.custom_foot_html || null,
314 site.id,
315 );
316
317 res.redirect(`/admin/sites/${req.params.slug}/edit?success=` + encodeURIComponent('Saved'));
318});
319
320// ==================== DELETE ====================
321router.post('/:slug/delete', requireGod, (req, res) => {
322 const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(req.params.slug);
323 if (!site) return res.redirect('/admin/sites?error=Not+found');
324
325 const postCount = db.prepare('SELECT COUNT(*) AS c FROM posts WHERE site_id = ?').get(site.id).c;
326 if (postCount > 0) {
327 return res.redirect('/admin/sites?error=' + encodeURIComponent(`Cannot delete: site has ${postCount} post(s). Delete posts first.`));
328 }
329
330 // Clean up site_members and audio_tracks (no posts to worry about).
331 db.prepare('DELETE FROM site_members WHERE site_id = ?').run(site.id);
332 db.prepare('DELETE FROM audio_tracks WHERE site_id = ?').run(site.id);
333 db.prepare('DELETE FROM sites WHERE id = ?').run(site.id);
334
335 res.redirect('/admin/sites?success=' + encodeURIComponent('Site deleted'));
336});
337
338export default router;
Note: See TracBrowser for help on using the repository browser.