-
Notifications
You must be signed in to change notification settings - Fork 8
/
plugin-allows-custom-ip-detection.js
77 lines (64 loc) · 1.67 KB
/
plugin-allows-custom-ip-detection.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
'use strict'
const Test = require('ava')
const Hapi = require('@hapi/hapi')
Test('uses getIp to detect the IP address', async (t) => {
const server = new Hapi.Server()
await server.register({
plugin: require('../lib'),
options: {
max: 10,
getIp: async (request) => {
return request.headers['rate-limitor-ip']
},
namespace: `getip-${Date.now()}`
}
})
await server.initialize()
server.route({
method: 'GET',
path: '/getIp',
handler: request => request.headers['rate-limitor-ip']
})
const request = {
url: '/getIp',
method: 'GET',
headers: {
'rate-limitor-ip': '1.2.3.4'
}
}
const response = await server.inject(request)
t.is(response.statusCode, 200)
t.is(response.result, '1.2.3.4')
t.is(response.headers['x-rate-limit-limit'], 10)
t.is(response.headers['x-rate-limit-remaining'], 9)
t.truthy(response.headers['x-rate-limit-reset'])
})
Test('falls back to request IP', async (t) => {
const server = new Hapi.Server()
await server.register({
plugin: require('../lib'),
options: {
max: 10,
namespace: `getip-${Date.now()}`
}
})
await server.initialize()
server.route({
method: 'GET',
path: '/getIp',
handler: request => request.headers['x-forwarded-for']
})
const request = {
url: '/getIp',
method: 'GET',
headers: {
'x-forwarded-for': '4.4.4.4'
}
}
const response = await server.inject(request)
t.is(response.statusCode, 200)
t.is(response.result, '4.4.4.4')
t.is(response.headers['x-rate-limit-limit'], 10)
t.is(response.headers['x-rate-limit-remaining'], 9)
t.truthy(response.headers['x-rate-limit-reset'])
})