1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const yaml = require("js-yaml");
|
4 | const fs = require("fs");
|
5 | const swagger_tools_1 = require("swagger-tools");
|
6 | const JwtTokenClient_1 = require("../jwt/JwtTokenClient");
|
7 | const UnauthorizedError_1 = require("../web/errors/UnauthorizedError");
|
8 | const ApiKeyVerification_1 = require("./ApiKeyVerification");
|
9 | class SwaggerMetadataMiddleware {
|
10 | |
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | constructor(config) {
|
21 | this.swaggerFile = config.swagger || this.loadSwagger(config);
|
22 | this.logger = config.logger;
|
23 | this.apiKey = config.apiKey;
|
24 | }
|
25 | loadSwagger(config) {
|
26 | if (!config.swaggerFilePath) {
|
27 | throw new Error('Need to specify the swaggerFilePath in the config');
|
28 | }
|
29 | try {
|
30 | const swaggerString = fs.readFileSync(config.swaggerFilePath, 'utf8');
|
31 | this.swagger = yaml.safeLoad(swaggerString);
|
32 | }
|
33 | catch (e) {
|
34 | const e1 = new Error(`There was an error reading swagger yaml file: ${e.message}`);
|
35 |
|
36 | throw e1;
|
37 | }
|
38 | }
|
39 | jwtHandler(req, authOrSecDef, scopesOrApiKey, callback) {
|
40 | const jwt = new JwtTokenClient_1.JwtTokenClient();
|
41 | try {
|
42 | const token = jwt.verify(scopesOrApiKey);
|
43 | if (token !== null) {
|
44 | req.decodedToken = token;
|
45 | return callback();
|
46 | }
|
47 | }
|
48 | catch (e) {
|
49 | return callback(new UnauthorizedError_1.UnauthorizedError('Failed to authenticate using bearer token'));
|
50 | }
|
51 | return callback(new UnauthorizedError_1.UnauthorizedError('Failed to authenticate using bearer token'));
|
52 | }
|
53 | register(expressApp) {
|
54 | const apiKey = this.apiKey;
|
55 | return new Promise((resolve) => {
|
56 | swagger_tools_1.initializeMiddleware(this.swagger, (swaggerTools) => {
|
57 |
|
58 | const swaggerMetadataFunc = swaggerTools.swaggerMetadata();
|
59 | const swaggerValidatorFunc = swaggerTools.swaggerValidator();
|
60 | const sm = { jwt: this.jwtHandler, apiKeyHeader: ApiKeyVerification_1.ApiKeyVerification.verifyApiKey(apiKey) };
|
61 | const swaggerSecurityFunc = swaggerTools.swaggerSecurity(sm);
|
62 | expressApp.use((req, res, next) => {
|
63 | swaggerMetadataFunc(req, res, (err) => {
|
64 | if (err) {
|
65 | return next(err);
|
66 | }
|
67 | return next();
|
68 | });
|
69 | });
|
70 | expressApp.use(swaggerSecurityFunc);
|
71 | expressApp.use(swaggerValidatorFunc);
|
72 |
|
73 | resolve();
|
74 | });
|
75 | });
|
76 | }
|
77 | }
|
78 | exports.default = SwaggerMetadataMiddleware;
|
79 |
|
\ | No newline at end of file |