Search code examples
node.jsexpressauthenticationpassport.jspassport-local

Passport throws a 500 internal server error at every request


I'm at a complete loss with this. I can only assume it's passport because when I comment out its initialization everything magically works again. I have 2 routes currently setup. One is a get request that requires a user to be logged in and the other is a post request that actually does the logging in.

in my app.js file my passport setup looks like this:

var sessionStore = new MySQLStore(options);

//handles cookie/session creation
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: config.sessionKey,
    resave: false,
    store:sessionStore,
    saveUninitialized: false,
    cookie: {
        //secure: true,
        maxAge:24*60*60*1000 //1 day in milliseconds
    }
}));
 app.use(passport.initialize());
 app.use(passport.session());
require('./services/passport');

//initiate route handlers
app.use('/login', require('./routes/authRoutes'));
app.use('/tiles', require('./routes/tileRoutes'));

I am using a local strategy as my users won't be using any kind of social app to login. I configured another file passport.js to actually handle the passport setup. I am using the sequelize database in order to verify users. This whole process looks like this:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');


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

passport.deserializeUser((user, done)=>{
    done(null, user.id);
});
passport.use(new LocalStrategy(function (username, password, done) {
    const db = require('../models');
    db.user.findOne({ where: {username: username} })
        .then((user)=>{
            if(!user){
                return done(null, false);
            }else{
                // if(user.dataValues.hashed_password === password)
                //     return done(null, user);
                bcrypt.compare(password, user.dataValues.hashed_password, function(err, res) {
                      if(res === true){
                          return done(null, user);
                      }else{
                          return done(null, err);
                      }
                });

            }
        });

}));

signing people up, creating the session, and storing the session id all seem to be happening, however when I start making get/post requests on my front end with axios (I'm using react) I continually get a internal server error. I've tried catching this in everyway I can think of, breaking at definite points, an console.logging out but I just get the same message:

[0] GET /tiles 500 8.049 ms - 2
[0] GET /tiles 500 2.757 ms - 2

or from the console

GET http://localhost:3000/tiles/ 500 (Internal Server Error)

the actual get request looks like this (i havent' put much in till I know it works):

const express = require('express');
const router = express.Router();

router.get('/', isLoggedIn, (req, res)=>{
    debugger;
    res.send({hi:'there'})
});


function isLoggedIn(req, res, next) {
    debugger;
        if (req.isAuthenticated()) return next();
        console.log('failure');
        res.redirect('/login')
}

module.exports=router;

Solution

  • The deserializeUser should call the function to find user by id here, then pass it to done, the first param is userId as serializeUser return the user.id to session store. Example:

    passport.deserializeUser((id, done)=>{
      passport.deserializeUser((id, done) => {
        User.findById(id).then((user) => {
          done(null, user);
        }).catch(done);
      });
    });