39 lines
1.0 KiB
JavaScript
39 lines
1.0 KiB
JavaScript
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 }
|