Created
September 9, 2022 20:20
-
-
Save georgeben/d6e9c0d11624048efdfd8f1777f0dc9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const redis = require('redis'); | |
const rateLimit = require('express-rate-limit'); | |
const RedisStore = require('rate-limit-redis'); | |
const app = express() | |
const redisClient = redis.createClient({ legacyMode: true }) | |
redisClient.connect() | |
redisClient.on("ready", () => console.log("Successfully connected to redis")); | |
/** | |
* Create a rate limit middleware | |
*/ | |
const FIVE_MINUTES = 5 * 60 * 1000 // 5 minutes | |
const rateLimiter = rateLimit({ | |
windowMs: FIVE_MINUTES, | |
max: 30, | |
standardHeaders: true, | |
legacyHeaders: false, | |
store: new RedisStore({ | |
sendCommand: (...args) => redisClient.v4.sendCommand(args), | |
}), | |
message: { | |
error: "Too many requests, please try again later.", | |
}, | |
}) | |
app.use(rateLimiter) | |
// Create a custom rate limiter for login. Restrict users to 10 | |
// login attempts in a 5 minute window | |
const loginRateLimiter = rateLimit({ | |
windowMs: FIVE_MINUTES, | |
max: 10, | |
standardHeaders: true, | |
legacyHeaders: false, | |
store: new RedisStore({ | |
sendCommand: (...args) => redisClient.v4.sendCommand(args), | |
}), | |
message: { | |
error: "Too many requests, please try again later.", | |
}, | |
}) | |
app.post('/login', loginRateLimiter, async (req, res) => { | |
// Check for email and password | |
return res.json({ message: 'Login successful' }) | |
}) | |
app.listen(5000, () => console.log('App running')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment