Exercise 24 - Using OAuth With Passport and Facebook
Exercise 24 - Using OAuth With Passport and Facebook
Updating config.js
Update config.js with the App ID and App Secret that you obtained earlier as follows:
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl': 'mongodb://localhost:27017/conFusion',
'facebook': {
clientId: 'Your Client App ID',
clientSecret: 'Your Client App Secret'
}
}
Open user.js from the models folder and update the User schema as follows:
1
facebookId: String,
...
});
Setting up Facebook Authentication
Open authenticate.js and add in the following line to add Facebook strategy:
...
var FacebookTokenStrategy = require('passport-facebook-token');
...
exports.facebookPassport = passport.use(new FacebookTokenStrategy({
clientID: config.facebook.clientId,
clientSecret: config.facebook.clientSecret
}, (accessToken, refreshToken, profile, done) => {
User.findOne({facebookId: profile.id}, (err, user) => {
if (err) {
return done(err, false);
}
if (!err && user !== null) {
return done(null, user);
}
else {
user = new User({ username: profile.displayName });
user.facebookId = profile.id;
user.firstname = profile.name.givenName;
user.lastname = profile.name.familyName;
user.save((err, user) => {
if (err)
return done(err, false);
else
return done(null, user);
})
}
});
}
));
Updating users.js
...
router.get('/facebook/token', passport.authenticate('facebook-token'), (req, res) => {
if (req.user) {
var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
2
res.json({success: true, token: token, status: 'You are successfully logged in!'});
}
});
...