Facebook login using nodejs and express

In my previous article i have explained about Twitter login using node js and express. In this article i am going to cover Facebook login using node js and express.

DOWNLOAD

Note : At the time of writing article i used node version 0.10.22 and Express 4.8.7.

app

Creating Facebook App:

Very first thing you going to need is AppID and AppSecret from Facebook App. Please go to Facebook Developers and create your app.

Choose WWW as platform when it ask. Give the proper name and you can leave namespace field blank.

app 2

 

It will ask for Captcha, enter it carefully and once done it will redirect you to app page. By authenticating your facebook account again you can view the App secret. Now go to Setting and add the Web as a platform.

If you want to test the app in localhost environment then add localhost:3000 as an site address. We are done with the Facebook App creation.

Configuring our Node App:

In the source directory go to the configuration/config.js and update the Facebook AppID and AppSecret. If you want to use Database to store and validate user information you can put the configuration field as true or false. To know the database design for the app please visit twitter login using node article.

configuration/config.js
module.exports={
  "facebook_api_key"      :     "FB APP ID",
  "facebook_api_secret"   :     "FB API SECRET",
  "callback_url"          :     "http://localhost:3000/auth/facebook/callback",
  "use_database"          :     "false",
  "host"                  :     "localhost",
  "username"              :     "root",
  "password"              :     "",
  "database"              :     "DB NAME"
}

Update the code with Facebook App information.

Route of Our App:

Routes Action
/auth/facebook Authenticate User with Facebook
/auth/facebook/callback Get the user information from if login successfully
/logout Logging out from App.

Configuring Passport:

I am using Passport node package for the OAuth authentication. It requires configuration of some parameters. Here is our Passport configuration code.

app.js
/*config is our configuration variable.*/
passport.use(new FacebookStrategy({
    clientID: config.facebook_api_key,
    clientSecret:config.facebook_api_secret ,
    callbackURL: config.callback_url
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User exists or not using profile.id
      if(config.use_database==='true')
      {
         //Further code of Database.
      }
      return done(null, profile);
    });
  }
));

Complete Server Code:

Here is our app.js with complete routing and Passport code.

app.js
var express           =     require('express')
  , passport          =     require('passport')
  , util              =     require('util')
  , FacebookStrategy  =     require('passport-facebook').Strategy
  , session           =     require('express-session')
  , cookieParser      =     require('cookie-parser')
  , bodyParser        =     require('body-parser')
  , config            =     require('./configuration/config')
  , mysql             =     require('mysql')
  , app               =     express();
//Define MySQL parameter in Config.js file.
var connection = mysql.createConnection({
  host     : config.host,
  user     : config.username,
  password : config.password,
  database : config.database
});
//Connect to Database only if Config.js parameter is set.
if(config.use_database==='true')
{
    connection.connect();
}
// Passport session setup.
passport.serializeUser(function(user, done) {
  done(null, user);
});
passport.deserializeUser(function(obj, done) {
  done(null, obj);
});
// Use the FacebookStrategy within Passport.
passport.use(new FacebookStrategy({
    clientID: config.facebook_api_key,
    clientSecret:config.facebook_api_secret ,
    callbackURL: config.callback_url
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User exists or not using profile.id
      //Further DB code.
      return done(null, profile);
    });
  }
));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', key: 'sid'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
//Router code
app.get('/', function(req, res){
  res.render('index', { user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});
//Passport Router
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
       successRedirect : '/',
       failureRedirect: '/login'
  }),
  function(req, res) {
    res.redirect('/');
  });
app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}
app.listen(3000);

Designing our View:

index.ejs
<% if (!user) { %>
  <div style="width:500px;height:180px;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>
    <a href="/auth/facebook"><img src="fb-login.jpg" width="151" height="24"></a>
    </div>
<% } else { %>
    <h2>Hello, <%= user.username %>.</h2>
<% } %>

Once user login we just have to show the values return from Facebook. Here it is.

<p>ID: <%= user.id %></p>
<p>Username: <%= user.username %></p>
<p>Name :<%= user.displayName %></p>

Running our App:

Download the code and update the config.js with the Facebook app information. Then run

npm install

to install dependencies and then run app using

node app.js

Visit localhost:3000 to view the app.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

24 Comments

  1. Very on-point with your Node tutorials, Shahid, much obliged.

    Curious as to how you were going to make the index, layout, and account .ejs views work together…

  2. Well.. I downloaded your code and ran it. But “Hello undefined” is printed.
    Can you guess what is wrong?

    1. hey may b coz , the profile is object is returning like dz — >

      profile goes here –> { id: ‘1478199245840060’,
      username: undefined,
      displayName: ‘App Dev Axy’,
      name:
      { familyName: undefined,
      givenName: undefined,
      middleName: undefined },
      gender: undefined,
      profileUrl: undefined,
      provider: ‘facebook’,
      _raw: ‘{“name”:”App Dev Axy”,”id”:”1**********0″}’,
      _json: { name: ‘App Dev Axy’, id: ‘1**********0’ } }
      user —> { id: ‘1*********0’,
      username: undefined,
      displayName: ‘App Dev Axy’,
      name:
      { familyName: undefined,
      givenName: undefined,
      middleName: undefined },
      gender: undefined,
      profileUrl: undefined,
      provider: ‘facebook’,
      _raw: ‘{“name”:”App Dev Axy”,”id”:”1**********0″}’,
      _json: { name: ‘App Dev Axy’, id: ‘1**********0’ } }

      so go back to ur application and navigate to views -> index.ejs

      edit this –> Hello, . to —> Hello, .

      hope this should fix ur issue 🙂

        1. I do with console command as below:

          app.get(‘/account’, ensureAuthenticated, function(req, res){
          console.log(req.user);
          res.render(‘account’, { user: req.user });
          });

          it returns:
          2016-09-25T11:58:03.31+0700 [App/0] OUT { id: ‘10154xxxxxxxxxxxx’,
          2016-09-25T11:58:03.31+0700 [App/0] OUT displayName: ‘Jeerapong Putthanbut’,
          2016-09-25T11:58:03.31+0700 [App/0] OUT name: {},
          2016-09-25T11:58:03.31+0700 [App/0] OUT provider: ‘facebook’,
          2016-09-25T11:58:03.31+0700 [App/0] OUT _raw: ‘{“name”:”Jeerapong Putthanbut”,”id”:”10154623775144673″}’,
          2016-09-25T11:58:03.31+0700 [App/0] OUT _json: { name: ‘Jeerapong Putthanbut’, id: ‘10154623775144673’ } }

  3. Not working.. says
    Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

  4. Hello! Awesome work sir! I just needed to know, what fields more to add, if we want to extract more than just the user id, like name, email, etc? (for both twitter and facebook login)

      1. How can the operations of MySql converted to that of mongoDB? If i want to store and retrieve my data from mongoDB, how can that be done?

  5. I wasted nearly one week for implementing this thing in maa project….

    But Finally wen i found this module O:) #Made_my_day O:)

    Thanx a ton broh u helped me #Twice …. #Shaid O:)

    THanx Alot 🙂 Plz keep on post’n 🙂 will b supporting ur work 🙂 #peace ! 🙂

  6. hi shahid, ur tutorial is osssome and i want to know how to get the users profile pic too..pls give me a quick response

  7. This sql always returning 0, even if the number of rows is greater than 0 in MySQL database.
    SELECT * from user_info where user_id=”+profile.id

Leave a Reply

Your email address will not be published. Required fields are marked *