Login with Facebook in Node.js Express Application

    Aug 15, 2016       by Pankaj Kumar
facebook-login-nodejs.jpg

 

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 let's configure the task at Node.js end, So lets see our server.js file, which is having all the major task at nodejs end.

 

const express = require('express'),
session = require('express-session'),
mysql =require('mysql'),
app = express();
 
const cookieParser = require('cookie-parser'),
bodyParser = require('body-parser');
 
const passport = require('passport'),
FacebookStrategy = require('passport-facebook').Strategy;
 
//Connection setup with mysql...
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "root",
database : "fblogin"
});
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());
 
// the authenticated user serialization to the session, and deserialization when subsequent requests are made.
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('/', (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' }),
(req, res)=> {
res.redirect('/');
});
 
app.get('/logout', (req, res)=>{
req.logout();
res.redirect('/');
});
 
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
 
app.listen(3000,()=>{
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 let's come to the view part, have a look our ejs file. Let's have a look on index.ejs file.

 

 
<html>
<head>
<title>Login with Facebook in Node.js Express app</title>
<style>
    .fb-login img{
        height: 100px;
        width: 250px;
    }
</style>
</head>
<body>
<% if (!user) { %>
<div class="fb-login">
    <h2 style="font-size:40px;">Login with facebook</h2>
    <a href="/auth/facebook"><img src="facebook-login.png"></a>
    </div>
<% } else { %>
 
    <div class="fb-login">
        <h2>You are sucessfully login, <%= user.displayName %>.</h2>
        <p >
            <a href="/logout">Log Out</a>
        </p>
    
        <h3>User Profile</h3>
        <p>Facebook ID: <%= user.id %></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.

 

Conclusion

So in this demo, We learned how to login with facebook in Node.js express application. You can find other nodejs sample application at jsonworld.com

 

That’s all for now. Thank you for reading and I hope this demo will be very helpful to understand login with facebook in Node.js express application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


Find other similar Articles here: