You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.3 KiB
JavaScript

11 months ago
// middlewares/auth.js
const jwt = require("jsonwebtoken")
require("dotenv").config()
11 months ago
// Middleware for verifying and authenticating JWT token
exports.authenticateToken = (req, res, next) => {
// Extract the token from the Authorization header
const token = req.header("Authorization")?.replace("Bearer ", "")
if (!token) {
return res
.status(401)
.json({ message: "Unauthorized. Token not provided." })
}
console.log("Token:", token) // Log the token to the console
try {
const decoded = jwt.verify(token, process.env.SECRET_SAUCE)
req.user = decoded // Attach the decoded information to the request for future use
// dEBUGGING PURPOSES
console.log("userId:", decoded.userId)
console.log("isAdmin:", decoded.isAdmin)
next()
} catch (error) {
console.error("Token Verification Error:", error)
return res
.status(401)
.json({ message: "Unauthorized. Invalid or expired token." })
}
}
// Function to generate a JWT token
11 months ago
exports.generateToken = (userId, email, isAdmin) => {
return jwt.sign({ userId, email, isAdmin }, process.env.SECRET_SAUCE, {
expiresIn: "1h",
})
}
// Middleware to verify admin status
exports.verifyAdmin = (req, res, next) => {
if (req.user && req.user.isAdmin) {
next()
} else {
return res
.status(403)
.json({ message: "Action Forbidden. User is not an admin." })
}
}