0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-10 23:36:14 -05:00
ghost/core/server/services/api-version-compatibility/mw-version-rewrites.js
Hannah Wolfe 6dc3f1bf56
Removed versioning from api-key/admin auth
refs: https://github.com/TryGhost/Toolbox/issues/229

- our api-key audience handling code is still relying on internal api version config
- the regex used is also buggy (it expects 3 parts, which isn't true without versions) and doesn't always match, in which case it can cause the tests to hang
- we already had some very similar code in the version-rewrite middleware which is also validates exact values for version and api type
- moved this code into a util inside api-version-compatibility-service
- using this code, all the tests still pass as is, but when I start to adjust them to cover more cases, none hang (test changes coming in a separate commit)
2022-05-06 08:09:54 +01:00

36 lines
1.2 KiB
JavaScript

const legacyApiPathMatch = require('./legacy-api-path-match');
const urlUtils = require('../../../shared/url-utils');
/**
* If there is a version in the URL, and this is a valid API URL containing admin/content
* Rewrite the URL and add the accept-version & deprecation headers
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
module.exports = (req, res, next) => {
let {version} = legacyApiPathMatch(req.url);
// If we don't match a valid version, carry on
if (!version) {
return next();
}
const versionlessUrl = req.url.replace(`${version}/`, '');
// Always send the explicit, numeric version in headers
if (version === 'canary') {
version = 'v4';
}
// Rewrite the url
req.url = versionlessUrl;
// Add the accept-version header so our internal systems will act as if it was set on the request
req.headers['accept-version'] = req.headers['accept-version'] || `${version}.0`;
res.header('Deprecation', `version="${version}"`);
res.header('Link', `<${urlUtils.urlJoin(urlUtils.urlFor('admin', true), 'api', versionlessUrl)}>; rel="latest-version"`);
next();
};