From 45ee2b9471539e44f57db5a2e86a7c0eeadf4eb0 Mon Sep 17 00:00:00 2001 From: Type-Style Date: Fri, 8 Mar 2024 14:47:25 +0100 Subject: [PATCH] [Task] #43, ratelimit for login page --- src/controller/read.ts | 6 +++--- src/middleware/limit.ts | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/controller/read.ts b/src/controller/read.ts index e3de1c2..305d891 100644 --- a/src/controller/read.ts +++ b/src/controller/read.ts @@ -5,7 +5,7 @@ import { validationResult, query } from 'express-validator'; import jwt from 'jsonwebtoken'; import logger from '@src/scripts/logger'; import { crypt } from '@src/scripts/crypt'; -import { loginSlowDown, loginLimiter } from '@src/middleware/limit'; +import { loginSlowDown, loginLimiter, baseSlowDown, baseRateLimiter } from '@src/middleware/limit'; const router = express.Router(); @@ -37,7 +37,7 @@ router.get('/', // TODO write test for checking the limit on request body -router.get("/login/", async function login(req: Request, res: Response) { +router.get("/login/", baseSlowDown, baseRateLimiter, async function login(req: Request, res: Response) { logger.log("login was called"); res.locals.text = "start"; @@ -110,4 +110,4 @@ function createToken(req: Request, res: Response) { return token; } -export default router; \ No newline at end of file +export default router; diff --git a/src/middleware/limit.ts b/src/middleware/limit.ts index 5bdb109..70e608a 100644 --- a/src/middleware/limit.ts +++ b/src/middleware/limit.ts @@ -8,7 +8,7 @@ import logger from '@src/scripts/logger'; */ const baseOptions: Partial = { windowMs: 30 * 60 * 1000, - //skip: (req, res) => (res.locals.ip == "127.0.0.1" || res.locals.ip == "::1") + skip: (req, res) => (res.locals.ip == "127.0.0.1" || res.locals.ip == "::1") } const baseSlowDownOptions: Partial = { @@ -28,8 +28,8 @@ const baseRateLimitOptions: Partial = { ipsThatReachedLimit[res.locals.ip] = { limitReachedOnError: true, time: Date.now() }; } res.status(options.statusCode).send(options.message); - } - + }, + message: "Too many attempts" } @@ -58,6 +58,7 @@ export const loginSlowDown = slowDown({ delayMs: (used: number) => (used - 1) * 250, // Add delay after delayAfter is reached }); +export const baseRateLimiter = rateLimit(baseRateLimitOptions); export const errorRateLimiter = rateLimit({ ...baseRateLimitOptions, @@ -68,5 +69,5 @@ export const loginLimiter = rateLimit({ ...baseRateLimitOptions, windowMs: 3 * 60 * 1000, limit: 3, - message: 'Too many failed login attempts', + message: 'Too many attempts without valid login', }); \ No newline at end of file