33 lines
852 B
JavaScript
33 lines
852 B
JavaScript
import jwt from "jsonwebtoken";
|
|
import Vendor from "../models/Vendor.model.js";
|
|
|
|
export const protectVendor = async (req, res, next) => {
|
|
if (req.method === "OPTIONS") {
|
|
return res.status(200).end();
|
|
}
|
|
|
|
let token;
|
|
|
|
if (
|
|
req.headers.authorization &&
|
|
req.headers.authorization.startsWith("Bearer")
|
|
) {
|
|
try {
|
|
token = req.headers.authorization.split(" ")[1];
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
|
|
const vendor = await Vendor.findById(decoded.id);
|
|
if (!vendor) return res.status(401).json({ message: "Unauthorized" });
|
|
|
|
req.user = vendor;
|
|
req.user.storeId = vendor.storeId;
|
|
|
|
next();
|
|
} catch (error) {
|
|
return res.status(401).json({ message: "Token failed" });
|
|
}
|
|
} else {
|
|
return res.status(401).json({ message: "Not authorized, no token" });
|
|
}
|
|
};
|