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

Rate Limit API Calls #402

Open
wants to merge 6 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
4 changes: 4 additions & 0 deletions api/controllers/AdminController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { JsonController, Post, Patch, UploadedFile, UseBefore, ForbiddenError, Body, Get } from 'routing-controllers';
import { UserAuthentication } from '../middleware/UserAuthentication';
import { RateLimiter } from '../middleware/RateLimiter';
import {
CreateBonusRequest,
CreateMilestoneRequest,
Expand All @@ -23,6 +24,7 @@ import StorageService from '../../services/StorageService';
import PermissionsService from '../../services/PermissionsService';
import { UserModel } from '../../models/UserModel';
import AttendanceService from '../../services/AttendanceService';
import { RateLimit } from '../decorators/RateLimit';

@UseBefore(UserAuthentication)
@JsonController('/admin')
Expand All @@ -40,7 +42,9 @@ export class AdminController {
this.attendanceService = attendanceService;
}


@Get('/email')
@RateLimit()
async getAllEmails(@AuthenticatedUser() user: UserModel): Promise<GetAllEmailsResponse> {
if (!PermissionsService.canSeeAllUserEmails(user)) throw new ForbiddenError();
const emails = await this.userAccountService.getAllEmails();
Expand Down
1 change: 1 addition & 0 deletions api/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import UserSocialMediaService from '../../services/UserSocialMediaService';
import StorageService from '../../services/StorageService';
import { UserAuthentication } from '../middleware/UserAuthentication';
import { AuthenticatedUser } from '../decorators/AuthenticatedUser';
import { RateLimit } from '../decorators/RateLimit';
import {
MediaType,
File,
Expand Down
23 changes: 23 additions & 0 deletions api/decorators/RateLimit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5,
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

console.log("HELLO");

export function RateLimit(): MethodDecorator {
return function (_target: any, _key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
console.log("originalMethod", originalMethod);
descriptor.value = function (...args: any[]) {
const context = args[0];
limiter(context.req, context.res, () => {});
return originalMethod.apply(this, args);
};
return descriptor;
};
}
19 changes: 19 additions & 0 deletions api/middleware/RateLimiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers';
import * as express from 'express';
import { rateLimit } from 'express-rate-limit';
// import { Config } from '../../config';

@Middleware({ type: 'before' })
export class RateLimiter implements ExpressMiddlewareInterface {
private limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: 'Too many requests, please try again later.',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

use(req: express.Request, res: express.Response, next: express.NextFunction) {
return this.limiter(req, res, next);
}
}
2 changes: 2 additions & 0 deletions api/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { RequestLogger } from './RequestLogger';
import { ErrorHandler } from './ErrorHandler';
import { NotFoundHandler } from './NotFoundHandler';
import { MetricsRecorder } from './MetricsRecorder';
//import { RateLimiter } from './RateLimiter';

export const middlewares = [
ErrorHandler,
NotFoundHandler,
RequestLogger,
MetricsRecorder,
//RateLimiter
];
2 changes: 2 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@ const app = createExpressServer({
defaultErrorHandler: false,
});

app.set('trust proxy', 1);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also this is ugly as well, it feels weird adding this app.set here. I don't think there's a way with our routing-controllers package to have the app.set config set, but maybe there's other ideas out there


app.listen(Config.port);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"dotenv": "^8.2.0",
"ejs": "^3.1.3",
"express": "^4.17.1",
"express-rate-limit": "6.11.2",
"faker": "^5.5.3",
"jsonwebtoken": "^8.5.1",
"moment": "^2.27.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2392,6 +2392,11 @@ expect@^27.5.1:
jest-matcher-utils "^27.5.1"
jest-message-util "^27.5.1"

[email protected]:
version "6.11.2"
resolved "https://registry.yarnpkg.com/express-rate-limit/-/express-rate-limit-6.11.2.tgz#6c42035603d3b52e4e2fb59f6ebaa89e628ef980"
integrity sha512-a7uwwfNTh1U60ssiIkuLFWHt4hAC5yxlLGU2VP0X4YNlyEDZAqF4tK3GD3NSitVBrCQmQ0++0uOyFOgC2y4DDw==

express-session@^1.17.1:
version "1.17.2"
resolved "https://registry.yarnpkg.com/express-session/-/express-session-1.17.2.tgz#397020374f9bf7997f891b85ea338767b30d0efd"
Expand Down
Loading