Saturday, October 21, 2017

Check that token is valid or invalid using jwt

Hey I have one small problem with token in app. I have middleware to check token in next routes and I use tokne to isLoggedIn function in angular to check logged users. But if I change token in local storage user still is logged because token still exist but is invalid. Could you help how I can response from middleware that token is valid or invalid and next check this in angular? Question: How check that token is valid or invalid in angular? e.g. if token is invalid change route location
Please look on my code:

middleware

router.use(function(req, res, next){
var token = req.body.token || req.body.query || req.headers['x-access-token']  
  if(token){
     jwt.verify(token, secret, function(err,decoded){
        if(err){
           res.json({success:false, message:'Invalid token'})
        } else {
           req.decoded = decoded;
           next()
        }
     })
  } else {
     res.json({ success: false, message:'No token provided' });
  }
});

factory

.factory('AuthToken', function($window){
  var authTokenFactory = {};
  authTokenFactory.setToken = function(token){
    if(token){
        $window.localStorage.setItem('token',token)
    } else {
        $window.localStorage.removeItem('token')
    }

  };
  authTokenFactory.getToken = function(){
    return $window.localStorage.getItem('token')
  }

  return authTokenFactory
})

isLoogedIn function

    authFactory.isLoggedIn = function(){
    if(AuthToken.getToken()){
        return true 
    } else {
        return false
    }
}
return authFactory

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/21/check-that-token-is-valid-or-invalid-using-jwt/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment