Saturday, February 14, 2015

Overview

If you ever wondered how people use the Sign in with Google way of logging in, here’s how. You can find more information here.

Installation

Step 1

1
2
3
4
5
### Command Line ###

# Get the right packages
npm install --save passport
npm install --save passport-google

Step 2

1
2
3
4
5
6
7
8
// ### in app.js ###

// At the top
var passport = require('passport');

// Add middleware
app.use(passport.initialize());
app.use(app.router);  // has to be before this line

Step 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ### in config/passport-config.js ###

var passport = require('passport')
  , GoogleStrategy = require('passport-google').Strategy;


// For persistent login
passport.serializeUser(function(user, done) {
  done(null, user);
});
passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


passport.use(new GoogleStrategy({
    returnURL: 'http://localhost:3000/auth/google/return',
    // Where it's valid
    realm: 'http://localhost:3000/'
  },
  function(identifier, profile, done) {
    process.nextTick(function () {
      profile.identifier = identifier;
      return done(null, profile);
    });
  }
));

Step 4

1
2
3
4
5
6
7
8
9
10
11
12
13
// ### in app.js ###

// at the bottom
require('./config/passport-config');

app.get('/auth/google', passport.authenticate('google', {
  scope: ['email']
}));

app.get('/auth/google/return', passport.authenticate('google', {
  successRedirect: "/good",
  failureRedirect: "/bad"
}));

Random Posts