Search code examples
javascriptnode.jsexpresspassport.jsnode-mysql

How to pass more variables via passport callback function?


I have the following function:

passport.use(new LocalStrategy(
    function (username, password, done) {

        connection.query('SELECT * FROM accounts WHERE username = ?  LIMIT 1', [username], function (err, rows, fields) {
            if (!err) {
                if (rows.length > 0) {
                    var row = rows[0];
                    var passwordHash = require('crypto').createHash('sha1').update(password).digest('hex');

                    if (!passwordHash.localeCompare((row.password))) {
                        return done(null, {username: row.username});
                    }
                }
            }
        });
    }
));

When the authentication succeedes, I want to pass more fields rather than just username. So, I've changed my code to:

 if (!passwordHash.localeCompare((row.password))) {
      return done(null, {username: row.username, role: row.accountType});
 }

However, when I call user.role field in my template, this will be null.

Thank you in advance


Solution

  • You can do the following:

    var row = rows[0];
    var passwordHash = require('crypto').createHash('sha1').update(password).digest('hex');
    
    if (!passwordHash.localeCompare((row.password))) {
           return done(null, row);
     }
    

    This will pass all fields from the result row. If you want to skip some fields, you can create an object, assign necessary fields and then pass it as parameter in the done() function.

    Please don't forget to modify your serialize/deserialze functions as well:

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