-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
668 lines (645 loc) · 20.6 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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
require('dotenv').config()
const db = require('./db')
const _ = require('./helpers')
const middleware = require('./middleware')
const express = require('express')
const cors = require('cors')
const multer = require('multer')
const uploads = multer({ dest: 'uploads' })
const compression = require('compression')
const tokenizer = new (require('./tokens'))()
const pgp = require('pg-promise')
// Configuration
const app = express()
app.use(compression())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// CORS
// https://httptoolkit.tech/blog/cache-your-cors
// https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs
app.use(cors({
// Browser cache time for preflight responses (Access-Control-Max-Age)
maxAge: 86400, // seconds
// Allow us to manually add to preflights
preflightContinue: true
}))
// Register default handlers
app.use((req, res, next) => {
if (req.method === 'OPTIONS') {
// Add cache-control to preflight responses
res.setHeader('Cache-Control', 'public, max-age=86400');
// Vary: origin set automatically
return void res.end()
}
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
// Null empty strings in JSON body
req.body = _.null_empty_strings(req.body)
}
return void next()
})
// Routes: Docs
app.use(
`${process.env.API_BASE}/openapi.yml`,
express.static('docs/openapi.yml')
)
// Pre-route middleware
app.use((req, res, next) => {
const skip_api_key = [
// OpenAPI OAuth2 password flow
`${process.env.API_BASE}/user/token`,
// Email confirmation link
`${process.env.API_BASE}/user/confirmation`
]
if (skip_api_key.includes(req.path)) {
return next()
}
return middleware.check_api_key(req, res, next)
})
// Routes: Clusters
get(
`${process.env.API_BASE}/clusters`,
req => db.clusters.list(req.query)
)
// Routes: Types
get(
`${process.env.API_BASE}/types`,
() => db.types.list()
)
post(
`${process.env.API_BASE}/types`,
middleware.authenticate(),
middleware.recaptcha,
(req, res) => {
if (req.body.pending === false && (!req.user || !req.user.roles.includes('admin'))) {
return void res.status(403).json(
{error: 'Only admins can approve a type (pending: false)'}
)
}
return db.types.add(req.body)
}
)
get(
`${process.env.API_BASE}/types/counts`,
req => db.types.count(req.query)
)
get(
`${process.env.API_BASE}/types/:id`,
req => db.types.show(req.params.id)
)
// Routes: Locations
get(
`${process.env.API_BASE}/locations`,
async (req, res) => {
const locations = await db.locations.list(req.query)
if (req.query.count === 'true') {
const limit = req.query.limit ? parseInt(req.query.limit) : 1000
let count = locations.length
if (locations.length === limit) {
count = (await db.locations.count(req.query)).count
}
res.set({'x-total-count': count})
}
return locations
}
)
post(
`${process.env.API_BASE}/locations`,
middleware.authenticate(),
middleware.recaptcha,
middleware.test_review('review'),
async req => {
// TODO: Perform within transaction (https://stackoverflow.com/a/43800783)
const user_id = req.user ? req.user.id : null
let photos
if (req.body.review) {
photos = await db.photos.test_unlinked(req.body.review.photo_ids)
}
const location = await db.locations.add({...req.body, user_id: user_id})
if (req.body.review) {
const review = await db.reviews.add(
location.id, {...req.body.review, user_id: user_id}
)
await db.photos.link(req.body.review.photo_ids, review.id)
review.photos = photos
location.reviews = [review]
}
await db.clusters.increment(location)
return location
}
)
get(
`${process.env.API_BASE}/locations/count`,
req => db.locations.count(req.query)
)
get(
`${process.env.API_BASE}/locations/changes`,
middleware.authenticate(),
async (req, res) => {
if (req.query.user_id && (!req.user || req.user.id != parseInt(req.query.user_id))) {
// Cannot filter by other user's foraging range
if (req.query.range === 'true') {
return void res.status(403).json({error: 'Only a user can filter by their own foraging range'})
}
const user = await db.users.show(req.query.user_id)
// Cannot filter by anonymous user
if (!user.name) {
return void res.status(403).json({error: 'User prefers to remain anonymous'})
}
}
return db.changes.list(req.query)
}
)
get(
`${process.env.API_BASE}/locations/:id`,
async req => {
const location = await db.locations.show(req.params.id)
if (req.query.embed) {
const embedded = req.query.embed.split(',')
if (embedded.includes('reviews')) {
location.reviews = await db.reviews.list(req.params.id)
}
if (embedded.includes('import') && location.import_id) {
location.import = await db.imports.show(location.import_id)
delete location.import_id
}
}
return location
}
)
put(
`${process.env.API_BASE}/locations/:id`,
middleware.authenticate(),
middleware.recaptcha,
async req => {
const old = await db.locations.show(req.params.id)
const updated = await db.locations.edit(req.params.id, req.body, req.user)
// Decrement first in case location properties have changed
if (
updated.lat != old.lat || updated.lng != old.lng ||
updated.muni != old.muni || !_.set_equal(updated.type_ids, old.type_ids)
) {
await db.clusters.decrement(old)
await db.clusters.increment(updated)
}
return updated
}
)
// Routes: Location tiles
get(
`${process.env.API_BASE}/tiles/:z/:x/:y.pbf`,
async (req, res) => {
const mvt = await db.tiles.show(req.params)
return void res.status(200).end(mvt)
}
)
// Routes: Reviews
get(
`${process.env.API_BASE}/locations/:id/reviews`,
req => db.reviews.list(req.params.id)
)
post(
`${process.env.API_BASE}/locations/:id/reviews`,
middleware.authenticate(),
middleware.recaptcha,
middleware.test_review(),
async req => {
// TODO: Perform within transaction (https://stackoverflow.com/a/43800783)
const photos = await db.photos.test_unlinked(req.body.photo_ids)
const review = await db.reviews.add(
req.params.id, {...req.body, user_id: req.user ? req.user.id : null}
)
await db.photos.link(req.body.photo_ids, review.id)
review.photos = photos
return review
}
)
get(
`${process.env.API_BASE}/reviews/:id`,
async (req) => {
const review = await db.reviews.show(req.params.id)
review.photos = await db.photos.list(req.params.id)
return review
}
)
put(
`${process.env.API_BASE}/reviews/:id`,
middleware.authenticate('user'),
middleware.test_review(),
async (req, res) => {
const original = await db.reviews.show(req.params.id)
// Restrict to linked user
if (req.user.id != original.user_id) {
return void res.status(403).json({error: 'Insufficient permissions'})
}
// TODO: Perform within transaction (https://stackoverflow.com/a/43800783)
const photos = await db.photos.test_unlinked(req.body.photo_ids, original.id)
const review = await db.reviews.edit(req.params.id, req.body)
await db.photos.link(req.body.photo_ids, review.id)
review.photos = photos
return review
}
)
drop(
`${process.env.API_BASE}/reviews/:id`,
middleware.authenticate('user'),
async (req, res) => {
const original = await db.reviews.show(req.params.id)
// Restrict to linked user
if (req.user.id != original.user_id) {
return void res.status(403).json({error: 'Insufficient permissions'})
}
await db.reviews.delete(req.params.id)
await db.changes.delete_review(req.params.id)
return void res.status(204).send()
}
)
// Routes: Photos
post(
`${process.env.API_BASE}/photos`,
middleware.authenticate(),
// middleware.recaptcha,
uploads.single('file'),
async req => {
const urls = await _.resize_and_upload_photo(req.file.path)
return db.photos.add(urls, req.user ? req.user.id : null)
}
)
// Routes: Users (public)
get(
`${process.env.API_BASE}/users/:id`,
async (req, res) => {
const user = await db.users.show_public(req.params.id)
if (!user.name) {
return void res.status(403).json({error: 'User prefers to remain anonymous'})
}
return user
}
)
// Routes: Users (private)
post(
`${process.env.API_BASE}/user`,
middleware.recaptcha,
async (req) => {
// Email uniqueness is case-insensitive
req.body.email = req.body.email.toLowerCase()
const exists = await db.oneOrNone(
'SELECT email, name FROM users WHERE email=${email}', {email: req.body.email}
)
if (exists) {
await _.send_email_confirmation_exists(exists)
} else {
const user = await db.users.add(req)
// Send confirmation email
const token = tokenizer.sign_email_confirmation(user)
await _.send_email_confirmation(user, token)
}
// Phrase: devise.confirmations.send_instructions
return {message: 'You will receive an email with instructions for how to confirm your email address in a few minutes'}
}
)
get(
`${process.env.API_BASE}/user`,
middleware.authenticate('user'),
(req) => db.users.show(req.user.id)
)
put(
`${process.env.API_BASE}/user`,
middleware.authenticate('user'),
async (req, res) => {
const user = await db.one(
'SELECT id, name, encrypted_password, email FROM users WHERE id = ${id}',
{id: req.user.id}
)
if (req.body.email != user.email || req.body.password) {
// Require password confirmation
if (!req.body.password_confirmation) {
return void res.status(401).json(
{error: 'Current password is required to change email or password'}
)
}
const confirmed = await _.compare_password(
req.body.password_confirmation, user.encrypted_password
)
if (!confirmed) {
return void res.status(401).json({error: 'Wrong password'})
}
if (req.body.email != user.email) {
// Save new email as unconfirmed
// When email clicked: set unconfirmed_email to email
await db.none(
'UPDATE users SET unconfirmed_email = ${email} WHERE id = ${id}',
{id: req.user.id, email: req.body.email}
)
// Check that email is not already taken
const other = await db.oneOrNone('SELECT email, name FROM users WHERE email = ${email}', {email: req.body.email})
if (other) {
await _.send_email_confirmation_exists(other)
} else {
// Send confirmation email
const token = tokenizer.sign_email_confirmation(user, req.body.email)
await _.send_email_confirmation({email: req.body.email}, token)
}
}
if (req.body.password === req.body.password_confirmation) {
// Ignore password input
req.body.password = null
} else {
// Revoke all existing tokens except the one in use
await db.none(
'DELETE FROM refresh_tokens WHERE user_id = ${id} AND jti != ${jti}',
{id: req.user.id, jti: req.user.jti}
)
}
}
return db.users.edit(req)
}
)
post(
`${process.env.API_BASE}/user/token`,
uploads.none(),
async (req, res) => {
let user
try {
user = await db.one(
'SELECT id, roles, encrypted_password, confirmed_at FROM users WHERE email = ${email}',
{email: req.body.username.toLowerCase()}
)
} catch (err) {
// Email not found
// Phrase: devise.failure.invalid
return void res.status(401).json({error: 'Invalid email or password'})
}
if (!user.confirmed_at) {
// Phrase: devise.failure.unconfirmed
throw Error('You have to confirm your email address before continuing')
}
if (!await _.compare_password(req.body.password, user.encrypted_password)) {
// Wrong password
// Phrase: devise.failure.invalid
return void res.status(401).json({error: 'Invalid email or password'})
}
const [tokens, jti, exp] = tokenizer.sign_and_wrap_access(user)
// Store refresh token id in database
await db.none(
'INSERT INTO refresh_tokens (user_id, jti, exp) VALUES (${user_id}, ${jti}, ${exp})',
{user_id: user.id, jti: jti, exp: exp}
)
return void res.status(200).set({'cache-control': 'no-store'}).json(tokens)
}
)
post(
`${process.env.API_BASE}/user/token/refresh`,
uploads.none(),
async (req, res) => {
// req.body.grant_type=refresh_token
const token = req.body.refresh_token
const data = tokenizer.verify_refresh(token, res)
if (!data) {
return
}
// Fetch user roles
const user = await db.oneOrNone(
'SELECT id, roles FROM users WHERE id = ${id}', {id: data.id}
)
if (!user) {
return void res.status(401).json({error: 'Invalid refresh token'})
}
// Generate new refresh token with same expiration
const [tokens, jti, exp] = tokenizer.sign_and_wrap_access(user, data.exp)
// Replace with new refresh token if old refresh token exists
const refreshed = await db.oneOrNone(
'UPDATE refresh_tokens SET jti = ${new} WHERE user_id = ${user_id} AND jti = ${old} RETURNING jti',
{user_id: user.id, old: data.jti, new: jti}
)
if (!refreshed) {
return void res.status(401).json({error: 'Invalid refresh token'})
}
return void res.status(200).set({'cache-control': 'no-store'}).json(tokens)
}
)
drop(
`${process.env.API_BASE}/user`,
middleware.authenticate('user'),
async (req, res) => {
// // Check password
// const user = await db.one(
// 'SELECT encrypted_password FROM users WHERE id = ${id}',
// {id: req.user.id}
// )
// if (!await _.compare_password(req.body.password, user.encrypted_password)) {
// return void res.status(401).json({error: 'Wrong password'})
// }
await db.users.delete(req.user.id)
return void res.status(204).send()
}
)
// Routes: User email
get(
`${process.env.API_BASE}/user/confirmation`,
async (req, res) => {
const token = req.query.token
const data = tokenizer.verify_email_confirmation(token, res)
if (!data) {
return
}
const user = await db.oneOrNone(
'SELECT id, email, confirmed_at, unconfirmed_email FROM users WHERE id=${id}',
{id: data.id}
)
if (!user) {
// Phrase: devise.errors.messages.not_found
throw Error('Email not found')
}
if (user.unconfirmed_email) {
if (user.unconfirmed_email === data.email) {
// Confirm unconfirmed email
await db.none(
'UPDATE users SET email = unconfirmed_email, unconfirmed_email = NULL WHERE id = ${id}',
{id: user.id}
)
return {message: 'Your email address has been successfully confirmed'}
} else {
throw Error('Email-confirmation token is not for the newest email on your account')
}
}
if (user.confirmed_at) {
// Phrase: devise.errors.messages.already_confirmed
throw Error('Email was already confirmed, please try signing in')
}
await db.users.confirm(user.id)
// Phrase: devise.confirmation.confirmed
return {message: 'Your email address has been successfully confirmed'}
}
)
post(
`${process.env.API_BASE}/user/confirmation`,
async (req, res) => {
const token = req.body.token
const data = tokenizer.verify_email_confirmation(token, res)
if (!data) {
return
}
const user = await db.oneOrNone(
'SELECT id, email, confirmed_at, unconfirmed_email FROM users WHERE id=${id}',
{id: data.id}
)
if (!user) {
// Phrase: devise.errors.messages.not_found
throw Error('Email not found')
}
if (user.unconfirmed_email) {
if (user.unconfirmed_email === data.email) {
// Confirm unconfirmed email
await db.none(
'UPDATE users SET email = unconfirmed_email, unconfirmed_email = NULL WHERE id = ${id}',
{id: user.id}
)
return {email: user.unconfirmed_email}
} else {
throw Error('Email-confirmation token does not match the newest email on your account')
}
}
if (user.confirmed_at) {
// Phrase: devise.errors.messages.already_confirmed
throw Error('Email was already confirmed, please try signing in')
}
await db.users.confirm(user.id)
// Phrase: devise.confirmation.confirmed
return {email: user.email}
}
)
post(
`${process.env.API_BASE}/user/confirmation/retry`,
middleware.recaptcha,
async (req) => {
const email = req.body.email.toLowerCase()
const user = await db.oneOrNone(
'SELECT id, email, unconfirmed_email, confirmed_at FROM users WHERE email = ${email} OR unconfirmed_email = ${email}',
{email: email}
)
if (!user) {
await _.send_email_confirmation_not_found({email: req.body.email})
} else if (user.email === email && user.confirmed_at) {
await _.send_email_confirmation_confirmed(user)
} else {
const token = tokenizer.sign_email_confirmation(
user, user.unconfirmed_email ? user.unconfirmed_email : null
)
await _.send_email_confirmation({email: email}, token)
}
// Phrase: devise.confirmation.send_instructions
return {message: 'You will receive an email with instructions for how to confirm your email address in a few minutes'}
}
)
// Routes: User password
put(
`${process.env.API_BASE}/user/password`,
async (req, res) => {
const token = req.body.token
let data = tokenizer.decode_password_reset(token, res)
if (!data) {
return
}
const user = await db.oneOrNone(
'SELECT id, email, encrypted_password FROM users WHERE id=${id}', {id: data.id}
)
if (!user) {
throw Error('Account not found')
}
data = tokenizer.verify_password_reset(token, user.encrypted_password, res)
if (!data) {
return
}
await db.users.set_password(user.id, req.body.password)
// Phrase: devise.passwords.updated_not_active
// return {message: 'Your password has been changed successfully'}
return {email: user.email}
}
)
post(
`${process.env.API_BASE}/user/password/reset`,
middleware.recaptcha,
async (req) => {
const email = req.body.email.toLowerCase()
const user = await db.oneOrNone(
'SELECT id, email, name, confirmed_at, encrypted_password FROM users WHERE email=${email}',
{email: email}
)
if (user) {
const token = tokenizer.sign_password_reset(user, user.encrypted_password)
await _.send_password_reset(user, token)
} else {
await _.send_password_reset_not_found({email: req.body.email})
}
// Phrase: devise.passwords.send_instructions
return {message: 'You will receive an email with instructions on how to reset your password in a few minutes'}
}
)
// Routes: Reports
post(
`${process.env.API_BASE}/reports`,
middleware.authenticate(),
middleware.recaptcha,
async (req) => {
if (req.user) {
req.body.reporter_id = req.user.id
if (!req.body.email || !req.body.name) {
const user = await db.one(
'SELECT name, email FROM users WHERE id=${id}', {id: req.user.id}
)
req.body.email = req.body.email || user.email
req.body.name = req.body.name || user.name
}
}
if (!req.body.email) {
throw Error('An email is required')
}
if (req.body.problem_code === 5 && !req.body.comment) {
throw Error('comment is required when problem_code = 5')
}
return db.reports.add(req.body)
}
)
// Routes: Imports
get(`${process.env.API_BASE}/imports`, () => db.imports.list())
get(`${process.env.API_BASE}/imports/:id`, req => db.imports.show(req.params.id))
// Generic handlers
function register_route(method, url, handlers) {
const middleware = handlers.slice(0, -1)
const handler = handlers[handlers.length - 1]
app[method](url, ...middleware, async (req, res, next) => {
try {
const data = await handler(req, res, next)
if (data) {
return void res.status(200).json(data)
}
} catch (err) {
console.log('[caught]', err || err.message)
if (method === 'get' && err.code === pgp.errors.queryResultErrorCode.noData) {
return void res.status(404).json({
error: err.message || err
})
}
return void res.status(400).json({
error: err.message || err
})
}
})
}
function get(url, ...handlers) {
register_route('get', url, handlers)
}
function post(url, ...handlers) {
register_route('post', url, handlers)
}
function put(url, ...handlers) {
register_route('put', url, handlers)
}
// delete is a reserved word
function drop(url, ...handlers) {
register_route('delete', url, handlers)
}
// Start server
app.listen(process.env.PORT, () => {
console.log(`Ready for requests on http://localhost:${process.env.PORT}`)
})