Chen
Chen

Reputation: 3060

Passport.js local strategy WITHOUT mongoose

I'm trying to find resources about the most simple login with passport for a node app. I mean, using:

middleware:

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(cookieParser());

    app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
    app.use(passport.initialize());
    app.use(passport.session());

    app.use(express.static('public'));

passport:

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

passport.deserializeUser(function(id, done) {
    done({ id: id, nickname: "test"})
});


    passport.use(new LocalStrategy(
      function(username, password, done) {
        console.log("test");
          if (username === 'username') {
              return done(null, { name: "test", id: '1234'});
          } else {
              return done(null, false, { message: 'Incorrect cred.' });
          }
      })
    )

and redirection:

    app.post('/login',
      passport.authenticate('local', { 
          successRedirect: '/index.html',
          failureRedirect: '/login'
     })
    );

my app structure:

/app.js
/public/index.html
/public/login.html

And that's it. the Web is full of the same examples of Mongoose with plugins, everyone simply copy-pasting from each other.

The point is that I would like, later on, to insert my own code ti the LocalStrategy code (would probably used LDAP).

Currently, instead of redirecting to /index.html with the page created in the public folder, I just receive [object Object] on index.html.

Upvotes: 5

Views: 2030

Answers (2)

robertklep
robertklep

Reputation: 203359

Your passport.deserializeUser() is incorrect:

passport.deserializeUser(function(id, done) {
  done({ id: id, nickname: "test"})
});

It's passing the "user" object as first argument to done, which is reserved for errors. This causes Express to render an error page where it tries to stringify the error, resulting in [object Object].

Try this:

passport.deserializeUser(function(id, done) {
  done(null, { id: id, nickname: "test"})
});

Upvotes: 3

Chen
Chen

Reputation: 3060

Found the issue! the redirection didn't work, so I looked back up and noticed that the express.static mw was set AFTER the passport initialize(), and not BEFORE. I just moved it up to the top and.. rainbows

Upvotes: 1

Related Questions