Skip to content

Commit

Permalink
Add authRateLimitCheck middleware #23
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanPenchev05 committed Mar 10, 2024
1 parent 3dff090 commit c7f6fbc
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
12 changes: 7 additions & 5 deletions server/controllers/auth/registerController.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,8 @@ export async function registerController(req, res) {

const hashPassword = await bcrypt.hash(password, 12);

//generate a UUID
const uuid = uuidv4();

const verificationToken = jwt.sign({uuid}, process.env.JWT_SECRET, { expiresIn: '15m' });

const tempUsername = await Temp.exists({'value.username': username});

if(tempUsername){
const error = new Error("Username is temporarily taken");
error.errors = {
Expand All @@ -84,8 +80,14 @@ export async function registerController(req, res) {
throw error;
}

//generate a UUID
const uuid = uuidv4();

const verificationToken = jwt.sign({uuid}, process.env.JWT_SECRET, { expiresIn: '15m' });

// Save the user data temporarily in Redis with a 15 minute expiry
await setTempMemory(uuid, {
ip,
firstName,
lastName,
email,
Expand Down
17 changes: 17 additions & 0 deletions server/middleware/authRateLimitCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Temp } from "../models/Temp.js";

export default async function authRateLimitCheck(req, res, next){
const ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;

const tempIP = await Temp.exists({'value.ip': ip});

if(!tempIP){
console.log('here');
next();
} else {
return res.status(429).json({ message: "We have sended an email with verification to you" });
}
}
3 changes: 2 additions & 1 deletion server/routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { registerController } from "../controllers/auth/registerController.js";
import authRateLimitCheck from "../middleware/authRateLimitCheck.js";
import verifyUser from "../controllers/auth/verifyUser.js";
import express from "express";

const authRouter = express.Router();

/* REGISTER */
authRouter.post('/register', registerController);
authRouter.post('/register', authRateLimitCheck, registerController);
/* VERIFY REGISTER USER */
authRouter.get('/verify/:token', verifyUser);

Expand Down

0 comments on commit c7f6fbc

Please sign in to comment.