I am trying to login a user using jwt. when the users signs in a token is generated and I set a header
res.header('Authorization', token);
then i redirect to another route with a middleware to verify the token but req.header('Authorization');
is undefined in the middleware .if I send the user's token with postman header Authorization: <user's token copied from database>
it works but not with redirecting. can someone point me my fault ? thank you
route with middleware
app.get("/home", verifyToken, async (req, res) => { // buraya auth ekle üye olmayan göremesin
try {
const tweets = await User.getAllTweets()
console.log("--> ", req.token)
res.render("home", { allTweets: tweets })
}
catch (e) {
res.send(e)
}
})
redirecting route
app.post("/signup", async (req, res) => {
const user_email = req.body.email
const user_password = req.body.password
const user = new User({ email: user_email, password: user_password })
try {
// const token = await user.generateAuthToken()
const token = jwt.sign({ _id: user._id.toString() }, "harrypotterbetterthanlotr")
res.header('Authorization', token);
console.log(token === res.getHeader("Authorization"));
user.tokens.push(token)
await user.save()
await user.sendMail(user.email)
res.redirect("/home")
} catch (e) {
console.log(e)
res.status(501).redirect("/signup")
}
})
middleware verifyToken.js
const User = require("../models/user");
const jwt = require("jsonwebtoken")
const verifyToken = async (req, res, next) => {
try {
const token = req.header('Authorization');
console.log("token", token);
const decoded = jwt.verify(token, "harrypotterbetterthanlotr")
const user = await User.findOne({ _id: decoded._id })
if (!user) {
throw new Error("User not found")
}
req.token = token;
req.user = user
// Next middleware
next();
} catch (e) {
// Forbid the route
console.log("Authorization", req.header("authorization"));
console.log("req token", req.token);
// console.log("req header", header);
res.status(401).send(e)
}
}
module.exports = verifyToken