dev1/backend/utils/authenticateUser.js

20 lines
602 B
JavaScript

import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET;
/**
* Adds `req.user = { id: <user_profile.id> }`
* If no or bad token ➜ 401.
*/
export default function authenticateUser(req, res, next) {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ error: "Authorization token required" });
try {
const { id } = jwt.verify(token, JWT_SECRET);
req.user = { id }; // attach the id for downstream use
next();
} catch (err) {
return res.status(401).json({ error: "Invalid or expired token" });
}
}