Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js local strategy WITHOUT mongoose

Tags:

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.

like image 233
Chen Avatar asked Apr 21 '17 09:04

Chen


2 Answers

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"})
});
like image 116
robertklep Avatar answered Sep 23 '22 11:09

robertklep


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

like image 29
Chen Avatar answered Sep 23 '22 11:09

Chen