DEV Community

Cover image for jsonwebtoken javascript
Md Yeasin Arafath
Md Yeasin Arafath

Posted on

1

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');
}
}

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

This is not stack overflow

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay