-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (61 loc) · 1.98 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
'use strict';
// Node modules
const Hapi = require('hapi');
const hapiAuthJwt2 = require('hapi-auth-jwt2');
const JWT = require('jsonwebtoken'); // used to sign our content
const mongoose = require('mongoose');
const Routes = require('./controllers/routes.js');
const MongoDBUrl = process.env.MONGO_DB_URL;
const server = new Hapi.Server({ port: process.env.PORT || 8080 });
const secret = process.env.JWT_SECRET;
// A dummy person to get the JWT token.
const people = {
1: {
id: 1,
name: 'Tony Valid User',
}
};
const validate = async function (decoded, request, h) {
// check to see if the person is valid.
if (!people[decoded.id]) {
return { isValid: false };
}
else {
return { isValid: true };
}
};
if (secret && process.env.NODE_ENV && process.env.NODE_ENV === 'dev') {
// one can use the token as the 'authorization' header in requests
const token = JWT.sign(people[1], secret); // synchronous
console.log(token);
}
const startServers = async () => {
try {
if (secret) {
await server.register(hapiAuthJwt2);
server.auth.strategy('jwt', 'jwt',
{ key: secret,
validate,
verifyOptions: { ignoreExpiration: true }
});
server.auth.default('jwt');
}
Routes(server);
await server.start();
console.log('Server running at:', server.info.uri);
mongoose.connect(MongoDBUrl, { useNewUrlParser: true, useCreateIndex: true })
.then(() => { console.log('Connected to MongoDB server') },
error => {
console.error(error);
server.stop({ timeout: 10000 }).then(function (err) {
console.log('hapi server stopped')
process.exit((err) ? 1 : 0)
})
});
}
catch (error) {
throw error;
}
}
startServers();
module.exports = server;