source: Klonkt/src/routes/account.js@ 47a0d29

main
Last change on this file since 47a0d29 was 834bcc3, checked in by Robin Genis <roboburr@…>, 3 months ago

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

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

  • Property mode set to 100644
File size: 10.4 KB
Line 
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';
19import bcrypt from 'bcryptjs';
20import multer from 'multer';
21import { v4 as uuid } from 'uuid';
22import db from '../config/database.js';
23import { getPrimarySite } from '../middleware/site.js';
24import { renderPage } from '../middleware/render.js';
25import { requireAuth } from '../middleware/auth.js';
26import { googleConfigured } from '../config/google.js';
27import { toWebp } from '../services/ImageWebpService.js';
28import { SUPPORTED } from '../services/i18n.js';
29
30const __dirname = path.dirname(fileURLToPath(import.meta.url));
31const AVATAR_DIR = path.resolve(
32 process.env.AVATAR_PATH || path.join(__dirname, '..', '..', 'storage', 'media', 'avatars')
33);
34fs.mkdirSync(AVATAR_DIR, { recursive: true });
35
36const ALLOWED_AVATAR_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif']);
37const MAX_AVATAR_BYTES = 5 * 1024 * 1024;
38
39const 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});
46const 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
58const router = express.Router();
59
60// ==================== GET account page ====================
61router.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; } // don't leak to the view
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// ==================== PERSONAL INTERFACE LANGUAGE ====================
84// Saves the language choice on the account (persists across devices/sessions) and
85// also sets it in the session immediately so it takes effect right away.
86router.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// The site this user may edit from their account: their own site
97// (owner_id), or for a god the primary site. Null if nothing found.
98function 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(); // primary/main site as fallback
103 }
104 return site || null;
105}
106
107// ==================== UPDATE SITE-NAAM (eigenaar) ====================
108router.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 ====================
123router.post('/profile', requireAuth, (req, res) => {
124 const bio = (req.body.bio || '').toString().slice(0, 500).trim();
125
126 // Email (optionally also changed). Validation: valid format + not already in use
127 // by another account. Email is the login/reset anchor, so it must be unique.
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; // update session so the UI reflects the change
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 ====================
155router.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 (listeners) have no real password.
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// Unlink Google account. Only allowed if a password is set,
184// otherwise the user would lock themselves out (no login method left).
185router.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 ====================
198router.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 ====================
225router.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
237export default router;
Note: See TracBrowser for help on using the repository browser.