Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Rate Limiting to specific endpoints - huntr.dev #177

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"class-validator": "^0.10.0",
"csv": "^5.1.1",
"ejs": "^2.6.1",
"express-rate-limit": "^5.1.3",
"generate-password": "^1.4.1",
"gettext-parser": "^3.1.0",
"handlebars": "^4.5.3",
Expand Down
9 changes: 9 additions & 0 deletions api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { PassportModule } from '@nestjs/passport';
import { NestExpressApplication } from '@nestjs/platform-express';
import { TypeOrmModule } from '@nestjs/typeorm';
import { renderFile } from 'ejs';
import * as rateLimit from 'express-rate-limit';
import { config } from './config';
import { AuthController } from './controllers/auth.controller';
import { ExportsController } from './controllers/exports.controller';
Expand Down Expand Up @@ -100,6 +101,14 @@ export const addPipesAndFilters = (app: NestExpressApplication) => {
whitelist: true,
}),
);

// rate-limiting middleware
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 20, // limit each IP to 20 requests per windowMs
}),
);

app.useStaticAssets(config.publicDir, { index: false, redirect: false });

Expand Down
15 changes: 3 additions & 12 deletions api/src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,18 +181,9 @@ export class UserService {

async authenticate({ grantType, email, password }: { grantType: GrantType; email: string; password?: string }): Promise<User> {
const normalizedEmail = normalizeEmail(email);
const user = await this.userRepo.findOneOrFail({ email: normalizedEmail });

const timeThreshold = moment()
.subtract(15, 'minutes')
.toDate();

// If lockout time has passed, reset counter
if (user.lastLogin < timeThreshold) {
user.loginAttempts = 0;
// Otherwise abort request
} else if (user.loginAttempts >= 3) {
throw new TooManyRequestsException('too many login attempts');
const user = await this.userRepo.findOne({ email: normalizedEmail });
if (!user) {
throw new UnauthorizedException('invalid credentials');
}

switch (grantType) {
Expand Down