-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
79 lines (69 loc) · 1.98 KB
/
index.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
/*!
* koa-ip-filter <https://github.com/tunnckoCore/koa-ip-filter>
*
* Copyright (c) 2015-2016 Charlike Mike Reagent, contributors.
* Released under the MIT license.
*/
'use strict'
var ipFilter = require('ip-filter')
/**
* > Filtering incoming request with glob patterns
* array, regexp, string or matcher function
*
* **Example**
*
* ```js
* 'use strict'
*
* var koa = require('koa')
* var ipFilter = require('koa-ip-filter')
* var helloWorld = require('koa-hello-world')
*
* var app = koa()
*
* app
* .use(ipFilter({
* forbidden: '403: Get out of here!',
* filter: ['127.??.6*.12', '!1.2.*.4']
* }))
* .use(helloWorld())
*
* app.listen(1234)
* console.log('koa server start listening on http://localhost:1234')
*
* // if your IP is `127.43.65.12` you will see `Hello World`
* // otherwise you will see `403: Get out of here!`
* ```
*
* @name koaIpFilter
* @param {Object} `options`
* @option {Function} [options] `id` custom identifier, defaults to `this.ip`
* @option {Boolean} [options] `strict` to throw when not valid IPv4/IPv6? default `true`
* @option {Array|String|RegExp|Function} [options] `filter` black/white list filter
* @option {String|Function} [options] `forbidden` custom message when `403 Forbidden` response
* @return {GeneratorFunction}
* @api public
*/
module.exports = function koaIpFilter (options) {
options = typeof options === 'object' ? options : {}
return function * (next) {
var id = typeof options.id === 'function'
? options.id.call(this, this)
: this.ip
if (!id || !options.filter) {
return yield * next
}
var forbidden = options.forbidden || '403 Forbidden'
var identifier = ipFilter(id, options.filter, options)
if (identifier === null) {
this.status = 403
this.body = typeof forbidden === 'function'
? forbidden.call(this, this)
: forbidden
return
}
this.filter = ipFilter
this.identifier = identifier
return yield * next
}
}