Skip to content

Instantly share code, notes, and snippets.

@emmaodia
Last active February 20, 2020 12:52
Show Gist options
  • Save emmaodia/4ee14b57009e41a928205074918c2055 to your computer and use it in GitHub Desktop.
Save emmaodia/4ee14b57009e41a928205074918c2055 to your computer and use it in GitHub Desktop.
Gist for the article where we take a look at PassportJS and how easy it is to use the it's Facebook Strategy to authenticate Users for your app.
const passport = require('passport');
const Strategy = require('passport-facebook').Strategy;
require('dotenv').config();
// Configure Passport authenticated session persistence.
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Configure the Facebook strategy for use by Passport.
passport.use(new Strategy({
clientID: process.env['FACEBOOK_CLIENT_ID'],
clientSecret: process.env['FACEBOOK_CLIENT_SECRET'],
callbackURL: 'http://localhost:3000/user/return',
profile: ['id', 'displayName']
},
function(accessToken, refreshToken, profile, done) {
//Check the DB to find a User with the profile.id
User.findOne({ facebook_id: profile.id }, function(err, user) {
if(err) {
console.log(err); // handle errors!
}
if (user) {
done(null, user); //Login if User already exists
} else { //else create a new User
user = new User({
facebook_id: profile.id, //pass in the id and displayName params from Facebook
name: profile.displayName
});
user.save(function(err) { //Save User if there are no errors else redirect to login.
if(err) {
console.log(err); // handle errors!
} else {
console.log("saving user ...");
done(null, user);
}
});
}
});
}
));
// Initialize Passport and restore authentication state, if any, from the
// session.
router.use(passport.initialize());
router.use(passport.session());
// Define routes.
router.get('/home',
(req, res) => {
res.json({ user: user });
});
router.get('/login', (req, res) => { res.json({msg: "login failed"}); });
router.get('/login/facebook', passport.authenticate('facebook'));
router.get('/return',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/api/v1/user/home');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment