UNPKG

@foundry-ai/api-auth

Version:
91 lines 3.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const RequestPromise = require("request-promise"); const lodash_1 = require("lodash"); const api_errors_1 = require("@foundry-ai/api-errors"); const ClientConfigFactory_1 = require("./util/ClientConfigFactory"); function default_1(config) { const authConfig = ClientConfigFactory_1.Factory(config); return function (req, res, next) { Promise.resolve(tokenFromReq(req)) .then(token => { if (!token) throw new api_errors_1.AuthenticationError('Missing authentication token'); const requestOptions = lodash_1.assignIn(authConfig.request, { method: 'GET', uri: authConfig.authEndpoint, qs: { access_token: token } }); RequestPromise(requestOptions) .then(data => { lodash_1.set(req, 'auth', data); next(); }) .catch(err => { if (err.error && err.error.type && err.error.status && err.error.message) next(toResJson(err.error)); else { switch (err.statusCode) { case 400: next(new api_errors_1.BadRequestError()); break; case 401: next(new api_errors_1.AuthenticationError()); break; case 403: next(new api_errors_1.ForbiddenError()); break; case 429: next(new api_errors_1.RateLimitError()); break; default: next(err); } } }); }) .catch(err => next(err)); }; } exports.default = default_1; function tokenFromReq(req) { let token = ''; if (req.headers && req.headers.authorization) { const authorization = req.headers.authorization; const parts = authorization.split(' '); if (parts.length == 2) { const [scheme, credentials] = parts; if (/^Bearer$/i.test(scheme)) { token = credentials; } } else { throw new api_errors_1.BadRequestError('Invalid authentication scheme'); } } if (req.body && req.body.access_token) { if (token) { throw new api_errors_1.BadRequestError('Multiple access tokens attached to request'); } token = req.body.access_token; } if (req.query && req.query.access_token) { if (token) { throw new api_errors_1.BadRequestError('Multiple access tokens attached to request'); } token = req.query.access_token; } return token; } exports.tokenFromReq = tokenFromReq; function toResJson(err) { return { type: err.type, status: err.status, message: err.message }; } exports.toResJson = toResJson; //# sourceMappingURL=index.js.map