title: passport.js hangs on some posts
body: <p>I've been searching stackoverflow for reasons why my node.js (express) app hangs on some posts with passport.js.</p>
  
  <p>I've been looking at theese two questions:</p>
  
  <p><a href="https://stackoverflow.com/questions/20626183/more-passport-js-woes-hangs-on-form-submission">More Passport.js woes - hangs on form submission</a></p>
  
  <p><a href="https://stackoverflow.com/questions/21844028/passport-local-is-hanging-on-authentication">Passport (local) is hanging on Authentication</a></p>
  
  <p>My code for creating a user works fine, and looks like this:</p>
  
  <pre><code>passport.use('local-signup', new LocalStrategy({
          // by default, local strategy uses username and password, we will override with email
          usernameField : 'email',
          passwordField : 'password',
          passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
      },
      function(req, email, password, done) {
          if (email)
              email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching
  
          // asynchronous
          process.nextTick(function() {
              // if the user is not already logged in:
              if (!req.user) {
  
                  User.findOne({
                      where: {
                          local_email: email
                      }
                  }).then(function(user) {
                      if (user){
                          return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                      }else{
                          // create the user
                          User
                 .build({
                    local_email: email,
                                local_password: generateHash(password),
                                id: 1 //Normal activated user
                 })
                 .save()
                 .then(newUser =&gt; {
                  //Our newly crated user
                  return done(null, newUser);
                 })
                 .catch(error =&gt;{
                 //Woops something went wrong 
                 return done(error); 
                 })
  
                          //var newUser            = new User();
                          //newUser.localemail    = email;
                          //newUser.localpassword = generateHash(password);
  
                          //User.create(newUser).then(function(newUser, created) {
                          //    if (!newUser) {
                          //        return done(err);
                          //    }
                          //    if (newUser) {
                          //        return done(null, newUser);
                          //    }
                          //});
                      }
                  });
                  // if the user is logged in but has no local account...
              } else if ( !req.user.local.email ) {
                  // ...presumably they're trying to connect a local account
                  // BUT let's check if the email used to connect a local account is being used by another user
                  User.findOne({
                      where: {
                          localemail: email
                      }
                  }).then(function(user) {
                      if (err)
                          return done(err);
                      if (user){
                          return done(null, false, req.flash('loginMessage', 'That email is already taken.'));
                          // Using 'loginMessage instead of signupMessage because it's used by /connect/local'
                      } else {
                          // create the user
                          var newUser            = new User();
  
                          newUser.local.email    = email;
                          newUser.local.password = generateHash(password);
                          User.create(newUser).then(function(newUser, created) {
                              if (!newUser) {
                                  return done(err);
                              }
                              if (newUser) {
                                  return done(null, newUser);
                              }
                          });
                      }
                  });
              } else {
                  // user is logged in and already has a local account. Ignore signup. (You should log out before trying to create a new account, user!)
                  return done(null, req.user);
              }
          });
      }));
  </code></pre>
  
  <p>In my routs file the post to that function looks like this:</p>
  
  <pre><code>// process the signup form
  app.post('/signup', passport.authenticate('local-signup', {
      successRedirect : '/profile', // redirect to the secure profile section
      failureRedirect : '/signup', // redirect back to the signup page if there is an error
      failureFlash : true // allow flash messages
  }));
  </code></pre>
  
  <p>My code for signing in however dosen't work that well. The function in passport.js looks like this:</p>
  
  <pre><code>passport.use('local-login', new LocalStrategy({
          // by default, local strategy uses username and password, we will override with email
          usernameField : 'email',
          passwordField : 'password',
          passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
      },
      function(req, email, password, done) {
          if (email)
              email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching
  
          // asynchronous
          process.nextTick(function() {
              User.findOne({
                  where: {
                      local_email: email
                  }
              }).then(function(user){
          console.log("TEST: "+user);
                  // if no user is found, return the message
                  if (!user){
          console.log("no user with the following email: " +email);
                      return done(null, false, req.flash('loginMessage', 'No user found.'));
                  }else if(!validPassword(password,user.local_password)){
                      console.log("wrong password");
          return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
                  // all is well, return user
                   }else{
                      return done(null, user);
          return;
            }
              }).catch(function(err){
          console.log("woops der skete en fejl: "+err);
          console.log("email is: "+email);
                  console.log("password is: "+password); 
          return done(err);   
      });
  
          });
  
      }));
  </code></pre>
  
  <p>The corresponding route looks like this:</p>
  
  <pre><code>// process the login form
  app.post('/login', passport.authenticate('local-login', {
      successRedirect : '/', // redirect to the secure profile section
      failureRedirect : '/login', // redirect back to the signup page if there is an error
      failureFlash : true // allow flash messages
  }));
  </code></pre>
  
  <p>The above code hangs when the form is being submitted. If I changes the code to:</p>
  
  <pre><code>app.post('/login', function(req, res, next) {
      passport.authenticate('local-login', function(err, user, info) {
        if (err) { return next(err); }
        if (!user) {
          return res.render('/login', {
            pageTitle: 'Sign in',
            form: req.body
          });
        }
        req.logIn(user, function(err) {
          if (err) { return next(err); }
          return res.redirect('/');
        });
      })(req, res, next);
  });
  </code></pre>
  
  <p>I receive an 500.
  Any ideas why this isen't working?</p>
  
  <p>Updated with console output:</p>
  
  <pre><code>Executing (default): SELECT `id`, `role`, `local_email`, `local_password`, `facebook_id`, `facebook_token`, `facebook_email`, `facebook_name`, `twitter_id`, `twitter_token`, `twitter_displayname`, `twitter_username`, `google_id`, `google_token`, `google_email`, `google_name`, `createdAt`, `updatedAt` FROM `users` AS `users` WHERE `users`.`local_email` = 'test@local' LIMIT 1;
  TEST: [object SequelizeInstance:users]
  POST /login 302 87.021 ms - 46
  Executing (default): SELECT `id`, `role`, `local_email`, `local_password`, `facebook_id`, `facebook_token`, `facebook_email`, `facebook_name`, `twitter_id`, `twitter_token`, `twitter_displayname`, `twitter_username`, `google_id`, `google_token`, `google_email`, `google_name`, `createdAt`, `updatedAt` FROM `users` AS `users` WHERE `users`.`id` = 1;
  </code></pre>
  
  <p>Updated with changed passport.deserializeUser</p>
  
  <pre><code> passport.deserializeUser(function(id, done) {
          /*User.findById(id, function(err, user) {
              done(err, user);
          });*/
          User.findById(id).then(user =&gt; {
              if (!user){
                  done(null);
              }else{
                  done(user);
              }
          })
      });
  </code></pre>