Skip to content

Commit

Permalink
Cache user and ratelimit update. Also delete cache if details change
Browse files Browse the repository at this point in the history
  • Loading branch information
tanish35 committed Oct 24, 2024
1 parent b5fad3a commit 5054883
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
15 changes: 9 additions & 6 deletions backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import sendMail from "../mail/sendMail";
import { Verifier } from "academic-email-verifier";
import checkCollegeEmail from "../mail/checkAcademic";
import { registerSchema } from "../validation/registerSchema";
import redis from "../lib/redis";

const googleSignInOrSignUp = asyncHandler(
//@ts-ignore
Expand Down Expand Up @@ -230,7 +231,7 @@ const registerUser = asyncHandler(async (req: Request, res: Response) => {
}
});
const resendURL = asyncHandler(async (req: Request, res: Response) => {
const {email, password} = req.body;
const { email, password } = req.body;
if (!email || !password) {
res.status(400).json({ message: "Please provide all fields" });
return;
Expand All @@ -248,8 +249,7 @@ const resendURL = asyncHandler(async (req: Request, res: Response) => {
res.status(401).json({ message: "Logged in with Google Or Github" });
return;
}

})
});
const verifyUser = asyncHandler(async (req: Request, res: Response) => {
const token = req.params.token;
if (!token) {
Expand All @@ -260,7 +260,9 @@ const verifyUser = asyncHandler(async (req: Request, res: Response) => {
const { sub, exp } = jwt.verify(token, process.env.SECRET);
// @ts-ignore
if (exp < Date.now()) {
res.status(400).json({ message: "Token expired. Login to verify your email" });
res
.status(400)
.json({ message: "Token expired. Login to verify your email" });
return;
}
const user = await prisma.user.findUnique({
Expand All @@ -272,7 +274,7 @@ const verifyUser = asyncHandler(async (req: Request, res: Response) => {
res.status(404).json({ message: "User not found" });
return;
}

if (user.emailVerified) {
res.status(400).json({ message: "User already verified" });
return;
Expand Down Expand Up @@ -317,7 +319,7 @@ const loginUser = asyncHandler(async (req: Request, res: Response) => {
const url = `${process.env.BACKEND_URL}/api/user/verify/${token}`;
const htmlContent = `<a href="${url}">Verify using this link</a>`;
sendMail(htmlContent, email);
res.status(201).json({ message: "Email Sent" })
res.status(201).json({ message: "Email Sent" });
return;
}
const match = await bcrypt.compare(password, user.password);
Expand Down Expand Up @@ -638,6 +640,7 @@ const updateDetails = asyncHandler(async (req: Request, res: Response) => {
pic,
},
});
await redis.del(`user:${userId}`);
return res.status(200).json({ message: "Details updated" });
});

Expand Down
14 changes: 13 additions & 1 deletion backend/src/middleware/checkAuth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma";
import redis from "../lib/redis";
// @ts-ignore
async function requireAuth(req, res, next) {
try {
Expand All @@ -11,6 +12,17 @@ async function requireAuth(req, res, next) {
res.sendStatus(410);
return;
}
const userId = decoded.sub;
if (!userId) {
res.sendStatus(401);
return;
}
const cachedUser = await redis.get(userId);
if (cachedUser) {
req.user = JSON.parse(cachedUser);
next();
return;
}
const user = await prisma.user.findUnique({
where: {
user_id: decoded.sub,
Expand All @@ -21,7 +33,7 @@ async function requireAuth(req, res, next) {
return;
}
req.user = user;

await redis.set(`user:${userId}`, JSON.stringify(user), "EX", 3600);
next();
} catch (err) {
res.sendStatus(401);
Expand Down
3 changes: 2 additions & 1 deletion backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
updateDetails,
} from "../controllers/userControllers";
import checkAuth from "../middleware/checkAuth";
import rateLimiter from "../middleware/rateLimit";

const router = express.Router();

Expand All @@ -31,6 +32,6 @@ router.post("/addDetails", addDetailsToUser); // add details to the current user
router.post("/addusername", addUsername); // change the username of the current user
router.get("/all", getAllUser);
router.get("/logout", logOut);
router.post("/update", checkAuth, updateDetails);
router.post("/update", checkAuth, rateLimiter, updateDetails);

export default router;

0 comments on commit 5054883

Please sign in to comment.