2022-05-10 11:08:54 +03:00
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove 'Ghost' from raw authorization header and extract the JWT token.
|
|
|
|
* Eg. Authorization: Ghost ${JWT}
|
|
|
|
* @param {string} header
|
|
|
|
*/
|
|
|
|
const extractTokenFromHeader = (header) => {
|
|
|
|
const [scheme, token] = header.split(' ');
|
|
|
|
|
|
|
|
if (/^Ghost$/i.test(scheme)) {
|
|
|
|
return token;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const extractAdminAPIKey = (token) => {
|
|
|
|
const decoded = jwt.decode(token, {complete: true});
|
|
|
|
|
|
|
|
if (!decoded || !decoded.header || !decoded.header.kid) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return decoded.header.kid;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {object} ApiKey
|
|
|
|
* @prop {string} key
|
|
|
|
* @prop {string} type
|
|
|
|
*/
|
|
|
|
|
2022-05-10 07:37:05 +03:00
|
|
|
/**
|
2022-05-10 11:08:54 +03:00
|
|
|
* When it's a Content API the function resolves with the value of the key secret.
|
|
|
|
* When it's an Admin API the function resolves with the value of the key id.
|
2022-05-10 07:37:05 +03:00
|
|
|
*
|
|
|
|
* @param {import('express').Request} req
|
2022-05-10 11:08:54 +03:00
|
|
|
* @returns {ApiKey}
|
2022-05-10 07:37:05 +03:00
|
|
|
*/
|
|
|
|
const extractAPIKey = (req) => {
|
2022-05-10 09:44:55 +03:00
|
|
|
let keyValue = null;
|
2022-05-10 11:08:54 +03:00
|
|
|
let keyType = null;
|
2022-05-10 07:37:05 +03:00
|
|
|
|
|
|
|
if (req.query && req.query.key) {
|
2022-05-10 09:44:55 +03:00
|
|
|
keyValue = req.query.key;
|
2022-05-10 11:08:54 +03:00
|
|
|
keyType = 'content';
|
|
|
|
} else if (req.headers && req.headers.authorization) {
|
|
|
|
keyValue = extractAdminAPIKey(extractTokenFromHeader(req.headers.authorization));
|
|
|
|
keyType = 'admin';
|
2022-05-10 07:37:05 +03:00
|
|
|
}
|
|
|
|
|
2022-05-10 11:08:54 +03:00
|
|
|
return {
|
|
|
|
key: keyValue,
|
|
|
|
type: keyType
|
|
|
|
};
|
2022-05-10 07:37:05 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = extractAPIKey;
|