Configure Strategy

Now that we've registered our app with Google, we can configure Passport.

First, let's create a '.env' file to store the client ID and secret we just obtained from Google.

$ touch .env

Then, add the client ID and secret. The contents of the file should look something like this:


Of course, your client ID and secret should be inserted where noted.

Open 'routes/auth.js' and add the following code at line 6 to configure the GoogleStrategy.

passport.use(new GoogleStrategy({
  clientID: process.env['GOOGLE_CLIENT_ID'],
  clientSecret: process.env['GOOGLE_CLIENT_SECRET'],
  callbackURL: '/oauth2/redirect/google',
  scope: [ 'profile' ]
}, function verify(issuer, profile, cb) {
  db.get('SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?', [
  ], function(err, row) {
    if (err) { return cb(err); }
    if (!row) {'INSERT INTO users (name) VALUES (?)', [
      ], function(err) {
        if (err) { return cb(err); }

        var id = this.lastID;'INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)', [

        ], function(err) {
          if (err) { return cb(err); }
          var user = {
            id: id,
            name: profile.displayName
          return cb(null, user);
    } else {
      db.get('SELECT * FROM users WHERE id = ?', [ row.user_id ], function(err, row) {
        if (err) { return cb(err); }
        if (!row) { return cb(null, false); }
        return cb(null, row);

This configures the GoogleStrategy to fetch the user record associated with the Google account. If a user record does not exist, one is created the first time someone signs in.

The strategy is now configured. Next we need to maintain state when redirecting to Google.