forked from chamini2/hapi-auth-ip-whitelist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (77 loc) · 1.91 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
const Hapi = require('hapi')
const plugin = require('./lib')
const moduleName = require('./package').name
const server = new Hapi.Server({
host: process.env.HOST || 'localhost',
address: process.env.IP || '0.0.0.0',
port: process.env.PORT || 3000,
routes: {
cors: true
},
debug: {
log: ['error'],
request: ['error']
}
})
// register plugin
server.register([
// Uncomment to get correct IP of client when running behind a proxy, therealyou is entirely optional
/*
{
plugin: require('therealyou')
},
*/
{
plugin
}
])
.then(() => {
// specify auth strategies
server.auth.strategy('localhost', 'ip-whitelist', ['127.0.0.1'])
server.auth.strategy('ip_outside_our_control', 'ip-whitelist', ['8.8.8.8']) // only allow IP that will never visit
})
.then(() => {
const routes = [
{
method: 'GET',
path: '/',
handler(request, h) {
const url = request.server.info.uri
return `Visit ${url}/authenticated to test successfully authenticated request or ${url}/unauthenticated to test unauthenticated request.`
},
options: {
auth: false
}
},
{
method: 'GET',
path: '/authenticated',
handler(request, h) {
return 'Authenticated request!'
},
options: {
auth: 'localhost'
}
},
{
method: 'GET',
path: '/unauthenticated',
handler(request, h) {
return 'This should not happen, should get 401 unauthenticated!'
},
options: {
auth: 'ip_outside_our_control'
}
}
]
// register routes after auth strategies are registered
server.route(routes)
})
.then(async () => {
// Start the server
await server.start()
console.log(`Example server for ${moduleName} running at: ${server.info.uri}`)
})
.catch(err => {
console.error(err)
})