Bilal Belli
Bilal Belli

Reputation: 44

How do I store my Token and use it by JWT and cookie-parser? I always get req.cookies.jwt return undefined

Problem: When i Login (i enter email and password), it redirect me to the login page again, it does not allow me to access the home page. and it prints on console : "token = undefined". Where is the problem and how can I fix it?

In ./app.js , i have this code :

./app.js

const cookieParser = require("cookie-parser");
const { requireAuth } = require('./user/auth');
app.use(cookieParser());
app.get('/accueil', requireAuth,(req, res) => {
    console.log('you are now on home page');
    res.render('accueil');
    res.end();
});

I have this ./User/Auth.js file which contains a middleware for the home page, and print on console : "token = undefined", so i think that the token is not stored i have no idea why.

./User/Auth.js

const jwt = require('jsonwebtoken');
require("cookie-parser");

const requireAuth = (req, res, next) => {
    let token = req.cookies.jwt;
    console.log("token = "+token);
    // check json web token exists & is verified
    if (token) {
        jwt.verify(token, 'net', (err, decodedToken) => {
        if (err) {
            console.log(err.message);
            res.redirect('/');
        } else {
            console.log('decodedToken : '+decodedToken);
            next();
        }
        });
    } else {
        res.redirect('/');
    }
};
module.exports = { requireAuth };

This file ./routes/compte contain the login post route:

./routes/compte

router.post('/compteCon', (req, res)=>{
    console.log('CONNECTION OF AN ACCOUNT');
    const email = req.body.email;
    const MotPasse = req.body.MotPasse;
    const sql = 'select * from compte where (compte.email = \"'+email+'\" and \"'+MotPasse+'\"=compte.motPasse)';
    getConn().query(sql,(err, results)=>{
        if(err){
            console.log('Failed : ', err);
            res.sendStatus(500);
            res.end();
            return;
        }
        if(results[0] == null){
            console.log("Your Email or Password is wrong");
            res.redirect('/');
            res.end();
            return;
        }else{
            if (results[0].typePost === "Admin"){
                // may be should i store token
                res.redirect('adminaccueil');
                res.end();
                return;
            }else{
                // may be should i store token
                res.redirect('accueil');
                res.end();
                return;
            }
        }
    });
})

Upvotes: 0

Views: 817

Answers (1)

Harshad.N
Harshad.N

Reputation: 98

i think you are not generated the token try like this

utils

const  jwt  = require ('jsonwebtoken')

// generating token
 maxAge= 60 * 1000 * 60 * 3 
function generateToken(id) {
    return jwt.sign({id}, process.env.JWT_SECRET, { expiresIn: maxAge });
  }

module.exports = generateToken

is better to use different files

Upvotes: 0

Related Questions