Home > database >  my function return null when I initiate value correctly(node.js, passport.js, express.js)
my function return null when I initiate value correctly(node.js, passport.js, express.js)

Time:04-13

recently I'm making login authentication and had a problem, I used jwt as a token for security especially issued two tokens for better security(refresh token, access token).

What I was trying to is 'pass different token passport's jwtstrategy depends on the situation.

So, If the refresh token and the access token are both valid, I just pass the access token to jwtstrategy when the refresh token is valid but the access token expired I issue a new token and pass it to jwtstrategy

However, the problem is even I put valid value to return it doesn't return anything. let me show you code.

const tokenCheck = async (req,res) => {
    let jwtoken = null
        //when both token are valid
    if (req && verifyToken('access',req.cookies['accessToken']) && verifyToken('refresh',req.cookies['refreshToken'])) {
   
       
        accessToken = req.cookies['accessToken'];
        jwtoken = accessToken;
        console.log('jwtoken : '  jwtoken);
        return jwtoken
        
        //when only refresh token is valid
        //issue new access token
    } else if (req && !verifyToken('access', req.cookies['accessToken']) && verifyToken('refresh', req.cookies['refreshToken'])) { 
        console.log('you need new access token')
        const refreshTokenInfo = verifyToken('refresh',req.cookies['refreshToken']);
        await User.findById({ _id: refreshTokenInfo.id })
            .then(user => { 
                const Payload = {
                id: user.id,
                userid: user.userid,
                role: user.role
                }
                jwt.sign(Payload, JWT_ACCESS_SECRET, { expiresIn: JWT_ACCESS_EXPIRATION_TIME }, (err, accessToken) => { 
                    if (err) {
                            console.log(err)
                    }
                    console.log(res)
                    console.log('new accesstoken : '   accessToken)
                    res.cookie('accessToken', accessToken,{ httpOnly: true});
                    jwtoken = accessToken;
                });
                return  jwtoken
            })  
    }
        return null

    }

when I log token with 'console.log('jwtoken : ' jwtoken);' right before I return jwtoken it logged well without problem

module.exports = passport => {

    const opts = {};
    opts.jwtFromRequest =  tokenCheck;
    opts.secretOrKey = JWT_ACCESS_SECRET
    opts.passReqToCallback = true;
    
    passport.use(new JwtStrategy(opts,(req,jwt_payload, done) => {
        // console.log(passport);
       
        

        console.log(req)
      console.log(jwt_payload);
        User.findById(jwt_payload.id)
            .then(user => {
                if(user) {
                    return done(null, user)
                }
              
                return done(null, false);
            })
            .catch(err => console.log(err)
           
            );
    }));
};

However, I couldn't get any value in here and it doesn't log nothing

can you explain what is wrong with my code and how to solve it?

thx for reading, your help will be appreciated.

CodePudding user response:

I think your problem maybe is because of the the return situation.

Use a try catch or use this:

               jwt.sign(Payload, JWT_ACCESS_SECRET, { expiresIn: JWT_ACCESS_EXPIRATION_TIME }, (err, accessToken) => { 
                    if (err) {
                        console.log(err)
                    }
                    console.log(res)
                    console.log('new accesstoken : '   accessToken)
                    res.cookie('accessToken', accessToken,{ httpOnly: true});
                    jwtoken = accessToken;
                    return  jwtoken
                });

CodePudding user response:

I replaced the CBS with async/await. You might need to tweak the solution a little bit if it doesn't work. Like changing the Callback to a promise a based response.

const tokenCheck = async (req,res) => {
    let jwtoken = null
        //when both token are valid
    if (req && verifyToken('access',req.cookies['accessToken']) && verifyToken('refresh',req.cookies['refreshToken'])) {
   
       
        accessToken = req.cookies['accessToken'];
        jwtoken = accessToken;
        console.log('jwtoken : '  jwtoken);
        return jwtoken
        
        //when only refresh token is valid
        //issue new access token
    } else if (req && !verifyToken('access', req.cookies['accessToken']) && verifyToken('refresh', req.cookies['refreshToken'])) { 
        console.log('you need new access token')
        const refreshTokenInfo = verifyToken('refresh',req.cookies['refreshToken']);
        try {
          const user =  await User.findById({ _id: refreshTokenInfo.id })
          const Payload = {
                        id: user.id,
                        userid: user.userid,
                        role: user.role
                        }
                  
        const accessToken = await verify(Payload);
        res.cookie('accessToken', accessToken,{ httpOnly: true});
        return jwtoken
        } catch(e) {
          console.log(e);
        }
            
    }
        return null

    }

    const verify = async (Payload) => {
      return new Promise((res, rej) => {
        jwt.sign(Payload, JWT_ACCESS_SECRET, { expiresIn: JWT_ACCESS_EXPIRATION_TIME }, (err, accessToken) => { 
          if (err) {
                  console.log(err)
                  rej(err)
          }
          console.log(res)
          console.log('new accesstoken : '   accessToken)
          
          jwtoken = jwtoken;
          res(accessToken);
       });
      })
    }
  • Related