-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
309 lines (276 loc) · 8.77 KB
/
app.js
File metadata and controls
309 lines (276 loc) · 8.77 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import path from 'path'
import AutoLoad from '@fastify/autoload'
import url, { fileURLToPath } from 'url'
import mariadb from 'fastify-mariadb'
import swagger from '@fastify/swagger'
import swaggerUI from "@fastify/swagger-ui";
import cookie from '@fastify/cookie'
import auth from '@fastify/auth'
import fs from 'fs'
import Ajv2019 from "ajv/dist/2019.js"
import addFormats from 'ajv-formats'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
export let logger = null;
// Pass --options via CLI arguments in command to enable these options.
export const options = {}
export const SchemaCompiler = ({ schema }) => {
const ajv = new Ajv2019()
//const ajv = new Ajv2019({allErrors: true})
addFormats(ajv)
const validate = ajv.compile(schema)
//const validate = new Ajv2019().compile(schema)
return (value) => !validate(value)
? ({ value, error: validate.errors })
: ({ value })
}
export default async function (fastify, opts) {
// Place here your custom code!
logger = fastify.log;
fastify.setValidatorCompiler(SchemaCompiler);
//TODO: This is a hack to get around the fact that fastify-cli does not currently allow setting trustProxy. Without this setting, it is impossible to get the original host when building urls.
fastify.decorateRequest("hostHack", function () {
return `${process.env.FASTIFY_HOST}${(process.env.PORT_DISPLAY === "true" && process.env.FASTIFY_PORT) ? `:${process.env.FASTIFY_PORT}` : ''}`
//return this.host.includes("host.docker.internal") ? "localhost" : this.host
//return this.host.includes("host.docker.internal") ? "testpaleobiodb.colo-prod-aws.arizona.edu" : this.host
})
fastify.register(cookie, {
hook: 'onRequest',
parseOptions: {}
})
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error("error handler")
fastify.log.error(error);
let path = request.path || request.url;
const errorLinks = [];
//Get rid of path parameters
Object.keys(request.params).forEach(key => {
path = path.replace("/" + request.params[key], "");
});
path = `${path.substring(0, path.lastIndexOf('/'))}/help`
errorLinks.push({
href: url.format({
protocol: request.protocol,
host: request.hostHack(),
pathname: path,
}),
rel: "help"
});
if (!error.statusCode) error.statusCode = 500;
error.links = errorLinks;
reply.code(error.statusCode).send({
statusCode: error.statusCode,
//Some razzle here to display unevaluatedProperty or allowedValues or additionalProperty if available
msg: `${error.message}${
error.validation && error.validation[0].params && error.validation[0].params.unevaluatedProperty ?
`: ${error.validation[0].params.unevaluatedProperty}` :
''
}${
error.validation && error.validation[0].params && error.validation[0].params.allowedValues ?
`: ${error.validation[0].params.allowedValues}` :
''
}${
error.validation && error.validation[0].params && error.validation[0].params.additionalProperty ?
`: ${error.validation[0].params.additionalProperty}` :
''
}`,
links: errorLinks
})
})
fastify.decorateReply('navLinks', (req, limit, offset, localCount, totalCount, single) => {
const getHostURL = function() {
return url.format({
protocol: req.protocol,
host: req.hostHack(),
})
}
const navLinks = [
];
const myURL = url.parse(getHostURL() + req.originalUrl, true);
myURL.search = null;
navLinks.push({
href: url.format(myURL),
rel: "self"
});
if (!single) {
const myURL = url.parse(getHostURL() + req.originalUrl, true);
delete myURL.query.offset;
myURL.search = null;
navLinks.push({
href: url.format(myURL),
rel: "first"
});
if (offset != 0 && offset-limit >= 0) {
const myURL = url.parse(getHostURL() + req.originalUrl, true);
myURL.query.offset = offset - limit;
myURL.search = null;
navLinks.push({
href: url.format(myURL),
rel: "previous"
});
}
if (offset + localCount < totalCount) {
const myURL = url.parse(getHostURL() + req.originalUrl, true);
myURL.query.offset = offset + limit;
delete myURL.search;
navLinks.push({
href: url.format(myURL),
rel: "next"
});
}
const mod = totalCount % limit
const lastURL = url.parse(getHostURL() + req.originalUrl, true);
lastURL.query.offset =
mod === 0 ?
totalCount - limit :
totalCount - mod;
if (lastURL.query.offset <= 0) delete lastURL.query.offset;
lastURL.search = null;
navLinks.push({
href: url.format(lastURL),
rel: "last"
});
}
return navLinks;
})
await fastify.register(swagger, {
/*
openapi: {
openapi: '3.0.0',
info: {
title: 'PBDB Upload API',
description: 'API for uploading content to the Paleobiology Database',
version: '0.1.0'
}
}
*/
swagger: {
info: {
title: 'PBDB Upload API',
description: 'API for uploading content to the Paleobiology Database',
version: '0.1.0'
}
}
})
/*
Moving this to the v1.routes to avoid issue mentioned below.
I dunno, maybe that's a better place for it anyway.
const image = fs.readFileSync('images/logo_grey.png', {encoding: 'base64'});
fastify.register(swaggerUI, {
//routePrefix is problematic.
//See https://github.com/fastify/fastify-swagger-ui/issues/180
//and many others.
routePrefix: "/api/v1/help",
logo: {
type: 'image/png',
content: Buffer.from(image, 'base64'),
//href: '/help',
target: '_blank'
},
theme: {
title: "PBDB upload API documentation",
favicon: [{
filename: 'logo_grey.png',
rel: 'icon',
sizes: '16x16',
type: 'image/png',
content: Buffer.from(image, 'base64')
}]
}
});
*/
fastify.register(mariadb, {
promise: true,
//NOTE: for local and dev testing with docker, set HOST to "host.docker.internal" in .env and make sure host.docker.internal is added to docker run in vscode settings
host: process.env.MARIADB_HOST,
user: process.env.MARIADB_USER,
password: process.env.MARIADB_PW,
database: 'pbdb',
connectionLimit: 5,
})
// Decorate request with a 'user' property
fastify.decorateRequest('userID', '')
fastify.decorateRequest('userName', '')
fastify.decorateRequest('authorizerID', '')
//TODO: This was a quick and dirty test. Could use some streamlining.
fastify.decorate('verifyAuth', async (request, reply) => {
fastify.log.trace("verifyAuth")
const sessionID = request.cookies.session_id
fastify.log.trace(sessionID);
if (sessionID) {
let conn;
try {
conn = await fastify.mariadb.getConnection();
const sql = 'SELECT user_id from session_data where session_id = ?';
const rows = await conn.query(sql, [sessionID]);
//fastify.log.trace(rows);
if (rows.length > 0 && rows[0].user_id) {
let conn2;
try {
conn2 = await fastify.mariadb.getConnection();
const sql = 'SELECT admin, role, person_no, real_name, authorizer_no from pbdb_wing.users where id = ?';
const rows2 = await conn.query(sql, rows[0].user_id);
//fastify.log.trace(rows2);
if (rows2.length > 0 && rows2[0].role) {
fastify.log.trace(rows2[0].person_no)
request.userID = rows2[0].person_no;
request.userName = rows2[0].real_name;
request.authorizerID = rows2[0].authorizer_no;
if (
'enterer' === rows2[0].role ||
'authorizer' === rows2[0].role ||(
'student' === rows2[0].role && (
"GET" === request.method || (
['POST', 'PUT'].includes(request.method) &&
['reference', 'collection', 'occurrence', 'specimen'].includes(request.url.match(/\/api\/v.\/([a-z]*)/)[1])
)
)
)
) {
return
} else {
const err = new Error('not authorized');
err.statusCode = 403;
throw err
}
} else {
const err = new Error('could not access users');
err.statusCode = 500;
throw err
}
} finally {
if (conn2) conn2.release();
}
} else {
const err = new Error('session not found');
err.statusCode = 400;
throw err
}
} finally {
if (conn) conn.release();
}
} else {
fastify.log.trace("not authenticated")
const err = new Error('not authenticated');
err.statusCode = 401;
throw err
}
})
.register(auth)
// Careful with the following lines
// This loads all plugins defined in plugins
// those should be support plugins that are reused
// through your application
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
options: Object.assign({}, opts)
})
// This loads all plugins defined in routes
// define your routes in one of these
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'routes'),
//options: Object.assign({}, opts),
options: { prefix: '/pbdbupload' },
ignorePattern: /^.*(model|schema)\.js$/,
})
}