From 944d5c4972e9000424ff35fc5244648d6450a4e2 Mon Sep 17 00:00:00 2001 From: divlo Date: Fri, 30 Oct 2020 17:16:53 +0100 Subject: [PATCH] feat(api): rate limiting --- api/app.js | 14 ++++++++++++++ api/package-lock.json | 5 +++++ api/package.json | 7 ++++--- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/api/app.js b/api/app.js index 09304f5..00cfe5a 100644 --- a/api/app.js +++ b/api/app.js @@ -6,6 +6,7 @@ const helmet = require('helmet') const cors = require('cors') const morgan = require('morgan') const { redirectToHTTPS } = require('express-http-to-https') +const rateLimit = require('express-rate-limit') /* Files Imports & Variables */ const sequelize = require('./assets/utils/database') @@ -20,6 +21,19 @@ if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')) } else if (process.env.NODE_ENV === 'production') { app.use(redirectToHTTPS()) + const requestPerSecond = 2 + const seconds = 60 + const windowMs = seconds * 1000 + app.enable('trust proxy') + app.use( + rateLimit({ + windowMs, + max: seconds * requestPerSecond, + handler: (_req, res) => { + return res.status(429).json({ message: 'Too many requests' }) + } + }) + ) } app.use(helmet()) app.use(cors()) diff --git a/api/package-lock.json b/api/package-lock.json index c0afe8c..21b2f25 100644 --- a/api/package-lock.json +++ b/api/package-lock.json @@ -1406,6 +1406,11 @@ "express": "^4.15.3" } }, + "express-rate-limit": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-5.1.3.tgz", + "integrity": "sha512-TINcxve5510pXj4n9/1AMupkj3iWxl3JuZaWhCdYDlZeoCPqweGZrxbrlqTCFb1CT5wli7s8e2SH/Qz2c9GorA==" + }, "express-validator": { "version": "6.6.1", "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-6.6.1.tgz", diff --git a/api/package.json b/api/package.json index 215e84f..4ac186f 100644 --- a/api/package.json +++ b/api/package.json @@ -11,23 +11,24 @@ "axios": "^0.21.0", "bcryptjs": "^2.4.3", "cors": "^2.8.5", + "dotenv": "^8.2.0", "express": "^4.17.1", "express-fileupload": "^1.2.0", "express-http-to-https": "^1.1.4", + "express-rate-limit": "^5.1.3", "express-validator": "^6.6.1", "helmet": "^4.1.1", "jsdom": "^16.4.0", "jsonwebtoken": "^8.5.1", "moment": "^2.29.1", + "morgan": "^1.10.0", "ms": "^2.1.2", "mysql2": "^2.2.5", "nodemailer": "^6.4.14", "sequelize": "^6.3.5", "smart-request-balancer": "^2.1.1", "uuid": "^8.3.1", - "validator": "^13.1.17", - "dotenv": "^8.2.0", - "morgan": "^1.10.0" + "validator": "^13.1.17" }, "devDependencies": { "nodemon": "^2.0.6",