1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function failure(settings = null)
|
17 | {
|
18 | if (settings)
|
19 | {
|
20 | let blocker = require('block-failed');
|
21 |
|
22 |
|
23 | const blockAttemptMs = settings.blockAttemptMs || 60 * 1000;
|
24 | const blockAttemptCount = settings.blockAttemptCount || 5;
|
25 | const blockDurationMs = settings.blockDurationMs || 5 * 60 * 1000;
|
26 |
|
27 |
|
28 | const block = blocker(blockDurationMs, blockAttemptMs, blockAttemptCount - 1);
|
29 |
|
30 | return function (req, res, next)
|
31 | {
|
32 | let attempted = false;
|
33 |
|
34 | block(req.clientIp, (on_failure) =>
|
35 | {
|
36 | attempted = true;
|
37 | res.on('finish', function ()
|
38 | {
|
39 | if (res.statusCode !== 200)
|
40 | {
|
41 | on_failure();
|
42 | }
|
43 | });
|
44 | next();
|
45 | }, (blockedMs) =>
|
46 | {
|
47 | if (!attempted)
|
48 | {
|
49 | res.error(`Operation is disabled due to too many failed attempts. Please try again in ${Math.round(blockedMs / 1000)} seconds`);
|
50 | }
|
51 | });
|
52 | };
|
53 | }
|
54 |
|
55 | return function (req, res, next)
|
56 | {
|
57 | next();
|
58 | };
|
59 |
|
60 | }
|
61 |
|
62 | module.exports = failure;
|