facebook login with nodejs and ejs template

Cronjob

 

In this article, I am going to explain login with facebook in nodejs application. As we have already discussed login with twitter and github.

So let's start proceeding with this by creating app id and app secret.

Create App Id and App Secret on facebook

As I told earlier, at first we need App ID and AppSecret from Facebook. For creating your app id and app secret go to Facebook Developers. Enter desired name of app and fill mendatory fields.

facebook login image

 

After filling the above fields, Add the Web as a platform. Now we are done with Facebook app creation task.

 

Now lets configure the task at nodejs end, So lets see our server.js file, which is having all the major task at nodejs end.

 

 
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'),
    mysql =require('mysql'),
    app =  express();
 
//Connection setup with mysql...
var connection = mysql.createConnection({
    host     :  "localhost",
    user     :  "root",
    password :  "Techugo@123",
    database :  "taggnet"
});
connection.connect();
 
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
 
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
 
// session related task & passport intiallization...
app.use(session({ secret: 'jsonworldplaceforjsdemos'}));
app.use(passport.initialize());
app.use(passport.session());
 
// Passport session setup.
passport.serializeUser(function(user, done) {
    done(null, user);
});
 
passport.deserializeUser(function(obj, done) {
    done(null, obj);
});
 
// Using FacebookStrategy within Passport here to perform the actual task...
 
passport.use(new FacebookStrategy({
    clientID: "*********",
    clientSecret: "*****************************",
    callbackURL: "http://localhost:3000/auth/facebook/callback",
},
function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User is already registered or a new user...
      connection.query("SELECT * from user_master where user_id="+profile.id,function(err,rows,fields){
        if(err) throw err;
        if(rows.length===0)
          {
            console.log("There is a new user, registering here");
            connection.query("INSERT into user_master(user_id,user_name,full_name) VALUES('"+profile.id+"','"+profile.username+"','"+profile.displayName+"')");
            console.log(profile);
            return done(null, profile);
          }
          else
            {            
              console.log("User already registered in database...");
              return done(null, profile);
            }
          });
    });
  }));
 
app.get('/', function(req, res){
  res.render('index', { user: req.user }); 
});
 
app.get('/auth/facebook', passport.authenticate('facebook',{scope:'email'}));
 
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,function(){
  console.log('server running on port:3000')
});
 

 

In the above file, At top we have included the needed nodejs package with passport related packages. Below that we have created connection with mysql. And below that we have configured passport. And at bottom we have defined the routing in our app.

 

Now lets come to the view part, have a look our ejs file. Let's have a look on index.ejs file.

 

 
<html>
<head>
<title>Facebook Login using Node and Express</title>
</head>
<body>
 
<% if (!user) { %>
 
<div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>
    <a href="/auth/facebook"><img src="fb-login.jpg" width="171" height="34"></a>
    </div>
 
<% } else { %>
 
    <div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
          <h2>Hello, <%= user.displayName %>.</h2>
        <p>
         <a style="padding-right:10px;" href="/">Home</a> |
            <a style="padding-right:10px;" href="/logout">Log Out</a>
        </p>
 
        <h3>My Profile</h3>
 
       <p>ID: <%= user.id %></p>
       <p>Username: <%= user.username %></p>
       <p>Name :<%= user.displayName %></p>
    </div>
 
<% } %>
 
</body>
</html>
 

 

In the above file we are managing log in button or profile data after login.  Follow the steps provided in the read.me file and run the app with url http://localhost:3000.

If still facing issue to run it. Write us at demo.jsonworld@gmail.com

 

You can download complete code from here. Download Code