Skip to content

Instantly share code, notes, and snippets.

@sagar2agrawal
Last active December 19, 2017 12:52
Show Gist options
  • Save sagar2agrawal/e07f6f0312090715c7eea716cf779da6 to your computer and use it in GitHub Desktop.
Save sagar2agrawal/e07f6f0312090715c7eea716cf779da6 to your computer and use it in GitHub Desktop.
Accessing session data in passport js
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var User = require('../models/User.js');
var configAuth = require('./auth.js');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({ 'id' : id }, function(err, user) {
done(err, user);
});
});
// =========================================================================
// FACEBOOK ================================================================
// =========================================================================
passport.use(new FacebookStrategy({
// pull in our app id and secret from our auth.js file
clientID : configAuth.facebookAuth.clientID, clientSecret : configAuth.facebookAuth.clientSecret,
callbackURL : configAuth.facebookAuth.callbackURL, profileFields : configAuth.facebookAuth.profileFields
},
// facebook will send back the token and profile
function(token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// find the user in the database based on their facebook id
User.findOne({ 'facebook.facebook_id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
if (err)
return done(err);
// if the user is found, then log them in
if (user) {
return done(null, user); // user found, return that user
} else { // if there is no user found with that facebook id, create them
var newUser = new User();
// set all of the facebook information in our user model
newUser.facebook.facebook_id = profile.id; // set the users facebook id
newUser.facebook.facebook_token = token; // we will save the token that facebook provides to the user
newUser.firstname = profile.name.givenName; // store first
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// HERE /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
newUser.utm.campaign_source = req.session.campaign_source;
newUser.utm.campaign_medium = req.session.campaign_medium;
newUser.utm.campaign_name = req.session.campaign_name;
newUser.utm.campaign_content = req.session.campaign_content;
newUser.utm.referral_code = req.session.referral_code;
newUser.save(function(err) {
if (err)
throw err;
// if successful, return the new user
return done(null, newUser);
});
}
});
});
}));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment