DEV Community

Cover image for jsonwebtoken javascript
Md Yeasin Arafath
Md Yeasin Arafath

Posted on

jsonwebtoken javascript

I can't verify the token. I got result undefined

// @type POST
// @route /login
// @desc route after login
// @access PUBLIC
router.post('/', (req, res) => {
const email = req.body.email;
const password = req.body.password;
Person.findOne({ email })
.then(person => {
if (!person) {
res.render('login', {errmsg: 'User not found'});
}else{
bcrypt.compare(password, person.password)
.then(isCorrect => {
if (isCorrect) {
const payload = {
id: person.id,
name: person.name,
email: person.email
}
jwt.sign(payload, keys.mongodb.secret, {expiresIn: 3600}, (err, token) => {
console.log(token);
// res.redirect('/account');
res.redirect('/login/account')
});
}else{
res.render('login', {errmsg: 'password not valid'});
}
})
.catch(err => {
console.log(err);
});
}
})
.catch(err => {
console.log(err);
});
});

// @type GET
// @route /login/account
// @desc route after login
// @access PRIVET

router.get('/account', authCheck, (req, res) => {
jwt.verify(req.token, keys.mongodb.secret, (err, data) => {
if (err) {
res.send('err inside route');
}else{
res.send('protected route');
}
})
console.log(req.user);
});

function authCheck(req, res, next){
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}else{
res.send('not working');
}
}

Top comments (1)

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

This is not stack overflow