I am stucking with this code. I need to check if a token is ok before proceed to a an "api" route. My problem is my callback in the line
checkTokenAlive(token, function (err) {
never returns.
What am I doing wrong?
const express = require('express')
const app = express()
const server = require('http').Server(app)
....
checkTokenAlive = (decoded, cb) => {
const now = Date.now().valueOf() / 1000
if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
cb(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
cb(`token not yet valid: ${JSON.stringify(decoded)}`)
}
}
checkTokenAuthenticated = (req, res, next) => {
let token = req.body.token;
checkTokenAlive(token, function (err) {
console.log('I am here'); //problem - never called
if (err) {
console.log(err)
return res.status(400).end(err)
}
return next()
});
}
app.post('/api', checkTokenAuthenticated, async (req, res) => {
....
})
decoded.expanddecoded.nbfareundefinedor have certain values then you never call your callback. And, since those values come fromreq.bodywhich can contain anything from an incoming request, that is clearly a problem. Also, it appears that you don't call the callback when the token is still valid.if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {andif (typeof decoded.nbf !== 'undefined' && decoded.nbf > now)insidecheckTokenAlivefunction are evaluated to false. So, it never reaches cb