Full-Stack Web Development with Vue.js and Node

(singke) #1
Building OAuth Strategies with passport.js Chapter 7

const email = profile.emails[0].value;
User.getUserByEmail(email, (err, user) => {
if (!user) {
const newUser = new User({
fullname: profile.displayName,
email,
facebookId: profile.id,
});
User.createUser(newUser, (error) => {
if (error) {
// Handle error
}
return cb(null, user);
});
} else {
return cb(null, user);
}
return true;
});
}));

app.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email'] }));

app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
});
};

While logging in with the Facebook login, if the user already exists in our database, the user
simply gets logged in and saved in the session. The session data is not stored in the browser


cookies but on the server-side itself. If the user doesn't exist in our database, then we create


a new user with the provided email from Facebook.


The last thing to configure here is to add the return URLs or the redirect URL from


Facebook to our application. For this, we can add the URLs in the App Settings page in
Facebook. In the app Settings page, under the Valid OAuth Redirect URIs, add the


redirect URLs to our application from Facebook.

Free download pdf