other
This commit is contained in:
49
backend/middleware/staffAuthMiddleware.js
Normal file
49
backend/middleware/staffAuthMiddleware.js
Normal file
@@ -0,0 +1,49 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import Staff from "../models/Staff.model.js";
|
||||
|
||||
/**
|
||||
* Middleware to protect staff-only routes - Verify JWT from DB
|
||||
*/
|
||||
export const protectStaff = async (req, res, next) => {
|
||||
let token = req.headers.authorization;
|
||||
|
||||
if (!token || !token.startsWith("Bearer ")) {
|
||||
return res.status(401).json({ error: "Not authorized, no token" });
|
||||
}
|
||||
|
||||
try {
|
||||
token = token.split(" ")[1];
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// Verify staff user exists and token matches stored value
|
||||
const staff = await Staff.findById(decoded.id);
|
||||
if (!staff || staff.currentToken !== token) {
|
||||
return res.status(401).json({ error: "Invalid or expired session" });
|
||||
}
|
||||
|
||||
req.user = staff; // Attach staff user data to request
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(401).json({ error: "Token is invalid or expired" });
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 📌 Staff Logout - Remove JWT from Database
|
||||
*/
|
||||
export const logoutStaff = async (req, res) => {
|
||||
try {
|
||||
const staff = await Staff.findById(req.user.id);
|
||||
if (!staff) {
|
||||
return res.status(401).json({ error: "User not found" });
|
||||
}
|
||||
|
||||
// Clear stored token
|
||||
staff.currentToken = null;
|
||||
await staff.save();
|
||||
|
||||
res.json({ message: "Logged out successfully" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user