Facebook Strategy - kplian/pxp-nd GitHub Wiki

The Facebook strategy allows users to log in to a web application using their Facebook account. Internally, Facebook authentication works using OAuth 2.0. Support for Google is implemented by the passport-google-oauth module.

1. Install

$ npm install passport-facebook

2. Configuration oAuth 2.0

In order to use Facebook authentication, you must first create an app at Facebook Developers. When created, an app is assigned an App ID and App Secret. . Create config file src/lib/auth/passport-facebook:

var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

passport.use(new FacebookStrategy({
  clientID: 'yourfacebookAppID',
  clientSecret: 'yourFacebookClientSecret',
  callbackURL: "http://localhost:3000/api/facebook/callback"
},
  function(accessToken, refreshToken, profile, done) {
    // In this section you should use the business logic corresponding to your needs.
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
       return done(err, user);
    });
  }
));

3. Routes

Two routes are required for Facebook authentication. The first route redirects the user to Facebook. The second route is the URL to which Facebook will redirect the user after they have logged in. Add routes in src/lib/auth/authRoutes.js:

router.get('/api/facebook', passport.authenticate('facebook', { scope: 'read_stream' })); 

router.get('/api/facebook/callback',
  passport.authenticate(
'facebook', 
{ failureRedirect: '/api/login'}//redirect when failed login
),
// Custom callback when login is correct   
function(req, res) {
    res.redirect('/');
});

4. Use config

Finally import the configuration file into your main file before initializing passport:

// ...
require('./src/lib/auth/passport-facebook');
app.use(passport.initialize());
// ...