import { NextFunction, Request, Response } from "express"; import jwt from "jsonwebtoken"; import type { AuthorizedUser } from "../types/user.js"; async function authenticateUser( req: Request, res: Response, next: NextFunction ) { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith("Bearer ")) { return res.status(401).json({ message: "User authentication failed.", }); } const token = authHeader.split(" ")[1]; try { const authorizedUser = jwt.verify( token, process.env.JWT_SECRET! ) as AuthorizedUser; req.user = authorizedUser; next(); } catch (error) { console.error("User authentication failed: ", error); return res.status(403).json({ message: "User authentication failed.", }); } } export default authenticateUser;