source: Klonkt/src/routes/admin-settings.js@ 2e9773f

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

refactor(auth): remove Google login (listeners now interact via the fediverse)

Removes config/google.js, the /auth/google* routes, the admin Google config page
+ links, the account link/unlink, and the public Google login button. /login and
/auth/admin both show the admin password form. SEO/Search-Console Google is
untouched. (Native comments removed next.)

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

  • Property mode set to 100644
File size: 8.5 KB
Line 
1/**
2 * Admin: global settings.
3 * - tenancy mode (Solo/Hub)
4 * - hub branding (name/tagline/intro/hero of the generic hub home page)
5 *
6 * GET /admin/settings -> show current settings
7 * POST /admin/settings -> save (god-only). Also accepts an uploaded
8 * hero image (multipart); an upload wins over the
9 * URL text field. Without an upload the URL field is leading.
10 *
11 * The hub page is generic (belonging to no user); this branding lives in
12 * global settings, not in a site.
13 */
14
15import express from 'express';
16import path from 'path';
17import fs from 'fs';
18import { fileURLToPath } from 'url';
19import multer from 'multer';
20import { v4 as uuid } from 'uuid';
21import { renderPage } from '../middleware/render.js';
22import { requireGod } from '../middleware/auth.js';
23import { getTenancy, setTenancy, getSetting, setSetting } from '../services/SettingsService.js';
24import { SUPPORTED } from '../services/i18n.js';
25import { mailerStatus, sendMail } from '../config/mailer.js';
26import { entitlementStatus, premiumUnlocked } from '../services/PatreonService.js';
27import { toWebp } from '../services/ImageWebpService.js';
28
29const router = express.Router();
30
31// Hero dark overlay: percentage 0-100 (0 = no overlay, 100 = fully black).
32// Default 45 = the old hard-coded value, so existing hubs don't change appearance.
33function clampOverlay(raw) {
34 const v = parseInt(raw, 10);
35 return Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : 45;
36}
37
38const __dirname = path.dirname(fileURLToPath(import.meta.url));
39// Hero uploads land in storage/media/hero → accessible as /media/hero/<file>
40// (the /media static handler serves storage/media). Same model as avatars.
41const HERO_DIR = path.resolve(
42 process.env.HERO_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'hero')
43);
44fs.mkdirSync(HERO_DIR, { recursive: true });
45
46// Only raster formats for upload. SVG is intentionally NOT allowed via upload
47// (raw SVG can contain scripts → stored-XSS when opened directly); an SVG hero
48// can still be set via the URL field (like the bundled demo placeholder).
49const ALLOWED_HERO_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
50const MAX_HERO_BYTES = 5 * 1024 * 1024;
51
52const heroUpload = multer({
53 storage: multer.diskStorage({
54 destination: (req, file, cb) => cb(null, HERO_DIR),
55 filename: (req, file, cb) => {
56 const ext = path.extname(file.originalname).toLowerCase();
57 cb(null, `${uuid()}${ext}`);
58 },
59 }),
60 limits: { fileSize: MAX_HERO_BYTES },
61 fileFilter: (req, file, cb) => {
62 const ext = path.extname(file.originalname).toLowerCase();
63 if (!ALLOWED_HERO_EXT.has(ext)) {
64 return cb(new Error('Hero-afbeelding moet jpg/png/webp/gif zijn'));
65 }
66 cb(null, true);
67 },
68});
69
70router.get('/', requireGod, (req, res) => {
71 renderPage(req, res, 'pages/admin-settings', {
72 pageTitle: 'Instellingen',
73 bodyClass: 'on-admin',
74 tenancy: getTenancy(),
75 hubTitle: getSetting('hub_title') || '',
76 hubTagline: getSetting('hub_tagline') || '',
77 hubIntro: getSetting('hub_intro') || '',
78 hubHeroImage: getSetting('hub_hero_image') || '',
79 hubHeroOverlay: clampOverlay(getSetting('hub_hero_overlay')),
80 defaultLang: getSetting('default_lang') || '',
81 premium: entitlementStatus(),
82 smtp: mailerStatus(),
83 footerNewsletter: getSetting('footer_newsletter') === '1',
84 success: req.query.success || null,
85 error: req.query.error || null,
86 });
87});
88
89router.post('/', requireGod, (req, res) => {
90 // multer.single processes multipart (hub branding form). For a plain
91 // urlencoded POST (tenancy form) multer does nothing and req.body stays intact.
92 heroUpload.single('hub_hero_file')(req, res, (err) => {
93 if (err) {
94 return res.redirect('/admin/settings?error=' + encodeURIComponent(err.message));
95 }
96
97 if (typeof req.body.tenancy !== 'undefined') {
98 // Hub mode is a premium feature: only switch to hub if premium is
99 // unlocked (premium layer off = free; on = Patreon required). Staying on
100 // hub is always allowed, so an instance can never get stuck.
101 if (req.body.tenancy === 'hub' && !premiumUnlocked() && getTenancy() !== 'hub') {
102 return res.redirect('/admin/settings?error=' + encodeURIComponent('Hub-modus is een premium-functie — koppel Patreon in Beheer → Instellingen.'));
103 }
104 setTenancy(req.body.tenancy); // valideert naar solo | hub | circle
105 }
106 if (typeof req.body.default_lang !== 'undefined') {
107 // Default language for visitors (empty = follow env/browser). Validated against NL/EN/DE.
108 const dl = (req.body.default_lang || '').toString().toLowerCase();
109 setSetting('default_lang', SUPPORTED.includes(dl) ? dl : '');
110 }
111 if (typeof req.body.timezone !== 'undefined') {
112 // Site timezone (IANA, e.g. Europe/Amsterdam). Empty = server default (UTC).
113 // Validate with Intl so a nonsense value never breaks date rendering.
114 const tz = (req.body.timezone || '').toString().trim();
115 let valid = '';
116 if (tz) { try { Intl.DateTimeFormat('en-US', { timeZone: tz }); valid = tz; } catch { valid = ''; } }
117 setSetting('timezone', valid);
118 }
119 if (typeof req.body.hub_title !== 'undefined') {
120 setSetting('hub_title', (req.body.hub_title || '').toString().slice(0, 80).trim());
121 }
122 if (typeof req.body.hub_tagline !== 'undefined') {
123 setSetting('hub_tagline', (req.body.hub_tagline || '').toString().slice(0, 120).trim());
124 }
125 if (typeof req.body.hub_intro !== 'undefined') {
126 setSetting('hub_intro', (req.body.hub_intro || '').toString().slice(0, 400).trim());
127 }
128
129 // Hero: an uploaded image wins; otherwise the URL text field.
130 if (req.file) {
131 const newUrl = `/media/hero/${toWebp(req.file)}`;
132 // Clean up a previously uploaded hero (only if it came from our hero dir).
133 const old = getSetting('hub_hero_image') || '';
134 if (old.startsWith('/media/hero/')) {
135 try { fs.unlinkSync(path.join(HERO_DIR, path.basename(old))); } catch {}
136 }
137 setSetting('hub_hero_image', newUrl);
138 } else if (typeof req.body.hub_hero_image !== 'undefined') {
139 setSetting('hub_hero_image', (req.body.hub_hero_image || '').toString().slice(0, 300).trim());
140 }
141
142 if (typeof req.body.hub_hero_overlay !== 'undefined') {
143 setSetting('hub_hero_overlay', String(clampOverlay(req.body.hub_hero_overlay)));
144 }
145
146 res.redirect('/admin/settings?success=' + encodeURIComponent('Opgeslagen'));
147 });
148});
149
150// ── SMTP / e-mail-instellingen ────────────────────────────────────
151router.post('/smtp', requireGod, (req, res) => {
152 const b = req.body || {};
153 if (b.clear === '1') {
154 ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from'].forEach((k) => setSetting(k, ''));
155 return res.redirect('/admin/settings?success=' + encodeURIComponent('SMTP-instellingen gewist'));
156 }
157 setSetting('smtp_host', (b.smtp_host || '').toString().trim());
158 setSetting('smtp_port', (b.smtp_port || '').toString().trim());
159 setSetting('smtp_user', (b.smtp_user || '').toString().trim());
160 setSetting('smtp_from', (b.smtp_from || '').toString().trim());
161 // Only overwrite the password if a new value was entered.
162 const pass = (b.smtp_pass || '').toString();
163 if (pass) setSetting('smtp_pass', pass);
164 res.redirect('/admin/settings?success=' + encodeURIComponent('SMTP-instellingen opgeslagen'));
165});
166
167// Newsletter sign-up in the footer on/off.
168router.post('/footer', requireGod, (req, res) => {
169 setSetting('footer_newsletter', req.body.footer_newsletter ? '1' : '0');
170 res.redirect('/admin/settings?success=' + encodeURIComponent('Footer-instelling opgeslagen'));
171});
172
173// Send a test email to a specified address (or the logged-in user).
174router.post('/smtp/test', requireGod, async (req, res) => {
175 const to = ((req.body && req.body.to) || (req.session.user && req.session.user.email) || '').toString().trim();
176 if (!to || to.indexOf('@') === -1) {
177 return res.redirect('/admin/settings?error=' + encodeURIComponent('Geef een geldig test-e-mailadres op.'));
178 }
179 try {
180 await sendMail({
181 to,
182 subject: 'Klonkt — SMTP-test',
183 text: 'Gelukt! Je SMTP-instellingen werken. Dit is een testbericht van je Klonkt-site.',
184 html: '<p>Gelukt! Je <strong>SMTP-instellingen werken</strong>. Dit is een testbericht van je Klonkt-site.</p>',
185 });
186 res.redirect('/admin/settings?success=' + encodeURIComponent('Testmail verstuurd naar ' + to));
187 } catch (e) {
188 res.redirect('/admin/settings?error=' + encodeURIComponent('Testmail mislukt: ' + (e.message || e)));
189 }
190});
191
192export default router;
Note: See TracBrowser for help on using the repository browser.