other
This commit is contained in:
84
backend/routes/staffAuth.routes.js
Normal file
84
backend/routes/staffAuth.routes.js
Normal file
@@ -0,0 +1,84 @@
|
||||
import express from "express";
|
||||
import bcrypt from "bcryptjs";
|
||||
import jwt from "jsonwebtoken";
|
||||
import Staff from "../models/Staff.model.js";
|
||||
import { protectStaff, logoutStaff } from "../middleware/staffAuthMiddleware.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* 📌 Staff Login - Store JWT in Database
|
||||
*/
|
||||
router.post("/login", async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
try {
|
||||
const staff = await Staff.findOne({ username });
|
||||
if (!staff) {
|
||||
return res.status(401).json({ error: "Staff user not found" });
|
||||
}
|
||||
|
||||
const isMatch = await bcrypt.compare(password, staff.passwordHash);
|
||||
if (!isMatch) {
|
||||
return res.status(401).json({ error: "Invalid credentials" });
|
||||
}
|
||||
|
||||
// Generate JWT for Staff/Admin
|
||||
const token = jwt.sign(
|
||||
{ id: staff._id, role: staff.role },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: "7d" }
|
||||
);
|
||||
|
||||
// Store token in database
|
||||
staff.currentToken = token;
|
||||
await staff.save();
|
||||
|
||||
res.json({ token, role: staff.role });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 📌 Staff Logout - Remove JWT from Database
|
||||
*/
|
||||
router.post("/logout", protectStaff, logoutStaff);
|
||||
|
||||
/**
|
||||
* 📌 Force Logout All Staff Users (Admin Only)
|
||||
*/
|
||||
router.post("/logout/all", protectStaff, async (req, res) => {
|
||||
try {
|
||||
if (req.user.role !== "admin") {
|
||||
return res.status(403).json({ error: "Access restricted to admins only" });
|
||||
}
|
||||
|
||||
await Staff.updateMany({}, { currentToken: null });
|
||||
|
||||
res.json({ message: "All staff users have been logged out" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to log out all staff users" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 📌 Check Staff Sessions (Admin Only)
|
||||
*/
|
||||
router.get("/sessions", protectStaff, async (req, res) => {
|
||||
try {
|
||||
if (req.user.role !== "admin") {
|
||||
return res.status(403).json({ error: "Access restricted to admins only" });
|
||||
}
|
||||
|
||||
const activeSessions = await Staff.find({ currentToken: { $ne: null } })
|
||||
.select("username role currentToken createdAt");
|
||||
|
||||
res.json({ activeSessions });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Failed to fetch active sessions" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user