prod124njac/prod124njac-back-b/authsec_node/Backend/middleware/authenticateJWT.js

39 lines
1.0 KiB
JavaScript
Raw Normal View History

2024-09-18 04:14:45 +00:00
const { verify } = require("jsonwebtoken")
// Middleware for verifying JWT and extracting user information
function authenticateJWT(req, res, next) {
let token = req.headers.authorization
// console.log("Authorization header:", req.headers.authorization)
// console.log("token is..",token);
console.log("Database Host:", process.env.DATABASE_HOST);
console.log("Database User:", process.env.DATABASE_USERNAME);
console.log("Database Port:", process.env.DATABASE_PORT);
if (!token || !token.startsWith("Bearer ")) {
return res.sendStatus(403)
}
// console.log("Original token:", token)
// Remove the "Bearer " prefix
token = token.slice(7)
// console.log("Modified token:", token)
const secret = "secret" // Use the same secret key as in the login controller
verify(token, secret, (err, user) => {
if (err) {
console.log(err)
return res.sendStatus(403)
}
req.user = user // Attach user information to the request object
next()
})
}
module.exports = { authenticateJWT }