Thursday, 11 May 2017

When to use passport.js?

I've been developing in node for the last months to try and understand the framework, and now I'm actually going to try to make an app for multiple devices.

I want to use a node project as the api, which will handle all post and get requests.

In another node project I would have a react web interface communicating with the node api with ajax and socket.io.

In a mobile android/ios or cordova I would have the mobile interface communicating as above.

Now that I've explained the background of my question I will describe my problem.

For now I have a node project that uses bcrypt to encrypt passwords for registration and login. I also use passport to establish a session and for flash messages.

router.post('/login',
    passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
    function(req, res) {
        res.redirect('/');
    });

passport.use(new LocalStrategy(
    function(username, password, done) {
        db_functions.getUserByEmail(username,function(error, results)  {
            if (error) throw error;

            bcrypt.compare(password, results[0].password, function(err, res) {
                if(res === true){
                    return done(null,results[0])
                } else {
                    return done(null, false, {message: 'Invalid password'})
                }
            });
        })
    }));

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

passport.deserializeUser(function(id, done) {
    console.log(id)
    db_functions.getUserById(id,function(error, results)  {
        if (error) throw error;
        done(error,results[0])
    })
});

I read here http://passportjs.org/docs/overview, that if I'm going to use my node project as an API, I should disable sessions and I will therefore use:

app.get('/api/users/me',
  passport.authenticate('basic', { session: false }),
  function(req, res) {
    res.json({ id: req.user.id, username: req.user.username });
  });

Now, that I have sessions disabled, why exactly should I keep using passport? I use bcrypt to register and check for password match when a user logs in. If I do remove it, does that mean that each request that comes from a web browser or a mobile device would have to also transmit the user and hashed password?



via Bogdan Daniel

No comments:

Post a Comment