Skip to content

Commit

Permalink
Update rate limiting logic for custom rate limit value
Browse files Browse the repository at this point in the history
  • Loading branch information
seeprogramming committed Dec 20, 2024
1 parent edf0521 commit b93530c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
9 changes: 6 additions & 3 deletions apps/bs_backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,19 @@ app.use(express.json());
// })
// );
app.use(requestLogger);
const limiterForAdminAPI = limiter(50);
const limiterForEmployeeAPI = limiter(50);
const limiterForCustomerAPI = limiter(50);

app.use('/api/auth', authRoutes);

app.get('/api/test1', limiter, verifyToken, authorizeRoles(['admin']), (req, res) => {
app.get('/api/test1', limiterForAdminAPI, verifyToken, authorizeRoles(['admin']), (req, res) => {
res.send('Hello Admin!');
});
app.get('/api/test2', verifyToken, authorizeRoles(['employee']), (req, res) => {
app.get('/api/test2', limiterForEmployeeAPI, verifyToken, authorizeRoles(['employee']), (req, res) => {
res.send('Hello Employee!');
});
app.get('/api/test3', verifyToken, authorizeRoles(['customer']), (req, res) => {
app.get('/api/test3', limiterForCustomerAPI, verifyToken, authorizeRoles(['customer']), (req, res) => {
res.send('Hello Customer!');
});

Expand Down
6 changes: 4 additions & 2 deletions apps/bs_backend/routes/auth.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ const limiter = require('../utils/rateLimitHandler');

const router = express.Router();

router.post('/register', limiter, validateRequest(registerValidation), register);
router.post('/login', limiter, validateRequest(loginValidation), login);
const limiterForAuth = limiter(5);

router.post('/register', limiterForAuth, validateRequest(registerValidation), register);
router.post('/login', limiterForAuth, validateRequest(loginValidation), login);
router.post('/logout', logout); //

module.exports = router;
21 changes: 12 additions & 9 deletions apps/bs_backend/utils/rateLimitHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ const rateLimit = require('express-rate-limit');
const ErrorHandler = require('./ErrorHandler');

//Define the rate limit
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
handler: (req, res, next) => {
next(
new ErrorHandler('Rate limit exceeded: Too many requests.', 429, 'REQUEST_EXCEED_ERROR', { field: 'api' })
);
},
});
const limiter = (maxRequest) =>
rateLimit({
windowMs: 15 * 60 * 1000,
max: maxRequest || 100,
handler: (req, res, next) => {
next(
new ErrorHandler('Rate limit exceeded: Too many requests.', 429, 'REQUEST_EXCEED_ERROR', {
field: 'api',
})
);
},
});

module.exports = limiter;

0 comments on commit b93530c

Please sign in to comment.