19 lines
549 B
JavaScript
19 lines
549 B
JavaScript
import jwt from "jsonwebtoken";
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || "your_jwt_secret";
|
|
|
|
export const authenticateToken = (req, res, next) => {
|
|
const token = req.headers.authorization?.split(" ")[1];
|
|
if (!token) {
|
|
return res.status(401).json({ message: "Unauthorized" });
|
|
}
|
|
|
|
try {
|
|
const user = jwt.verify(token, JWT_SECRET);
|
|
req.user = user;
|
|
next();
|
|
} catch (error) {
|
|
console.error("Invalid token:", error.message); // Log the error for debugging
|
|
res.status(403).json({ message: "Invalid token" });
|
|
}
|
|
};
|