Skip to content

Instantly share code, notes, and snippets.

@TahaBoulehmi
Last active April 2, 2018 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TahaBoulehmi/3110266e2fbbeaff01ed9d21ebd0333d to your computer and use it in GitHub Desktop.
Save TahaBoulehmi/3110266e2fbbeaff01ed9d21ebd0333d to your computer and use it in GitHub Desktop.
Facebook Authentication using Sails.js
facebookAuth: function(req, res) {
//You need to add the fb signup button in the frontend, and post the token that you got from facebook to the backend.
if (_.isUndefined(req.param('facebookToken'))) {
return res.json({
success: false,
msg: 'Please log in using your facebook account'
});
}
// Get information about the Facebook user with the specified access token.
FacebookOauth.getUserByAccessToken({
access_token: req.param('facebookToken'),
fields: 'email, picture, name, verified',
}).exec({
// An unexpected error occurred.
error: function (err) {
return res.json({
success: false,
msg: 'Wrong token'
});
},
// OK.
success: function (result) {
if (result.verified == false) {
return res.json({
success: false,
msg: 'Your facebook account is not verified'
});
}
else {
User.findOne({email: result.email}).exec(function(err, foundUser) {
if (err) {
return res.json({
success: false,
msg: 'Server error'
});
}
if (!foundUser) {
//Signup and login
req.session.userId = createdUser.id;
var data = {
success: true,
msg: "Account created"
};
return res.json(data);
}
else { //Only login
if (foundUser.deleted) {
return res.json({
success: false,
msg: 'You can not login to this account'
});
}
if (foundUser.banned) {
return res.json({
success: false,
msg: 'You can not login to this account.'
});
}
req.session.userId = foundUser.id;
var data = {
success: true
}
return res.json(data);
}
});
}
},
});
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment