Thursday, 1 June 2017

Save a JWT as a cookie

so basically I want to store a JWT token in a cookie so that it can be accessed later to authenticate API calls. I can't figure out how to do this.

 passport.use(new LocalStrategy(
      function(email, password, done) {
       User.getUserByEmail(email, function(err, user){
        if(err) throw err;
        if(!user){
            return done(null, false, {message: 'Unknown User'});
        }

        User.comparePassword(password, user.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch){

            const token = jwt.sign(user, config.secret, {
              expiresIn: 604800 // 1 week
            });

                    //STORE TOKEN AS A COOKIE

                return done(null, user);
            } else {
                return done(null, false, {message: 'Invalid password'});
            }
        });
       });
        }
    ));
    router.post('/login',
      passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
      function(req, res) {
        res.redirect('/');
      });

Thanks in advance, Ed.



via Ed Lynch

No comments:

Post a Comment