From 2a8b336ca3ecf89f5e4f4e8217ba5adbc3dd897d Mon Sep 17 00:00:00 2001 From: SubhadeepAtta Date: Thu, 29 Oct 2026 11:02:28 +0530 Subject: [PATCH] fix: support optional auth for quiz joining --- .../src/middlewares/authmiddleware.ts | 37 ++++++++++++++----- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/apps/http-server/src/middlewares/authmiddleware.ts b/apps/http-server/src/middlewares/authmiddleware.ts index 7fa0e0e..ef3a4c6 100644 --- a/apps/http-server/src/middlewares/authmiddleware.ts +++ b/apps/http-server/src/middlewares/authmiddleware.ts @@ -46,20 +46,37 @@ export const authMiddleware = async (req: Request, res: Response, next: NextFunc * A bad or expired token is treated as no token rather than an error. Someone * with a stale token in their browser should still be able to play. */ -export const optionalAuthMiddleware = async (req: Request, _res: Response, next: NextFunction) => { - const authHeader = req.headers["authorization"]; - if (!authHeader || !authHeader.startsWith('Bearer ')) return next(); +export const optionalAuthMiddleware = ( + req: Request, + _res: Response, + next: NextFunction +) => { + const authHeader = req.headers.authorization; - const token = authHeader.split(' ')[1]; - if (!token) return next(); + if (!authHeader?.startsWith("Bearer ")) { + return next(); + } + + const token = authHeader.split(" ")[1]; + + if (!token) { + return next(); + } try { - const decoded = jwt.verify(token, process.env.JWT_SECRET || "secret") as { userId: string }; - req.userId = decoded.userId; + const decoded = jwt.verify( + token, + process.env.JWT_SECRET || "secret" + ) as { userId?: string }; + + if (typeof decoded.userId === "string" && decoded.userId.length > 0) { + req.userId = decoded.userId; + } } catch { - // Expired or malformed: continue as an anonymous participant. + // Invalid or expired token: continue as an anonymous participant. } - next(); -} + return next(); +}; +