Skip to content

Commit

Permalink
[Task] #43, ratelimit for login page
Browse files Browse the repository at this point in the history
  • Loading branch information
Type-Style committed Mar 8, 2024
1 parent 95b5322 commit 45ee2b9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
6 changes: 3 additions & 3 deletions src/controller/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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";

Expand Down Expand Up @@ -110,4 +110,4 @@ function createToken(req: Request, res: Response) {
return token;
}

export default router;
export default router;
9 changes: 5 additions & 4 deletions src/middleware/limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import logger from '@src/scripts/logger';
*/
const baseOptions: Partial<rateLimiterOptions & slowDownOptions> = {
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<slowDownOptions> = {
Expand All @@ -28,8 +28,8 @@ const baseRateLimitOptions: Partial<rateLimiterOptions> = {
ipsThatReachedLimit[res.locals.ip] = { limitReachedOnError: true, time: Date.now() };
}
res.status(options.statusCode).send(options.message);
}

},
message: "Too many attempts"
}


Expand Down Expand Up @@ -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,
Expand All @@ -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',
});

0 comments on commit 45ee2b9

Please sign in to comment.