forked from CityOfPhiladelphia/eng-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
94 lines (82 loc) · 2.54 KB
/
server.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
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const jwt = require('jsonwebtoken');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// require routes
const admin = require('./routes/admin')
const prisoner = require('./routes/prisoner')
const warden = require('./routes/warden')
app.get('/', function(req, res){
res.json({"live" : "this is live"});
});
app.use('/api/admin', validateAdmin, admin)
app.use('/api/warden', validateWarden, warden)
app.use('/api/prisoner', prisoner)
// export app for jest testing
module.exports = app;
function validateAdmin(req, res, next) {
// default algorithm is SH256 https://github.com/auth0/node-jsonwebtoken#usage
let token = extractToken(req) || null;
if (token) {
let parsedToken = tokenParser(token);
if (parsedToken && parsedToken.role === 'Administrator') {
return next()
}
else {
console.log('ERROR: Not an Admin');
res.sendStatus(404);
}
}
else {
console.log('ERROR: No Token Provided');
res.sendStatus(404);
}
}
function validateWarden(req, res, next) {
// default algorithm is SH256 https://github.com/auth0/node-jsonwebtoken#usage
let token = extractToken(req) || null;
if (token) {
let parsedToken = tokenParser(token);
if (parsedToken && parsedToken.role === 'warden') {
// adding token location to req in order to only parse token once
req.location = parsedToken.location
return next()
}
else {
console.log('ERROR: Not a Warden');
res.sendStatus(404);
}
}
else {
console.log('ERROR: No Token Provided');
res.sendStatus(404);
}
}
function extractToken (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
function tokenParser (token) {
try {
var decoded = jwt.decode(token, 'secret');
if(decoded && decoded.role) {
return decoded;
}
else {
return null
}
} catch (err) {
console.log(err)
console.log('ERROR: Could not connect to the protected route');
return null
}
}
app.listen(3000, function(){ console.log('Live at: 3000');});