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.
41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
const jwt = require('jsonwebtoken');
|
|
require("dotenv").config()
|
|
|
|
// Function to verify JWT token
|
|
exports.verifyToken = (token) => {
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.SECRET_SAUCE);
|
|
return decoded;
|
|
} catch (error) {
|
|
console.error(error);
|
|
return null; // Return null if verification fails
|
|
}
|
|
};
|
|
|
|
// Middleware for verifying 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.' });
|
|
}
|
|
|
|
const decoded = exports.verifyToken(token);
|
|
|
|
if (!decoded) {
|
|
return res.status(401).json({ message: 'Unauthorized. Invalid token.' });
|
|
}
|
|
|
|
// Attach the decoded information to the request for future use
|
|
req.user = decoded;
|
|
|
|
// Proceed to the next middleware or route handler
|
|
next();
|
|
};
|
|
|
|
// Function to generate a JWT token
|
|
exports.generateToken = (userId, email) => {
|
|
return jwt.sign({ userId, email }, process.env.SECRET_SAUCE, { expiresIn: '1h' });
|
|
};
|