source: Klonkt/src/routes/account.js@ 1794fac

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

Hub #3: explicit is_primary flag + shared getPrimarySite() (DRY)

The "oldest site = primary site" assumption was duplicated independently in
resolveSite, hub.js, account.js and admin.js (fragile: if the oldest happened
to be an artist site, the hub home would be wrong). Now:

  • sites.is_primary column + backfill (marks the oldest if none is primary yet; ensurePrimarySite sets it on fresh installs) → existing behaviour exactly preserved.
  • one getPrimarySite() helper (is_primary, fallback oldest) replaces the 4 copies.
  • god can CHOOSE the primary/main site: ★ button + "primary" badge on /admin/sites (exactly one primary via a transaction).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 7.7 KB
RevLine 
[7bc636b]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
15import express from 'express';
16import path from 'path';
17import fs from 'fs';
18import { fileURLToPath } from 'url';
[9e27d64]19import bcrypt from 'bcryptjs';
[7bc636b]20import multer from 'multer';
21import { v4 as uuid } from 'uuid';
22import db from '../config/database.js';
[7881080]23import { getPrimarySite } from '../middleware/site.js';
[7bc636b]24import { renderPage } from '../middleware/render.js';
25import { requireAuth } from '../middleware/auth.js';
26
27const __dirname = path.dirname(fileURLToPath(import.meta.url));
28const AVATAR_DIR = path.resolve(
29 process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
30);
31fs.mkdirSync(AVATAR_DIR, { recursive: true });
32
33const ALLOWED_AVATAR_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
34const MAX_AVATAR_BYTES = 5 * 1024 * 1024;
35
36const avatarStorage = multer.diskStorage({
37 destination: (req, file, cb) => cb(null, AVATAR_DIR),
38 filename: (req, file, cb) => {
39 const ext = path.extname(file.originalname).toLowerCase();
40 cb(null, `${uuid()}${ext}`);
41 },
42});
43const avatarUpload = multer({
44 storage: avatarStorage,
45 limits: { fileSize: MAX_AVATAR_BYTES },
46 fileFilter: (req, file, cb) => {
47 const ext = path.extname(file.originalname).toLowerCase();
48 if (!ALLOWED_AVATAR_EXT.has(ext)) {
49 return cb(new Error('Avatar must be jpg/png/webp/gif'));
50 }
51 cb(null, true);
52 },
53});
54
55const router = express.Router();
56
57// ==================== GET account page ====================
58router.get('/', requireAuth, (req, res) => {
59 const account = db.prepare(`
[9e27d64]60 SELECT id, username, email, role, bio, avatar_url, created_at, password_hash
[7bc636b]61 FROM users WHERE id = ?
62 `).get(req.session.user.id);
[9e27d64]63 const hasPassword = !!(account && account.password_hash && account.password_hash !== '!google-oauth');
64 if (account) delete account.password_hash; // niet naar de view lekken
[7bc636b]65
66 renderPage(req, res, 'pages/account', {
67 pageTitle: 'Account',
68 bodyClass: 'on-special',
69 account,
[9e27d64]70 hasPassword,
[1be21ba]71 editableSite: ownedSite(req.session.user),
[7bc636b]72 success: req.query.success || null,
73 error: req.query.error || null,
74 });
75});
76
[1be21ba]77// De site die deze gebruiker mag bewerken vanuit z'n account: z'n eigen site
78// (owner_id), of voor een god de primaire site. Null als er niets is.
79function ownedSite(user) {
80 if (!user) return null;
81 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);
82 if (!site && user.role === 'god') {
[7881080]83 site = getPrimarySite(); // primaire/hoofd-site als fallback
[1be21ba]84 }
85 return site || null;
86}
87
88// ==================== UPDATE SITE-NAAM (eigenaar) ====================
89router.post('/site', requireAuth, (req, res) => {
90 const site = ownedSite(req.session.user);
91 if (!site) return res.redirect('/account?error=' + encodeURIComponent('Geen site om te bewerken.'));
92 if (site.owner_id !== req.session.user.id && req.session.user.role !== 'god') {
93 return res.redirect('/account?error=' + encodeURIComponent('Geen rechten om deze site te bewerken.'));
94 }
95 const title = (req.body.site_title || '').toString().slice(0, 200).trim();
96 if (!title) return res.redirect('/account?error=' + encodeURIComponent('Site-naam mag niet leeg zijn.'));
97 const tagline = (req.body.site_tagline || '').toString().slice(0, 200).trim();
98 db.prepare('UPDATE sites SET title = ?, tagline = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
99 .run(title, tagline || null, site.id);
100 res.redirect('/account?success=' + encodeURIComponent('Site-naam bijgewerkt'));
101});
102
[7bc636b]103// ==================== UPDATE BIO ====================
104router.post('/profile', requireAuth, (req, res) => {
105 const bio = (req.body.bio || '').toString().slice(0, 500).trim();
106 db.prepare('UPDATE users SET bio = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
107 .run(bio || null, req.session.user.id);
108 res.redirect('/account?success=' + encodeURIComponent('Profile updated'));
109});
110
111// P57 — /preferences route removed. Per-user theme/palette was a multi-tenant
112// holdover that conflicts with the site-default model: visitors should see
113// the site's appearance, not whatever a user once picked. The users.theme and
114// users.palette columns stay in the schema (no migration needed) but are no
115// longer read or written.
116
[9e27d64]117// ==================== CHANGE PASSWORD ====================
118router.post('/password', requireAuth, (req, res) => {
119 const { current, new_password, confirm } = req.body;
120 if (!current || !new_password || !confirm) {
121 return res.redirect('/account?error=' + encodeURIComponent('Alle wachtwoordvelden zijn verplicht'));
122 }
123 if (new_password.length < 8) {
124 return res.redirect('/account?error=' + encodeURIComponent('Nieuw wachtwoord moet minstens 8 tekens zijn'));
125 }
126 if (new_password !== confirm) {
127 return res.redirect('/account?error=' + encodeURIComponent('Nieuwe wachtwoorden komen niet overeen'));
128 }
129
130 const row = db.prepare('SELECT password_hash FROM users WHERE id = ?').get(req.session.user.id);
131 // Google-only accounts (luisteraars) hebben geen echt wachtwoord.
132 if (!row || !row.password_hash || row.password_hash === '!google-oauth') {
133 return res.redirect('/account?error=' + encodeURIComponent('Dit account heeft geen wachtwoord (Google-login)'));
134 }
135 if (!bcrypt.compareSync(current, row.password_hash)) {
136 return res.redirect('/account?error=' + encodeURIComponent('Huidig wachtwoord is onjuist'));
137 }
138
139 const newHash = bcrypt.hashSync(new_password, 10);
140 db.prepare('UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
141 .run(newHash, req.session.user.id);
142
143 res.redirect('/account?success=' + encodeURIComponent('Wachtwoord gewijzigd'));
144});
[7bc636b]145
146// ==================== UPLOAD AVATAR ====================
147router.post('/avatar', requireAuth, (req, res) => {
148 avatarUpload.single('avatar')(req, res, (err) => {
149 if (err) {
150 return res.redirect('/account?error=' + encodeURIComponent(err.message));
151 }
152 if (!req.file) {
153 return res.redirect('/account?error=' + encodeURIComponent('No file uploaded'));
154 }
155
156 const url = `/media/avatars/${req.file.filename}`;
157
158 // Remove the old avatar file (if it lives in our avatar dir)
159 const old = db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(req.session.user.id)?.avatar_url;
160 if (old && old.startsWith('/media/avatars/')) {
161 const oldPath = path.join(AVATAR_DIR, path.basename(old));
162 try { fs.unlinkSync(oldPath); } catch {}
163 }
164
165 db.prepare('UPDATE users SET avatar_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
166 .run(url, req.session.user.id);
167 req.session.user.avatar_url = url;
168
169 res.redirect('/account?success=' + encodeURIComponent('Avatar updated'));
170 });
171});
172
173// ==================== REMOVE AVATAR ====================
174router.post('/avatar/remove', requireAuth, (req, res) => {
175 const old = db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(req.session.user.id)?.avatar_url;
176 if (old && old.startsWith('/media/avatars/')) {
177 const oldPath = path.join(AVATAR_DIR, path.basename(old));
178 try { fs.unlinkSync(oldPath); } catch {}
179 }
180 db.prepare('UPDATE users SET avatar_url = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?')
181 .run(req.session.user.id);
182 req.session.user.avatar_url = null;
183 res.redirect('/account?success=' + encodeURIComponent('Avatar removed'));
184});
185
186export default router;
Note: See TracBrowser for help on using the repository browser.