source: Klonkt/src/routes/account.js@ 62b899d

main
Last change on this file since 62b899d was 1be21ba, checked in by roboburr <roboburr@…>, 3 months ago

Account: owner can edit site name + tagline in account settings

New "Site" section on /account (owner / god only): edit site_title +
tagline via POST /account/site (ownership check). A quick place to change
the site name without navigating to Appearance.

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