/
server.js
95 lines (79 loc) · 1.95 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
95
'use strict';
const Hapi = require('hapi');
const mongoose = require('mongoose');
const hapiAuthJWT = require('hapi-auth-jwt2');
const jwksRsa = require('jwks-rsa');
const DogController = require('./src/controllers/dog');
const MongoDBUrl = 'mongodb://localhost:27017/dogapi';
const server = new Hapi.Server({
port: 3000,
host: 'localhost'
});
const validateUser = (decoded, request, callback) => {
// This is a simple check that the `sub` claim
// exists in the access token. Modify it to suit
// the needs of your application
console.log("Decoded", decoded);
if (decoded && decoded.sub) {
return callback(null, true, {});
}
return callback(null, false, {});
}
const registerRoutes = () => {
server.route({
method: 'GET',
path: '/dogs',
options: {
handler: DogController.list
}
});
server.route({
method: 'GET',
path: '/dogs/{id}',
options: {
handler: DogController.get
}
});
server.route({
method: 'POST',
path: '/dogs',
handler: DogController.create
});
server.route({
method: 'PUT',
path: '/dogs/{id}',
handler: DogController.update
});
server.route({
method: 'DELETE',
path: '/dogs/{id}',
handler: DogController.remove
});
}
const init = async() => {
await server.register(hapiAuthJWT);
// see: http://hapijs.com/api#serverauthschemename-scheme
server.auth.strategy('jwt', 'jwt', {
key: jwksRsa.hapiJwt2Key({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'https://kabiyesi.auth0.com/.well-known/jwks.json'
}),
verifyOptions: {
audience: 'https://mydogapi.com',
issuer: "https://kabiyesi.auth0.com/",
algorithms: ['RS256']
},
validate: validateUser
});
server.auth.default('jwt');
registerRoutes();
await server.start();
return server;
};
init().then(server => {
console.log('Server running at:', server.info.uri);
}).catch(err => {
console.log(err);
});