koa-userinfo
Version:
openid style userinfo as middleware, for koa
65 lines (51 loc) • 1.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "requestUserinfo", {
enumerable: true,
get: function () {
return _requestUserinfo.default;
}
});
exports.default = void 0;
var _requestUserinfo = _interopRequireDefault(require("./request-userinfo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = require('debug')('koa-userinfo');
const getAccessTokenFromHeader = ctx => {
const auth = ctx.headers.authorization;
if (!auth) {
debug('No "Authorization" header found, headers:', ctx.headers);
return undefined;
}
const match = auth.match(/^Bearer (.+)$/);
if (!match) {
debug('Authorization header does not match "Bearer" token format');
return undefined;
}
return match[1];
};
var _default = options => {
if (!options.site) {
throw new Error('option "site" missing');
}
return async (ctx, next) => {
const token = getAccessTokenFromHeader(ctx);
if (!token) {
if (options.allowMissingOrInvalidToken) {
return await next();
} else {
return ctx.throw(401, 'Unable to use or extract Bearer token');
}
} else {
try {
ctx.userinfo = await (0, _requestUserinfo.default)(options.site, token);
debug('userinfo', ctx.userinfo);
} catch (err) {
return ctx.throw(401, err);
}
await next();
}
};
};
exports.default = _default;