post-get-service
Version:
simple way to create node http in memory server
57 lines (46 loc) • 1.4 kB
JavaScript
// @ts-check
const authorization_map = {
headers: 'headerKey',
query: 'queryKey',
bodyKey: 'bodyKey',
};
const authorization_defaults = {
bodyKey: 'access_token',
queryKey: 'access_token',
headerKey: 'Bearer',
};
function extract_token(request, type, indicator) {
if (type === 'headers') {
const auth = request.headers && request.headers.authorization;
if (typeof auth === 'string' && auth.startsWith(`${indicator} `)) {
return auth.slice(indicator.length + 1);
}
return undefined;
}
if (type === 'query') {
return request.query ? request.query[indicator] : undefined;
}
return request.body ? request.body[indicator] : undefined;
}
/**
*
* @param {any} initial_app
* @param {object} param1
* @returns {void}
*/
function set_authorization_middleware(initial_app, { authorization }) {
if (!authorization) {
return;
}
// type is optional and default is headers authorization
authorization.type = authorization.type || 'headers';
// indicator is optional and default is headers authorization Bearer
const indicator = authorization.indicator || authorization_defaults[authorization_map[authorization.type]];
const type = authorization.type;
initial_app.addHook('preHandler', async function (request) {
request.token = extract_token(request, type, indicator);
});
}
module.exports = {
set_authorization_middleware,
};