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.
74 lines
2.0 KiB
JavaScript
74 lines
2.0 KiB
JavaScript
const jwt = require("jsonwebtoken");
|
|
require("dotenv").config();
|
|
|
|
// Middleware for verifying and authenticating JWT token
|
|
exports.authenticateToken = (req, res, next) => {
|
|
try {
|
|
// Extract the token from the Authorization header
|
|
const authHeader = req.header('Authorization');
|
|
|
|
if (!authHeader) {
|
|
return res.status(401).json({ message: 'Unauthorized. Token not provided.' });
|
|
}
|
|
|
|
const token = authHeader.replace('Bearer ', '');
|
|
|
|
console.log('Token:', token); // Log the token to the console
|
|
|
|
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.log('User token expired.');
|
|
|
|
if (error instanceof jwt.TokenExpiredError) {
|
|
return res.status(401).json({ message: 'Unauthorized. Token has expired.' });
|
|
} else {
|
|
return res.status(401).json({ message: 'Unauthorized. Invalid token.' });
|
|
}
|
|
}
|
|
};
|
|
|
|
|
|
// Function to generate a JWT token
|
|
exports.generateToken = (userId, email, isAdmin) => {
|
|
return jwt.sign({ userId, email, isAdmin }, process.env.SECRET_SAUCE, {
|
|
expiresIn: "3h",
|
|
})
|
|
}
|
|
|
|
// 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." })
|
|
}
|
|
}
|
|
|
|
exports.verifyUser = (req, res, next) => {
|
|
const authenticatedUserId = req.user.userId;
|
|
const requestedUserId = req.body.userId;
|
|
|
|
if (authenticatedUserId && authenticatedUserId === requestedUserId) {
|
|
// User is authenticated, and the requested userId matches the authenticated userId
|
|
next();
|
|
} else {
|
|
return res.status(403).json({
|
|
message: "Permission denied.",
|
|
});
|
|
}
|
|
};
|
|
|
|
|
|
exports.extractAnonymousUserId = (req, res, next) => {
|
|
req.anonymousUserId = req.headers['x-anonymous-user-id'];
|
|
next();
|
|
};
|