From adc3e35425626b39931e3fe86cc91ad63ed8bcf7 Mon Sep 17 00:00:00 2001 From: anshul23102 Date: Tue, 2 Jun 2026 22:17:37 +0530 Subject: [PATCH] fix(chat): derive username from authenticated session instead of request body [NSoC'26] sendMessage read the username field directly from req.body and stored it in Supabase. Any authenticated user could supply username: 'other_user' in the request body to post messages appearing to come from a different person. The route already requires authenticateUser, so req.user is always populated. The username is now derived from req.user.user_metadata (falling back to req.user.email) so it always reflects the real authenticated identity. Closes #160 --- backend/controllers/chat.controller.js | 42 ++++++++------------------ 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/backend/controllers/chat.controller.js b/backend/controllers/chat.controller.js index e2d7d07..4eeebe7 100644 --- a/backend/controllers/chat.controller.js +++ b/backend/controllers/chat.controller.js @@ -17,35 +17,17 @@ export const getMessages = async (req, res) => { export const sendMessage = async (req, res) => { try { - const { text, username, image, audio } = req.body; - - console.log("Incoming:", { - text, - username, - image, - audio, - }); - - const authHeader = req.headers.authorization; - - if (!authHeader?.startsWith("Bearer ")) { - return res.status(401).json({ - error: "Authentication required", - }); - } - - const token = authHeader.split(" ")[1]; - - const { - data: { user }, - error: authError, - } = await supabase.auth.getUser(token); - - if (authError || !user) { - return res.status(403).json({ - error: "Unauthorized user", - }); - } + const { text, image, audio } = req.body; + + // Derive username from the authenticated session instead of trusting the + // request body. The route requires authenticateUser, so req.user is always + // set at this point. Accepting username from the body allowed any + // authenticated caller to impersonate a different user by supplying an + // arbitrary username value. + const username = req.user?.user_metadata?.username + || req.user?.user_metadata?.name + || req.user?.email + || "Anonymous"; const validationError = validateMessagePayload({ text, @@ -64,7 +46,7 @@ export const sendMessage = async (req, res) => { .insert([ { text, - username: user.email || username, + username, image, audio, status: "sent",