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.
After filling the above fields, Add the Web as a platform. Now we are done with Facebook app creation task.
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.
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.
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.