Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | 1x 1x 1x 4x 7x 7x 2x 5x 5x 2x 3x 2x 2x 2x 1x 1x 1x 1x 1x 1x | 'use strict';
const { Agent, ClientRequest, ServerResponse } = require('http');
const superagent = require('superagent');
const keepAliveAgent = new Agent({ keepAlive: true });
/**
* @typedef {Object} FullTokenInfo
* @property {string} token The access token.
* @property {Object} info
* @property {string} info.userId
* @property {string} info.account
* @property {Object} info.roles <string, boolean> pairs.
* @property {string} info.name
* @property {string} info.clientId
* @property {string[]} info.scopes
*/
/**
* Generate the Express authentication middleware.
*
* @param {string} authUri The authentication endpoint. For example
* `http://localhost:1080/auth/api/v1/auth/tokeninfo`.
* @returns {function} The Express middleware.
*/
function authMiddleware(authUri) {
/**
* @param {ClientRequest} req
* @param {ServerResponse} res
* @param {function} next
*/
return function (req, res, next) {
let token = req.get('Authorization');
if (!token) {
return void res.status(400).json({ code: 'err_param', message: 'empty Authorization' });
}
token = token.trim();
if (token.length < 8 || token.substr(0, 7).toLowerCase() !== 'bearer ') {
return void res.status(400).json({ code: 'err_param', message: 'not bearer token' });
}
superagent
.agent(keepAliveAgent)
.auth(token.substr(7), { type: 'bearer' })
.get(authUri)
.ok((res) => !!res)
.then((authRes) => {
Iif (!authRes) {
return void res.status(500).json({
code: 'err_unknown',
message: `unexpected error`,
});
} else if (authRes.statusCode === 401) {
return void res.status(401).json({ code: 'err_auth' });
} else Iif (authRes.statusCode !== 200) {
return void res.status(503).json({
code: 'err_int_msg',
message: `auth error with status code: ${res.statusCode}`,
});
}
req[module.exports.TokenInfoKey] = {
token: token.substr(7),
info: authRes.body.data,
};
next();
})
.catch((err) => {
return void res.status(503).json({
code: 'err_rsc',
message: `${err}`,
});
});
};
}
module.exports = {
TokenInfoKey: 'FullTokenInfo',
authMiddleware,
};
|