Last active
February 20, 2020 12:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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