other
This commit is contained in:
32
backend/middleware/authMiddleware.js
Normal file
32
backend/middleware/authMiddleware.js
Normal file
@@ -0,0 +1,32 @@
|
||||
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" });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user