| 1 | /**
|
|---|
| 2 | * Account routes — profile, password, avatar.
|
|---|
| 3 | *
|
|---|
| 4 | * Sections:
|
|---|
| 5 | * GET / -> render full account page (profile + password + avatar + danger)
|
|---|
| 6 | * POST /profile -> update bio
|
|---|
| 7 | * POST /password -> change password (verify current, hash new)
|
|---|
| 8 | * POST /avatar -> upload avatar image (multer)
|
|---|
| 9 | * POST /avatar/remove -> clear avatar_url
|
|---|
| 10 | *
|
|---|
| 11 | * Each form has its own POST handler. After success, redirects back to
|
|---|
| 12 | * /account?success=... so the page picks it up via query string.
|
|---|
| 13 | */
|
|---|
| 14 |
|
|---|
| 15 | import express from 'express';
|
|---|
| 16 | import path from 'path';
|
|---|
| 17 | import fs from 'fs';
|
|---|
| 18 | import { fileURLToPath } from 'url';
|
|---|
| 19 | import bcrypt from 'bcryptjs';
|
|---|
| 20 | import multer from 'multer';
|
|---|
| 21 | import { v4 as uuid } from 'uuid';
|
|---|
| 22 | import db from '../config/database.js';
|
|---|
| 23 | import { getPrimarySite } from '../middleware/site.js';
|
|---|
| 24 | import { renderPage } from '../middleware/render.js';
|
|---|
| 25 | import { requireAuth } from '../middleware/auth.js';
|
|---|
| 26 | import { googleConfigured } from '../config/google.js';
|
|---|
| 27 | import { toWebp } from '../services/ImageWebpService.js';
|
|---|
| 28 | import { SUPPORTED } from '../services/i18n.js';
|
|---|
| 29 |
|
|---|
| 30 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 31 | const AVATAR_DIR = path.resolve(
|
|---|
| 32 | process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
|
|---|
| 33 | );
|
|---|
| 34 | fs.mkdirSync(AVATAR_DIR, { recursive: true });
|
|---|
| 35 |
|
|---|
| 36 | const ALLOWED_AVATAR_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
|
|---|
| 37 | const MAX_AVATAR_BYTES = 5 * 1024 * 1024;
|
|---|
| 38 |
|
|---|
| 39 | const avatarStorage = multer.diskStorage({
|
|---|
| 40 | destination: (req, file, cb) => cb(null, AVATAR_DIR),
|
|---|
| 41 | filename: (req, file, cb) => {
|
|---|
| 42 | const ext = path.extname(file.originalname).toLowerCase();
|
|---|
| 43 | cb(null, `${uuid()}${ext}`);
|
|---|
| 44 | },
|
|---|
| 45 | });
|
|---|
| 46 | const avatarUpload = multer({
|
|---|
| 47 | storage: avatarStorage,
|
|---|
| 48 | limits: { fileSize: MAX_AVATAR_BYTES },
|
|---|
| 49 | fileFilter: (req, file, cb) => {
|
|---|
| 50 | const ext = path.extname(file.originalname).toLowerCase();
|
|---|
| 51 | if (!ALLOWED_AVATAR_EXT.has(ext)) {
|
|---|
| 52 | return cb(new Error('Avatar must be jpg/png/webp/gif'));
|
|---|
| 53 | }
|
|---|
| 54 | cb(null, true);
|
|---|
| 55 | },
|
|---|
| 56 | });
|
|---|
| 57 |
|
|---|
| 58 | const router = express.Router();
|
|---|
| 59 |
|
|---|
| 60 | // ==================== GET account page ====================
|
|---|
| 61 | router.get('/', requireAuth, (req, res) => {
|
|---|
| 62 | const account = db.prepare(`
|
|---|
| 63 | SELECT id, username, email, role, bio, avatar_url, created_at, password_hash, google_sub, lang
|
|---|
| 64 | FROM users WHERE id = ?
|
|---|
| 65 | `).get(req.session.user.id);
|
|---|
| 66 | const hasPassword = !!(account && account.password_hash && account.password_hash !== '!google-oauth');
|
|---|
| 67 | const googleLinked = !!(account && account.google_sub);
|
|---|
| 68 | if (account) { delete account.password_hash; delete account.google_sub; } // niet naar de view lekken
|
|---|
| 69 |
|
|---|
| 70 | renderPage(req, res, 'pages/account', {
|
|---|
| 71 | pageTitle: 'Account',
|
|---|
| 72 | bodyClass: 'on-special',
|
|---|
| 73 | account,
|
|---|
| 74 | hasPassword,
|
|---|
| 75 | googleLinked,
|
|---|
| 76 | googleAvailable: googleConfigured(),
|
|---|
| 77 | editableSite: ownedSite(req.session.user),
|
|---|
| 78 | success: req.query.success || null,
|
|---|
| 79 | error: req.query.error || null,
|
|---|
| 80 | });
|
|---|
| 81 | });
|
|---|
| 82 |
|
|---|
| 83 | // ==================== PERSOONLIJKE INTERFACE-TAAL ====================
|
|---|
| 84 | // Slaat de taalkeuze op het account op (reist mee over apparaten/sessies) én
|
|---|
| 85 | // zet 'm meteen in de sessie zodat 't direct effect heeft.
|
|---|
| 86 | router.post('/lang', requireAuth, (req, res) => {
|
|---|
| 87 | const code = SUPPORTED.includes(req.body.lang) ? req.body.lang : null;
|
|---|
| 88 | if (code) {
|
|---|
| 89 | db.prepare('UPDATE users SET lang = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(code, req.session.user.id);
|
|---|
| 90 | req.session.user.lang = code;
|
|---|
| 91 | req.session.lang = code;
|
|---|
| 92 | }
|
|---|
| 93 | res.redirect('/account?success=' + encodeURIComponent('Taal opgeslagen'));
|
|---|
| 94 | });
|
|---|
| 95 |
|
|---|
| 96 | // De site die deze gebruiker mag bewerken vanuit z'n account: z'n eigen site
|
|---|
| 97 | // (owner_id), of voor een god de primaire site. Null als er niets is.
|
|---|
| 98 | function ownedSite(user) {
|
|---|
| 99 | if (!user) return null;
|
|---|
| 100 | let site = db.prepare('SELECT id, title, tagline, slug, owner_id FROM sites WHERE owner_id = ? ORDER BY created_at LIMIT 1').get(user.id);
|
|---|
| 101 | if (!site && user.role === 'god') {
|
|---|
| 102 | site = getPrimarySite(); // primaire/hoofd-site als fallback
|
|---|
| 103 | }
|
|---|
| 104 | return site || null;
|
|---|
| 105 | }
|
|---|
| 106 |
|
|---|
| 107 | // ==================== UPDATE SITE-NAAM (eigenaar) ====================
|
|---|
| 108 | router.post('/site', requireAuth, (req, res) => {
|
|---|
| 109 | const site = ownedSite(req.session.user);
|
|---|
| 110 | if (!site) return res.redirect('/account?error=' + encodeURIComponent('Geen site om te bewerken.'));
|
|---|
| 111 | if (site.owner_id !== req.session.user.id && req.session.user.role !== 'god') {
|
|---|
| 112 | return res.redirect('/account?error=' + encodeURIComponent('Geen rechten om deze site te bewerken.'));
|
|---|
| 113 | }
|
|---|
| 114 | const title = (req.body.site_title || '').toString().slice(0, 200).trim();
|
|---|
| 115 | if (!title) return res.redirect('/account?error=' + encodeURIComponent('Site-naam mag niet leeg zijn.'));
|
|---|
| 116 | const tagline = (req.body.site_tagline || '').toString().slice(0, 200).trim();
|
|---|
| 117 | db.prepare('UPDATE sites SET title = ?, tagline = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 118 | .run(title, tagline || null, site.id);
|
|---|
| 119 | res.redirect('/account?success=' + encodeURIComponent('Site-naam bijgewerkt'));
|
|---|
| 120 | });
|
|---|
| 121 |
|
|---|
| 122 | // ==================== UPDATE BIO ====================
|
|---|
| 123 | router.post('/profile', requireAuth, (req, res) => {
|
|---|
| 124 | const bio = (req.body.bio || '').toString().slice(0, 500).trim();
|
|---|
| 125 |
|
|---|
| 126 | // E-mail (optioneel mee te wijzigen). Validatie: geldig formaat + niet al door
|
|---|
| 127 | // een ander account in gebruik. E-mail is het login-/reset-anker, dus uniek.
|
|---|
| 128 | const email = (req.body.email || '').toString().trim();
|
|---|
| 129 | if (email) {
|
|---|
| 130 | if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) {
|
|---|
| 131 | return res.redirect('/account?error=' + encodeURIComponent('Voer een geldig e-mailadres in.'));
|
|---|
| 132 | }
|
|---|
| 133 | const taken = db.prepare('SELECT 1 FROM users WHERE LOWER(email) = LOWER(?) AND id != ?')
|
|---|
| 134 | .get(email, req.session.user.id);
|
|---|
| 135 | if (taken) {
|
|---|
| 136 | return res.redirect('/account?error=' + encodeURIComponent('Dit e-mailadres is al in gebruik.'));
|
|---|
| 137 | }
|
|---|
| 138 | db.prepare('UPDATE users SET email = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 139 | .run(email, req.session.user.id);
|
|---|
| 140 | req.session.user.email = email; // sessie bijwerken zodat de UI klopt
|
|---|
| 141 | }
|
|---|
| 142 |
|
|---|
| 143 | db.prepare('UPDATE users SET bio = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 144 | .run(bio || null, req.session.user.id);
|
|---|
| 145 | res.redirect('/account?success=' + encodeURIComponent('Profiel bijgewerkt'));
|
|---|
| 146 | });
|
|---|
| 147 |
|
|---|
| 148 | // P57 — /preferences route removed. Per-user theme/palette was a multi-tenant
|
|---|
| 149 | // holdover that conflicts with the site-default model: visitors should see
|
|---|
| 150 | // the site's appearance, not whatever a user once picked. The users.theme and
|
|---|
| 151 | // users.palette columns stay in the schema (no migration needed) but are no
|
|---|
| 152 | // longer read or written.
|
|---|
| 153 |
|
|---|
| 154 | // ==================== CHANGE PASSWORD ====================
|
|---|
| 155 | router.post('/password', requireAuth, (req, res) => {
|
|---|
| 156 | const { current, new_password, confirm } = req.body;
|
|---|
| 157 | if (!current || !new_password || !confirm) {
|
|---|
| 158 | return res.redirect('/account?error=' + encodeURIComponent('Alle wachtwoordvelden zijn verplicht'));
|
|---|
| 159 | }
|
|---|
| 160 | if (new_password.length < 8) {
|
|---|
| 161 | return res.redirect('/account?error=' + encodeURIComponent('Nieuw wachtwoord moet minstens 8 tekens zijn'));
|
|---|
| 162 | }
|
|---|
| 163 | if (new_password !== confirm) {
|
|---|
| 164 | return res.redirect('/account?error=' + encodeURIComponent('Nieuwe wachtwoorden komen niet overeen'));
|
|---|
| 165 | }
|
|---|
| 166 |
|
|---|
| 167 | const row = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(req.session.user.id);
|
|---|
| 168 | // Google-only accounts (luisteraars) hebben geen echt wachtwoord.
|
|---|
| 169 | if (!row || !row.password_hash || row.password_hash === '!google-oauth') {
|
|---|
| 170 | return res.redirect('/account?error=' + encodeURIComponent('Dit account heeft geen wachtwoord (Google-login)'));
|
|---|
| 171 | }
|
|---|
| 172 | if (!bcrypt.compareSync(current, row.password_hash)) {
|
|---|
| 173 | return res.redirect('/account?error=' + encodeURIComponent('Huidig wachtwoord is onjuist'));
|
|---|
| 174 | }
|
|---|
| 175 |
|
|---|
| 176 | const newHash = bcrypt.hashSync(new_password, 10);
|
|---|
| 177 | db.prepare('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 178 | .run(newHash, req.session.user.id);
|
|---|
| 179 |
|
|---|
| 180 | res.redirect('/account?success=' + encodeURIComponent('Wachtwoord gewijzigd'));
|
|---|
| 181 | });
|
|---|
| 182 |
|
|---|
| 183 | // Google-account ontkoppelen. Alleen toegestaan als er nog een wachtwoord is,
|
|---|
| 184 | // anders zou je jezelf buitensluiten (geen login-methode meer over).
|
|---|
| 185 | router.post('/google/unlink', requireAuth, (req, res) => {
|
|---|
| 186 | const row = db.prepare('SELECT password_hash, google_sub FROM users WHERE id = ?').get(req.session.user.id);
|
|---|
| 187 | if (!row || !row.google_sub) {
|
|---|
| 188 | return res.redirect('/account?error=' + encodeURIComponent('Er is geen Google-account gekoppeld'));
|
|---|
| 189 | }
|
|---|
| 190 | if (!row.password_hash || row.password_hash === '!google-oauth') {
|
|---|
| 191 | return res.redirect('/account?error=' + encodeURIComponent('Stel eerst een wachtwoord in — anders kun je niet meer inloggen.'));
|
|---|
| 192 | }
|
|---|
| 193 | db.prepare('UPDATE users SET google_sub = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(req.session.user.id);
|
|---|
| 194 | res.redirect('/account?success=' + encodeURIComponent('Google-account ontkoppeld'));
|
|---|
| 195 | });
|
|---|
| 196 |
|
|---|
| 197 | // ==================== UPLOAD AVATAR ====================
|
|---|
| 198 | router.post('/avatar', requireAuth, (req, res) => {
|
|---|
| 199 | avatarUpload.single('avatar')(req, res, (err) => {
|
|---|
| 200 | if (err) {
|
|---|
| 201 | return res.redirect('/account?error=' + encodeURIComponent(err.message));
|
|---|
| 202 | }
|
|---|
| 203 | if (!req.file) {
|
|---|
| 204 | return res.redirect('/account?error=' + encodeURIComponent('No file uploaded'));
|
|---|
| 205 | }
|
|---|
| 206 |
|
|---|
| 207 | const url = `/media/avatars/${toWebp(req.file)}`;
|
|---|
| 208 |
|
|---|
| 209 | // Remove the old avatar file (if it lives in our avatar dir)
|
|---|
| 210 | const old = db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(req.session.user.id)?.avatar_url;
|
|---|
| 211 | if (old && old.startsWith('/media/avatars/')) {
|
|---|
| 212 | const oldPath = path.join(AVATAR_DIR, path.basename(old));
|
|---|
| 213 | try { fs.unlinkSync(oldPath); } catch {}
|
|---|
| 214 | }
|
|---|
| 215 |
|
|---|
| 216 | db.prepare('UPDATE users SET avatar_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 217 | .run(url, req.session.user.id);
|
|---|
| 218 | req.session.user.avatar_url = url;
|
|---|
| 219 |
|
|---|
| 220 | res.redirect('/account?success=' + encodeURIComponent('Avatar updated'));
|
|---|
| 221 | });
|
|---|
| 222 | });
|
|---|
| 223 |
|
|---|
| 224 | // ==================== REMOVE AVATAR ====================
|
|---|
| 225 | router.post('/avatar/remove', requireAuth, (req, res) => {
|
|---|
| 226 | const old = db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(req.session.user.id)?.avatar_url;
|
|---|
| 227 | if (old && old.startsWith('/media/avatars/')) {
|
|---|
| 228 | const oldPath = path.join(AVATAR_DIR, path.basename(old));
|
|---|
| 229 | try { fs.unlinkSync(oldPath); } catch {}
|
|---|
| 230 | }
|
|---|
| 231 | db.prepare('UPDATE users SET avatar_url = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
|
|---|
| 232 | .run(req.session.user.id);
|
|---|
| 233 | req.session.user.avatar_url = null;
|
|---|
| 234 | res.redirect('/account?success=' + encodeURIComponent('Avatar removed'));
|
|---|
| 235 | });
|
|---|
| 236 |
|
|---|
| 237 | export default router;
|
|---|