1

I have the following ajax post which is working perfectly with passportjs.

$(document).ready(function(){
  $('#btn-login').click(function() {
      var email = $('#loginEmail').val();
      var password = $('#loginPassword').val();
      var emailValidation = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);
      if(!email | !password) {
        $('#loginLabel').text('Email and password are required.');
      }
      else if(!emailValidation.test(email)) {
        $('#loginLabel').text('Email format is invalid.');
      }
      else {
        var userData = {
          username: email,
          password: password
        };

        var request = $.ajax({
          type: 'POST',
          url: '/login',
          data: userData
        });

        request.done(function (response, textStatus, jqXHR) {
          window.location.href = '/profile';
        }).fail(function (jqXHR, exception) {
          $('#loginLabel').text('Invalid email and/or password.');
        });
      }
  });
});

Now I am trying to do the same thing from node but it is not working.

  activateUserAccount(payload, res) {
    const token = payload.token;
    signUpService.validateEmailToken(token)
      .then(isVerified => {
        if(isVerified[0]) {

          const userData = JSON.stringify({
            username: isVerified[1],
            password: isVerified[2]
          });

          const options = {
            hostname: 'localhost',
            port: 3000,
            path: '/login',
            agent: false,
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
          };

          const req = http.request(options, (response) => {
            let responseString = '';

            response.on('data', data => {
                responseString += data;
            });
            response.on('end', (data) => {
                res.redirect('profile');
            });


          });

          req.write(userData);
          req.end();
        }
        else {
          res.redirect('error-page' + '?status=errit');
        }
      })
      .catch(err => console.log(err));
  }

Don't mind the JSON part, as values are passed correctly to passportjs, I have console logged everything.

Passportjs part.

const expiryDate = new Date(Date.now() + 60 * 60 * 1000);
app.use(session({
  secret: 'XeGcW4Vb23',
  resave: false,
  saveUninitialized: false,
  httpOnly: true,
  expires: expiryDate
}));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((user, done) => {
  done(null, user);
});

const restrictedArea = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.redirect('/login');
  }
};

passport.use(new LocalStrategy(
  (username, password, done) => {
    console.log("strategy username");
    console.log(username);
    console.log("strategy password");
    console.log(password);
    console.log("strategy done");
    console.log(done);
    databaseManagement.selectUser(username, password)
      .then(user => _.isEmpty(user)
        ? done(null, false)
        : done(null, { username: username, password: password }));
  }
));

app.post('/login', (req, res, next) => {
  console.log("REQ BODY");
    console.log(req.body);
    passport.authenticate('local', (err, user, info) => {
      console.log("REQ err");
      console.log(err);
      console.log("REQ user");
      console.log(user);
      console.log("REQ info");
      console.log(info);
        if(err) { return res.status(500).json(err);}
        if(!user) { return res.status(401).json(info);}
        req.logIn(user,(err) => {
            if (err) { return next(err); }
            return res.json({detail: info});
        });
    })(req, res, next);
});

app.get('/profile', restrictedArea, (req, res) => {
  profile.renderProfile(res);
});

In both cases (ajax/node post) the output is the following:

REQ BODY
{ username: 'someemail@gmail.com', password: 'Potato123' }
strategy username
someemail@gmail.com
strategy password
Potato123
strategy done
[Function: verified]
REQ err
null
REQ user
{ username: 'someemail@gmail.com', password: 'Potato123' }
REQ info
undefined

but it seems that the session is not created after node post, as it redirects me back to /login.

Do you know what might be the issue here? In case additional details are needed, let me know.

Nenson
  • 173
  • 2
  • 9
  • Have you setup `passport.session()` and/or `express-session`? – Cisco Aug 13 '17 at 13:33
  • Yes, I have edited the post now. – Nenson Aug 13 '17 at 13:35
  • I don't know if this is helpful but it looks like you do serialize and deserialize in an uncommon way. here is how most people do it. you could see in the answer https://stackoverflow.com/questions/27637609/understanding-passport-serialize-deserialize – jack blank Aug 15 '17 at 05:50
  • Thanks Jack, that doesn't seem to be the issue. The example is different, as they are using MongoDB. – Nenson Aug 17 '17 at 19:23

0 Answers0