Saturday, March 10, 2018

facebook authentication using passport.js in nodejs

Authentication using passportJs is the most popular and secure module. By using passportJs,  we can signin / login / authenticate  very easily and quickly.

We can also facebook authenticate using passport-facebook.

Here we will discuss regarding facebook authentication.

login.html

<div ng-controller="UserLoginController as ctrl">
            <h2>Login</h2>
           
             Your form for login by email and password ....

            <a href="javascript:void(0)" onClick="window.location.href='/user/loginByFacebook';">
                  <img src="images/icon/facebook_login.png" class="">
            </a>

      </div>

user.js (user model) // Stored in /app/model/user.js

'use strict';
/*
 *Declare variables and include mongoose
 */
var mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      ObjectId = Schema.ObjectId;
var jwt = require('jsonwebtoken');

/*
 *Define structure of collection
 */
var userSchema = new Schema({
      social_id: { type: String },
      social_type: { type: String },
      user_name: { type: String },
      email: {
            type: String,
            index: true
      },
      password: String
      is_active: { type: String, enum: ['1', '0'], default: "1" },
      created_at: {
            type: Date,
            default: Date.now
      },
      updated_at: { type: Date },
}, { collection: 'user' });

/*
 *Validations
 */
userSchema.path('email').required(true, 'email is required!');
userSchema.path('email').match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'fill a valid email address');

userSchema.path('email').validate(function(value, done) {
      this.model('User').count({ email: value }, function(err, count) {
            if (err)
                  return done(err);
            // If `count` is greater than zero, "invalidate"
            done(!count);
      });
}, 'Email already exists');

/*
 *methods
 */
userSchema.methods.generateJwt = function() {
      var expiry = new Date();
      expiry.setDate(expiry.getDate() + 7);

      return jwt.sign({
            _id: this._id,
            email: this.email,
            user_name: this.user_name,
            exp: parseInt(expiry.getTime() / 1000),
      }, "MY_SECRET", {
        expiresIn: '7d' //7 days
    }); // DO NOT KEEP YOUR SECRET IN THE CODE!
};

/*
 *Define model and export it for user in other page
 */
var User = mongoose.model('User', userSchema);
module.exports = User;

routes.js

var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var mongoose = require('mongoose');
var User = require('./models/user');

module.exports = function(app) {
   
     //Start ============Facebook Passport authentication localStategy=============
                passport.use(new FacebookStrategy({
                    clientID: "your facebook api client id",
                    clientSecret: "your facebook api secret key",
                    callbackURL: "http://localhost/user/loginByFacebookCallback",//your live domain full url
                    profileFields: ['email', 'name', 'gender', 'birthday'],
                },
                        function (accessToken, refreshToken, profile, cb) {
                            process.nextTick(function () {
                                console.log(profile);
                                User.findOne({
                                    social_id: profile.id,
                                    social_media: "facebook",
                                    is_active: 1
                                },
                                'social_id user_name email is_active',
                                function (err, user) {
                                    if (!user) {
                                        var infoData = "";
                                        if (!!profile.id)
                                            infoData += "social_no=" + profile.id;
                                        if (!!profile.provider)
                                            infoData += "&provider=" + profile.provider;
                                        if (!!profile._json.first_name)
                                            infoData += "&username=" + profile._json.first_name;
                                        if (!!profile.gender)
                                            infoData += "&gender=" + profile.gender;
                                        if (!!profile._json.email)
                                            infoData += "&email=" + profile._json.email;
                                        return cb(null, false, {profile: infoData});
                                    } else {
                                        return cb(null, user);
                                    }
                                });
                            });
                        }
                ));
      //End :=====================Passport authentication localStategy=============

      router.get('/user/loginByFacebook', passport.authenticate('facebook'), function (req, res) {});
   
      router.get('/api/user/loginByFacebookCallback', function (req, res) {
                    passport.authenticate('facebook', function (err, user, info) {
                        if (err) {
                            logger.log("error", "facebook login error : " + err);
                            res.json({status: 0, , message: err});
                        }
                        if (!user) {
                            res.redirect("Your user register path");
                        } else {
                            req.login(user, {}, function (err) {
                                if (err) {
                                    res.redirect("Your user sign in path"+"/?errormessage=Could not login user");
                                } else {
                                 
                                        logger.log("info", user._id + ' user logged in');
                                        var _res = user.generateJWT(user);
                                        res.cookie('hz-token', _res, {maxAge:  60 * 60 * 24 * 7 * 1000, httpOnly: false});

                                        res.redirect("Your redirection url after user login");

                                }
                            });
                        }
                    })(req, res);
                });
};

From this way, we can authenticate with facebook by using passport-facebook module in nodejs.

For authenticate by email and password using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/authentication-using-passpotjs-in-nodejs.html

For twitter authenticate using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/twitter-authentication-using-passportjs-in-nodejs.html

No comments:

Post a Comment