1 year ago

#307488

test-img

Richard Aginga

Passport.js not sending req.user object while redirecting

I'm trying to build an authentication system with passport-local. I got the initial starter code from here: https://www.digitalocean.com/community/tutorials/easy-node-authentication-setup-and-local#toc-handling-signupregistration

When I try console.log(req.user), it gets logged successfully, meaning that passport does return req.user. However, when redirecting to the logged-in route, req.user becomes undefined. How can I get req.user to be sent to my logged-in route? Here is my code.

Frontend request:

const serverResponse = fetch('http://localhost:5000/api/client/signin', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(x)
  })
  .then((res)=> {
    if (res.user) {
      alert('Sign in successful.')
      return res.user
    } else {
      alert('Try again.')
    }})
  .catch((err)=> {
    alert(`Error: ${err}`)
  })

Backend sign-in route:

router.post('/signin', passport.authenticate('local-login', {
  successRedirect: '/api/client/profile',
  failureRedirect: '/api/client/signin',
  failureFlash: true
}))

Passport js login config file:

passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true // allows us to pass back the entire request to the callback
  },
    function(req, email, password, done) {
      // find a user whose email is the same as the forms email
      UserModel.findOne({
        email: req.body.email
      }, function(err,
        user) {
        // if there are any errors,
        if (err)
          return done(err);
        // if no user is found,
        if (!user) {
          console.log('That account does not exist!')
          return done(null, false, req.flash('loginMessage', 'No user found.'));
        }
        // if the password is wrong
        if (user.password != password) {
          console.log('Wrong password!')
          return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
        }

        // all is well, return successful user
        return done(null, user);
      });
    }));

Logged-in check

function loggedIn(req, res, next) {
  if (req.user) {
    console.log(`User: found.`)
    return next();
  } else {
    console.log('No user object.')
  }
}

Finally, logged-in route

router.get('/profile', loggedIn, (req, res) => {
  console.log('User logged in.')
  console.log(`${req.user}`)
  res.send(req.user)
})

node.js

express

passport-local

0 Answers

Your Answer

Accepted video resources