Commit 8a2cc6cf76d08638df2307e33f071afae03596ba
1 parent
d4e968beab
Exists in
master
and in
1 other branch
Rate limit on product tree
Showing 1 changed file with 23 additions and 3 deletions Side-by-side Diff
lib/partner-listener/routers/product-tree.js
1 | 1 | const MODULE_NAME = 'PARTNER-LISTENER.ROUTERS.PRODUCT-TREE'; |
2 | 2 | |
3 | +const RATE_LIMIT_MESSAGE = 'Rate limited. Cobalah satu menit lagi!\n'; | |
4 | +const RATE_LIMIT_MAX = 2; | |
5 | +const RATE_LIMIT_WINDOW_MS = 60 * 1000; | |
6 | + | |
3 | 7 | const axios = require('axios').default; |
4 | 8 | const express = require('express'); |
5 | 9 | const urlJoin = require('join-path'); |
10 | +const expressRateLimit = require('express-rate-limit'); | |
6 | 11 | |
7 | 12 | const coreUrl = require('komodo-sdk/core-url'); |
8 | 13 | const logger = require('tektrans-logger'); |
... | ... | @@ -15,11 +20,26 @@ const CORE_ENDPOINT = urlJoin(coreUrl, '/product-tree'); |
15 | 20 | const router = express.Router(); |
16 | 21 | module.exports = router; |
17 | 22 | |
23 | +const rateLimit = expressRateLimit({ | |
24 | + windowMs: RATE_LIMIT_WINDOW_MS, | |
25 | + max: RATE_LIMIT_MAX, | |
26 | + message: RATE_LIMIT_MESSAGE, | |
27 | + keyGenerator: (req, res) => res.locals && res.locals.terminalName, | |
28 | + // handler: (req, res, next, opts) => { | |
29 | + // onRateLimited(req, res, 'ip', opts); | |
30 | + // }, | |
31 | +}); | |
32 | + | |
33 | +const extractTerminalName = (req, res, next) => { | |
34 | + const terminalNameWithoutIp = (getFromBodyQsParams(req, 'terminal_name') || '').toString().trim(); | |
35 | + res.locals.terminalName = `${terminalNameWithoutIp}@${ipv6ToIpv4(req.ip)}`; | |
36 | + next(); | |
37 | +}; | |
38 | + | |
18 | 39 | const mainHandler = async (req, res) => { |
19 | 40 | const { xid } = res.locals; |
20 | 41 | |
21 | - const terminalNameWithoutIp = (getFromBodyQsParams(req, 'terminal_name') || '').toString().trim(); | |
22 | - const terminalName = `${terminalNameWithoutIp}@${ipv6ToIpv4(req.ip)}`; | |
42 | + const { terminalName } = res.locals; | |
23 | 43 | const password = getFromBodyQsParams(req, 'password'); |
24 | 44 | |
25 | 45 | try { |
... | ... | @@ -52,4 +72,4 @@ const mainHandler = async (req, res) => { |
52 | 72 | } |
53 | 73 | }; |
54 | 74 | |
55 | -router.get('/', mainHandler); | |
75 | +router.get('/', extractTerminalName, rateLimit, mainHandler); |