forked from voicenter/fastify-openapi-glue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
148 lines (128 loc) · 4.21 KB
/
index.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
const fp = require("fastify-plugin");
const ip = require('ip');
const jwt = require('jsonwebtoken');
const parser = require("./lib/parser");
function isObject(obj) {
return typeof obj === "object" && obj !== null;
}
function getObject(param) {
let data = param;
if (typeof param === "string") {
try {
data = require(param);
} catch (error) {
throw new Error(`failed to load ${param}`);
}
}
if (typeof data === "function") {
data = data();
}
return data;
}
// fastify uses the built-in AJV instance during serialization, and that
// instance does not know about int32 and int64 so remove those formats
// from the responses
const unknownFormats = { int32: true, int64: true };
function stripResponseFormats(schema) {
for (let item in schema) {
if (isObject(schema[item])) {
if (schema[item].format && unknownFormats[schema[item].format]) {
schema[item].format = undefined;
}
stripResponseFormats(schema[item]);
}
}
}
async function fastifyOpenapiGlue(instance, opts) {
const service = getObject(opts.service);
if (!isObject(service)) {
throw new Error("'service' parameter must refer to an object");
}
const config = await parser().parse(opts.specification);
const routeConf = {};
// AJV misses some validators for int32, int64 etc which ajv-oai adds
const Ajv = require("ajv-oai");
const ajv = new Ajv({
// the fastify defaults
removeAdditional: true,
useDefaults: true,
coerceTypes: true
});
instance.setSchemaCompiler(schema => ajv.compile(schema));
if (config.prefix) {
routeConf.prefix = config.prefix;
}
/**
* @param request {request}
* @param entity {string} name of object or field, used for error handling
* @return {Promise.<void>}
*/
async function checkJWT(request, entity) {
if (!('authorization' in request.headers)) throw new Error(`Missing authorization header for ${entity}`);
const token = request.headers['authorization'].split(' ')[1];
let payload;
// check if the token is expired or broken
try {
payload = jwt.verify(token, global.PUBLIC_KEY, {algorithm: "RS256"});
} catch (err) {
throw new Error(`${err.name} ${err.message} for ${entity}`);
}
const {IpList, Role} = payload;
// check that client IP in token range
if (IpList && IpList.length) {
const ipInAllowedRange = IpList.some(ipRange => ip.cidrSubnet(ipRange).contains(request.req.ip));
if (!ipInAllowedRange) throw new Error('IP address if out of range you permit for') ;
}
request.Roles = Role;
}
async function checkAccess(request, item) {
if (item.schema) {
const schema = item.schema;
// TODO extend rule for more x-auth-type
const xAuthTypes = item.openapiSource['x-AuthType'];
if (xAuthTypes.length && !xAuthTypes.some(el => el === "None")) {
request.xAuthTypes = xAuthTypes;
await checkJWT(request, schema.operationId);
}
// TODO remove after debug
if (schema && schema.body) {
const properties = schema.body.properties;
for (const key in properties) {
if (!properties.hasOwnProperty(key)) continue;
if (properties[key]['x-AuthFieldType']) {
console.log(properties[key], key);
}
}
}
}
}
async function generateRoutes(routesInstance, opts) {
config.routes.forEach(item => {
const response = item.schema.response;
if (response) {
stripResponseFormats(response);
}
if (service[item.operationId]) {
routesInstance.log.debug("service has", item.operationId );
item.handler = async (request, reply) => {
if (global.CHECK_TOKEN) await checkAccess(request, item);
return service[item.operationId](request, reply);
};
} else {
item.handler = async (request, reply) => {
throw new Error(`Operation ${item.operationId} not implemented`);
};
}
routesInstance.route(item);
});
}
instance.register(generateRoutes, routeConf);
}
module.exports = fp(fastifyOpenapiGlue, {
fastify: ">=0.39.0",
name: "fastify-openapi-glue"
});
module.exports.options = {
specification: "examples/petstore/petstore-swagger.v2.json",
service: "examples/petstore/service.js"
};