-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (49 loc) · 1.43 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
//Express library
const express = require('express')
//Individual route files
const authRoutes = require('./routes/authenticate')
const candidateRoutes = require('./routes/candidate')
const partyRoutes = require('./routes/party')
const electionRoutes = require('./routes/election')
const districtRoutes = require('./routes/district')
const userRoutes = require('./routes/user')
//Utility for handling JWT
const jwtUtil = require('./util/jwtutil')
//Initialize
const app = express()
//Default port
const port = process.env.PORT || 4200
//Add routes
authRoutes(app)
partyRoutes(app)
candidateRoutes(app)
electionRoutes(app)
districtRoutes(app)
userRoutes(app)
//Ensure each request is authenticated
app.use(async (req, res, next) => {
//Could see use for a whitelist here, but for now only allow unauthenticated reqests to authenticate
if(req.path.indexOf('/authenticate') !== -1)
{
return req.next();
}
try{
//validate the jwt
const token = req.headers('jwt');
const isValid = await jwtUtil.verify(token, SECRET)
if(isValid)
{
//This is good, we can move on
return req.next()
}
res.status('401').send('Unauthorized')
}catch(e){
next(e)
}
})
//Default error handler. All hard errors should come through here
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).send('Server error')
})
app.listen(port)