Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js always returning 500 internal error

I am trying to build a very simple authentication api using passport.js, but I my code always returns 500 internal error status.

var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var logger = require('morgan');
var path = require('path');
var passport = require('passport');
var passportLocal = require('passport-local');    

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
    secret: process.env.SESSION_SECRET || 'secret',
    resave: false,
    saveUninitialized: false
}));

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

passport.use(new passportLocal.Strategy(function (username, password, done) {
    console.log('login using ' + username);
    done(null, { id: 1, username: 'test', password: '12345'});
}));

passport.serializeUser(function(user, done) {
    done(user.id);
});

passport.deserializeUser(function(id, done) {
    done({ id: id, username: 'test', password: '12345' });
});

app.get('/', function(req, res) {
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user
    });
});

app.get('/login', function(req, res) {
    res.render('login');
});

app.post('/login', passport.authenticate('local'), function(req, res) {
    res.redirect('/');
});    

app.listen(app.get('port'), function(){
    console.log('server is listenning on port ' + app.get('port'));
});

I have a simple post form at my '/login' path, I test my server by entering whatever I want in the username and password fields, then the browser sends the post request to '/login', then the server successfully reach the line:

console.log('login using ' + username);

And the result is that the server returns the value 1 ( id: 1 ) to the browser and a 500 internal server error.

what am I missing?

like image 765
Matan Givoni Avatar asked Dec 14 '22 15:12

Matan Givoni


1 Answers

Found the problem..

When calling done function inside serializeUser I sent my user.id as the err object.

To fix this I simply replaced:

passport.serializeUser(function(user, done) {
    done(user.id);
});

to:

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
like image 53
Matan Givoni Avatar answered Jan 01 '23 07:01

Matan Givoni