inventory-api / middleware /authMiddleware.js
Prathamesh2403's picture
Readme.md
a44b98c
Raw
History Blame Contribute Delete
771 Bytes
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
const protect = async (req, res, next) => {
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// Get token from header
token = req.headers.authorization.split(" ")[1];
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Get user from the token
req.user = await User.findById(decoded.id).select("-password");
next();
} catch (error) {
console.error(error);
res.status(401).json({ msg: "Not authorized, token failed" });
}
}
if (!token) {
res.status(401).json({ msg: "Not authorized, no token" });
}
};
export { protect };