2018-12-11 11:18:07 +03:00
|
|
|
const jwt = require('express-jwt');
|
2021-05-24 12:42:05 +03:00
|
|
|
const {UnauthorizedError} = require('@tryghost/errors');
|
2018-12-11 11:18:07 +03:00
|
|
|
const membersService = require('../../members');
|
2020-05-27 20:47:53 +03:00
|
|
|
const config = require('../../../../shared/config');
|
2018-11-07 13:10:07 +03:00
|
|
|
|
2018-12-11 11:18:07 +03:00
|
|
|
let UNO_MEMBERINO;
|
2018-11-07 13:10:07 +03:00
|
|
|
|
2021-10-04 14:18:22 +03:00
|
|
|
async function createMiddleware() {
|
|
|
|
const url = require('url');
|
|
|
|
const {protocol, host} = url.parse(config.get('url'));
|
|
|
|
const siteOrigin = `${protocol}//${host}`;
|
2018-11-07 13:10:07 +03:00
|
|
|
|
2021-10-04 14:18:22 +03:00
|
|
|
const membersConfig = await membersService.api.getPublicConfig();
|
|
|
|
return jwt({
|
|
|
|
credentialsRequired: false,
|
|
|
|
requestProperty: 'member',
|
|
|
|
audience: siteOrigin,
|
|
|
|
issuer: membersConfig.issuer,
|
|
|
|
algorithms: ['RS512'],
|
|
|
|
secret: membersConfig.publicKey,
|
|
|
|
getToken(req) {
|
|
|
|
if (!req.get('authorization')) {
|
|
|
|
return null;
|
|
|
|
}
|
2018-11-07 13:10:07 +03:00
|
|
|
|
2021-10-04 14:18:22 +03:00
|
|
|
const [scheme, credentials] = req.get('authorization').split(/\s+/);
|
2018-11-07 13:10:07 +03:00
|
|
|
|
2021-10-04 14:18:22 +03:00
|
|
|
if (scheme !== 'GhostMembers') {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return credentials;
|
2018-12-11 11:18:07 +03:00
|
|
|
}
|
2021-10-04 14:18:22 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
get authenticateMembersToken() {
|
2021-05-24 12:42:05 +03:00
|
|
|
return async function (req, res, next) {
|
2021-10-04 14:18:22 +03:00
|
|
|
if (!UNO_MEMBERINO) {
|
|
|
|
UNO_MEMBERINO = await createMiddleware();
|
|
|
|
}
|
2021-05-24 12:42:05 +03:00
|
|
|
try {
|
2021-10-04 14:18:22 +03:00
|
|
|
const middleware = UNO_MEMBERINO;
|
2021-05-24 12:42:05 +03:00
|
|
|
|
|
|
|
middleware(req, res, function (err, ...rest) {
|
|
|
|
if (err && err.name === 'UnauthorizedError') {
|
|
|
|
return next(new UnauthorizedError({err}), ...rest);
|
|
|
|
}
|
|
|
|
return next(err, ...rest);
|
|
|
|
});
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
|
|
|
}
|
2019-06-26 12:02:08 +03:00
|
|
|
};
|
2018-12-11 11:18:07 +03:00
|
|
|
}
|
2018-11-07 13:10:07 +03:00
|
|
|
};
|