source: Klonkt/src/middleware/render.js@ ab544fd

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

fix: PrutFolio header + roster show the SITE OWNER's photo, not the viewer's

Bug: profile-header.ejs used user.avatar_url (the LOGGED-IN viewer) as the
profile photo -> every PrutFolio showed the picture of whoever was looking
("studionoord" appeared to change along with the viewer). Now: site.profile_photo
-> avatar of the site owner -> music/initial fallback; never the viewer.
siteOwnerAvatar comes from render.js. Roster (hub overview) likewise: per-site
owner avatar instead of nothing.

Result: an artist's account avatar (/account) is immediately their PrutFolio
photo; one "own picture" that is correct, per user.

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

  • Property mode set to 100644
File size: 4.8 KB
RevLine 
[7bc636b]1/**
2 * Render helper — THE pattern for the entire app.
3 *
4 * Two modes:
5 * 1. HTMX request → render just the page content (no shell)
6 * 2. Full page request → render content, then embed in shell
7 *
8 * Usage:
9 * renderPage(req, res, 'pages/home', { posts, ...data })
10 */
11
12import path from 'path';
13import { fileURLToPath } from 'url';
14import ejs from 'ejs';
[8cb1dc7]15import db from '../config/database.js';
[7bc636b]16import PermissionsService from '../services/PermissionsService.js';
17import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
18
19const __dirname = path.dirname(fileURLToPath(import.meta.url));
20const VIEWS_DIR = path.join(__dirname, '..', 'views');
21
22const formatDate = (iso) => {
23 if (!iso) return '';
24 const d = new Date(iso);
25 const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
26 return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
27};
28
29const formatDateTime = (iso) => {
30 if (!iso) return '';
31 const d = new Date(iso);
32 return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
33};
34
35export async function renderPage(req, res, viewName, data = {}) {
36 // Decide: partial (HTMX) or full?
37 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
38
[8cb1dc7]39 // Bezit deze (niet-god) user een eigen site? Bepaalt of 'ie een "Beheer"-
40 // ingang ziet (artiest-zelfbeheer). god ziet beheer sowieso (op rol).
41 const _u = req.session?.user || null;
42 const userOwnsSite = !!(_u && _u.role !== 'god' &&
43 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
44
[ab544fd]45 // De avatar van de SITE-EIGENAAR (niet de kijker!) — voor de PrutFolio-kop,
46 // zodat de artiest z'n eigen account-foto als sitefoto kan gebruiken.
47 const _site = data.site || res.locals.site || null;
48 const siteOwnerAvatar = (_site && _site.owner_id)
49 ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
50 : null;
51
[7bc636b]52 // Common locals
53 const locals = {
[8cb1dc7]54 user: _u,
55 userOwnsSite,
[ab544fd]56 siteOwnerAvatar,
57 site: _site,
[7bc636b]58 audioTracks: data.audioTracks || res.locals.audioTracks || [],
59 siteUrlBase: res.locals.siteUrlBase || '',
[2cc887b]60 tenancy: res.locals.tenancy || 'solo',
[7bc636b]61 platforms_catalog: PLATFORMS_CATALOG,
62 permissions: PermissionsService,
63 formatDate,
64 formatDateTime,
65 pageTitle: data.pageTitle || (data.site && data.site.title) || 'PrutCMS',
66 bodyClass: data.bodyClass || 'on-home',
67 socialDescr: data.socialDescr || '',
68 socialImage: data.socialImage || '',
69 cspNonce: () => '',
70 currentPath: req.path,
71 ...data,
72 };
73
74 try {
75 // Step 1: Render the page view to HTML
76 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
77 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
78
79 if (isPartial) {
80 // HTMX: just send the content. Set HX-Trigger for body class swap
81 res.setHeader('HX-Trigger-After-Settle', JSON.stringify({
82 pcmsNav: { bodyClass: locals.bodyClass },
83 pcmsPostSwap: data.post ? {
84 title: data.post.title,
85 slug: data.post.slug,
86 pageTitle: locals.pageTitle,
87 } : null,
88 }));
89 return res.send(pageContent);
90 }
91
92 // Full: wrap content in shell
93 locals.pageContent = pageContent;
94 res.render('shell', locals);
95 } catch (err) {
96 console.error('[renderPage] Error rendering', viewName, err);
97 if (process.env.NODE_ENV === 'production') {
98 return res.status(500).send('Internal Server Error');
99 }
100 // Dev: surface the underlying cause prominently. EJS rewrites err.message
101 // to include the file/line/code-context, so we also surface name+stack
102 // separately in case the message was truncated or empty.
103 const escape = (s) => String(s == null ? '' : s)
104 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
105 res.status(500).send(`<!doctype html>
106<meta charset="utf-8">
107<title>Render error: ${escape(viewName)}</title>
108<style>
109 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
110 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
111 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
112 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
113 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
114</style>
115<h1>Render error in ${escape(viewName)}</h1>
116<h2>Cause</h2>
117<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
118<h2>Stack</h2>
119<pre>${escape(err.stack || '(no stack)')}</pre>
120${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
121`);
122 }
123}
Note: See TracBrowser for help on using the repository browser.