Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃尩 [SPIKE] Cache members content #20022

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion ghost/core/core/frontend/services/rendering/renderer.js
Expand Up @@ -32,7 +32,7 @@ module.exports = function renderer(req, res, data) {
}

// Render Call
res.render(res._template, data, function (err, html) {
res.render(res._template, data, function (err, html, renderInfo) {
if (err) {
if (err.code === 'ENOENT') {
return req.next(
Expand All @@ -43,6 +43,17 @@ module.exports = function renderer(req, res, data) {
}
return req.next(err);
}
if (res.locals.member) {
const memberDataUsed = Array.from(renderInfo.dataUsed).filter(property => property.startsWith('@member'));
const personalisedMemberDataUsed = memberDataUsed.filter(property => !['@member', '@member.paid'].includes(property));

// We didn't use any personal data, any member with the same tier as this one should get the same content
if (personalisedMemberDataUsed.length === 0) {
const activeSubscription = res.locals.member.subscriptions.find(sub => sub.status === 'active');
const memberTier = activeSubscription && activeSubscription.tier.slug || 'free';
res.setHeader('X-Member-Cache-Tier', memberTier);
}
}
res.send(html);
});
};
7 changes: 6 additions & 1 deletion ghost/core/core/frontend/services/theme-engine/active.js
Expand Up @@ -112,7 +112,12 @@ class ActiveTheme {
siteApp.cache = {};
// Set the views and engine
siteApp.set('views', this.path);
siteApp.engine('hbs', engine.configure(this.partialsPath, this.path));
const hbsEngine = engine.configure(this.partialsPath, this.path);
siteApp.engine('hbs', function (view, opts, done) {
hbsEngine(view, opts, function (err, res) {
return done(err, res, {dataUsed: engine.datamap[view]});
});
});

this._mounted = true;
}
Expand Down
75 changes: 74 additions & 1 deletion ghost/core/core/frontend/services/theme-engine/engine.js
@@ -1,3 +1,6 @@
const Handlebars = require('handlebars');
const fs = require('fs');
const path = require('path');
const hbs = require('express-hbs');
const config = require('../../../shared/config');
const instance = hbs.create();
Expand All @@ -6,13 +9,83 @@ const instance = hbs.create();
if (config.get('env') !== 'production') {
instance.handlebars.logger.level = 0;
}
class DataReader extends Handlebars.Visitor {
constructor(data, filepath, exhbs, partialsPath) {
super();
this.data = data || new Set();
this.filename = filepath;
this.exhbs = exhbs;
this.partialsPath = partialsPath;
}

CommentStatement(comment) {
const layoutRegex = /<\s+([A-Za-z0-9\._\-\/]+)\s*/;
const [isLayout, layoutName] = comment.value.match(layoutRegex) || [false, null];

if (isLayout) {
try {
const layoutFilePath = this.exhbs.layoutPath(this.filename, layoutName);
const layoutContent = fs.readFileSync(layoutFilePath + '.hbs').toString();
const ast = Handlebars.parseWithoutProcessing(layoutContent);
const reader = new DataReader(this.data, layoutFilePath, this.exhbs, this.partialsPath);
reader.accept(ast);
} catch (err) {
console.error(err);
}
}
}

PathExpression(path) {
if (path.data) {
this.data.add(path.original);
}
}

PartialStatement(partial) {
if (!this.partialsPath) {
throw new Error('No partials path, but found a partial');
}
const partialFilePath = path.join(this.partialsPath, partial.name.original);
try {
const partialContent = fs.readFileSync(partialFilePath + '.hbs').toString();
const ast = Handlebars.parseWithoutProcessing(partialContent);
const reader = new DataReader(this.data, partialFilePath, this.exhbs, this.partialsPath);
reader.accept(ast);
} catch (err) {
console.error(err);
}
}

static getData(exhbs, source, filename, partialsPath) {
const ast = Handlebars.parseWithoutProcessing(source);
const reader = new DataReader(new Set(), filename, exhbs, partialsPath);
reader.accept(ast);
return reader.data;
}
}

instance.escapeExpression = instance.handlebars.Utils.escapeExpression;

instance.configure = function configure(partialsPath, themePath) {
const helperTemplatesPath = config.get('paths').helperTemplates;
const hbsOptions = {
partialsDir: [config.get('paths').helperTemplates],
onCompile: function onCompile(exhbs, source) {
onCompile: function onCompile(exhbs, source, filename) {
if (filename.startsWith(helperTemplatesPath)) {
return exhbs.handlebars.compile(source, {preventIndent: true});
}
if (partialsPath && filename.startsWith(partialsPath)) {
return exhbs.handlebars.compile(source, {preventIndent: true});
}

const data = DataReader.getData(exhbs, source, filename, partialsPath);

if (!exhbs.datamap) {
exhbs.datamap = {};
}

exhbs.datamap[filename] = data;

return exhbs.handlebars.compile(source, {preventIndent: true});
},
restrictLayoutsTo: themePath
Expand Down
34 changes: 33 additions & 1 deletion ghost/core/core/server/services/members/middleware.js
@@ -1,3 +1,4 @@
const crypto = require('crypto');
const _ = require('lodash');
const logging = require('@tryghost/logging');
const membersService = require('./service');
Expand All @@ -11,12 +12,42 @@ const {
} = require('./utils');
const errors = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const onHeaders = require('on-headers');

const messages = {
missingUuid: 'Missing uuid.',
invalidUuid: 'Invalid uuid.'
};

const accessInfoSession = async function accessInfoSession(req, res, next) {
onHeaders(res, function () {
if (!req.member) {
const accessCookie = `ghost-access=null; Max-Age=0; Path=/; HttpOnly; SameSite=Strict;`;
const hmacCookie = `ghost-access-hmac=null; Max-Age=0; Path=/; HttpOnly; SameSite=Strict;`;
const existingCookies = res.getHeader('Set-Cookie') || [];
const cookiesToSet = [accessCookie, hmacCookie].concat(existingCookies);

res.setHeader('Set-Cookie', cookiesToSet);
return;
}

const activeSubscription = req.member.subscriptions?.find(sub => sub.status === 'active');

const memberTier = activeSubscription && activeSubscription.tier.slug || 'free';
const memberTierHmac = crypto.createHmac('sha256', '53CR37').update(memberTier).digest('hex');

const maxAge = 3600;
const accessCookie = `ghost-access=${memberTier}; Max-Age=${maxAge}; Path=/; HttpOnly; SameSite=Strict;`;
const hmacCookie = `ghost-access-hmac=${memberTierHmac}; Max-Age=${maxAge}; Path=/; HttpOnly; SameSite=Strict;`;

const existingCookies = res.getHeader('Set-Cookie') || [];
const cookiesToSet = [accessCookie, hmacCookie].concat(existingCookies);

res.setHeader('Set-Cookie', cookiesToSet);
});
next();
};

// @TODO: This piece of middleware actually belongs to the frontend, not to the member app
// Need to figure a way to separate these things (e.g. frontend actually talks to members API)
const loadMemberSession = async function loadMemberSession(req, res, next) {
Expand Down Expand Up @@ -92,7 +123,7 @@ const deleteSession = async function deleteSession(req, res) {

const getMemberData = async function getMemberData(req, res) {
try {
const member = await membersService.ssr.getMemberDataFromSession(req, res);
const member = req.member;
if (member) {
res.json(formattedMemberResponse(member));
} else {
Expand Down Expand Up @@ -322,5 +353,6 @@ module.exports = {
updateMemberData,
updateMemberNewsletters,
deleteSession,
accessInfoSession,
deleteSuppression
};
2 changes: 1 addition & 1 deletion ghost/core/core/server/web/members/app.js
Expand Up @@ -45,7 +45,7 @@ module.exports = function setupMembersApp() {
membersApp.put('/api/member/newsletters', bodyParser.json({limit: '50mb'}), middleware.updateMemberNewsletters);

// Get and update member data
membersApp.get('/api/member', middleware.getMemberData);
membersApp.get('/api/member', middleware.loadMemberSession, middleware.accessInfoSession, middleware.getMemberData);
membersApp.put('/api/member', bodyParser.json({limit: '50mb'}), middleware.updateMemberData);
membersApp.post('/api/member/email', bodyParser.json({limit: '50mb'}), (req, res) => membersService.api.middleware.updateEmailAddress(req, res));

Expand Down