title: Node Express Passport app 404ing when trying to login
body: <p>I am trying to figure out why my app is 404ing when I login. The proper index page loads however, from there /login 404s. The stack error isn't at all helpful and just references the error handler in app.js. To try remedy this I tried putting my login.jade template in every directory I thought it could be referencing to no avail. This must mean there's something wrong with the way I'm routing everything but I've tripple checked everything a few times. Any help would be appreciated. </p>
  
  <p>Edit: After more troubleshooting, there had got to be something wrong with the way /login is routed. My app doesn't seem to care if auth has a valid path when requiring it. </p>
  
  <p>App.js</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var passport = require('passport');
  var session = require('express-session');
  var auth = require('./auth')
  var app = express();
  
  // load mongoose package
  var mongoose = require('mongoose');
  var UserModel = require('./models/User');
  UserModel.init();
  
  
  var routes = require('./routes/index');
  var todos = require('./routes/todos');
  
  
  
  // Use native Node promises
  mongoose.Promise = global.Promise;
  
  // connect to MongoDB
  mongoose.connect('mongodb://localhost/todo-api')
    .then(() =&gt;  console.log('connection succesful'))
    .catch((err) =&gt; console.error(err));
  
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'jade');
  
  // uncomment after placing your favicon in /public
  //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(session({secret: '56950fe494af8e88204adf6d', resave: true, saveUninitialized: true}));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  
  app.use(passport.initialize());
  app.use(passport.session());
  
  app.use('/', routes);
  app.use('/todos', todos);
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });
  
  // error handlers
  
  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: err
      });
    });
  }
  
  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: {}
    });
  });
  module.exports = app;
  </code></pre>
  
  <p>Routes.js </p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var auth = require('../auth');
  var controllers = require('../controllers');
  var app = express();
  
  /* GET home page. */
  router.get('/', function(req, res, next) {
    res.render('index', { title: 'ngTodo' });
  });
  
  app.get('/register', controllers.users.getRegister);
  app.post('/register', controllers.users.createUser);
  
  app.post('/login', auth.login);
  app.get('/logout', auth.logout);
  app.get('/login', controllers.users.getLogin);
  
  app.get('/client', function (req, res) {
    res.render('../views/client/index', {currentUser: req.session.user});
  });
  
  app.get('/error', function (req, res) {
    res.render('..views/error')
  });
  
  app.get('/', function (req, res) {
      res.render('index', {currentUser: req.user});
  });
  
  app.get('*', function (req, res) {
    res.render('index', {currentUser: req.user});
  });
  
  module.exports = router;
  </code></pre>
  
  <p>UserController.js </p>
  
  <pre><code>var encryption = require('../utilities/cripto'),
      usersData = require('../models/usersData');
  
  module.exports = {
      getRegister: function (req, res, next) {
          if (req.user) {
              res.redirect('/');
          }
  
          else {
              res.render('users/register');
          }
      },
      createUser: function (req, res, next) {
          var newUserData = req.body;
  
          if (newUserData.password !== newUserData.confirmPassword) {
              req.session.error = 'Passwords do not match!';
              res.redirect('/register');
          }
  
          else {
              newUserData.salt = encryption.generateSalt();
              newUserData.hashPass = encryption.generateHashedPassword(newUserData.salt, newUserData.password);
              usersData.createUser(newUserData, function (err, user) {
                  if (err) {
                      req.session.error = 'Username exists!';
                      res.redirect('/register');
                      return;
                  }
  
                  req.logIn(user, function (err) {
                      if (err) {
                          res.status(400);
                          return res.send({reason: err.toString()});
                      }
  
                      else {
                          res.redirect('/');
                      }
                  });
              });
          }
      },
      updateUser: function (req, res, next) {
          if (req.user._id == req.body._id || req.user.roles.indexOf('admin') &gt; -1) {
              var updatedUserData = req.body;
              if (updatedUserData.password &amp;&amp; updatedUserData.password.length &gt; 0) {
                  updatedUserData.salt = encryption.generateSalt();
                  updatedUserData.hashPass = encryption.generateHashedPassword(updatedUserData.salt, updatedUserData.password);
              }
  
              if (updatedUserData.password !== updatedUserData.confirmPassword) {
                  req.session.error = 'Passwords do not match!';
                  res.redirect('/profile');
              } else {
                  usersData.updateUser({_id: req.body._id}, updatedUserData, function (err, user) {
                      res.redirect('/profile');
                  })
              }
          }
          else {
              res.send({reason: 'You do not have permissions!'})
          }
      },
      getLogin: function (req, res, next) {
          if (req.user) {
              res.redirect('/');
          }
          else {
              res.render('users/login');
          }
      },
      getProfile: function (req, res, next) {
          if (!req.user) {
              res.redirect('/');
          } else {
              res.render('profile/profile', {currentUser: req.user, userToUpdate: req.user});
          }
      }
  };
  </code></pre>
  
  <p>Auth.js</p>
  
  <pre><code>var passport = require('passport');
  
  module.exports = {
      login: function(req, res, next) {
          var auth = passport.authenticate('local', function(err, user) {
              if (err) return next(err);
              if (!user) {
                  req.session.error = 'Invalid Username or Password!';
                  res.redirect('/');
              }
  
              req.logIn(user, function(err) {
                  if (err) return next(err);
                  res.redirect('/client');
                  console.log();
              })
          });
  
          auth(req, res, next);
      },
      logout: function(req, res, next) {
          req.logout();
          res.redirect('/');
      },
      isAuthenticated: function(req, res, next) {
          if (!req.isAuthenticated()) {
              return false;
          }
          else {
              return true;
          }
      },
      isInRole: function(role) {
          return function(req, res, next) {
              if (req.isAuthenticated() &amp;&amp; req.user.roles.indexOf(role) &gt; -1) {
                  return true;
              }
              else {
                  return false;
              }
          }
      }
  };
  </code></pre>