Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Auth check if new user on Facebook login

I am creating a web app using Firebase auth to authenticate my users and a MongoDB database to store some relevant user information specific to my site. I am trying to add Facebook as another means of authentication.

Logging in with Facebook is working, but what I want to do is intercept the user generation/authentication with Firebase to check if Firebase is creating a new user on a first-time Facebook login. This way if a new user is being created in Firebase I can also create a new user in my mongo database (essentially handling a signup). My facebook login function looks like this:

handleFacebookLogin() {
 firebase.auth().signInWithPopup(provider).then(function(result) {

  var token = result.credential.accessToken;
  var user = result.user;

  // check if new user here
  // handleNewFacebookUser()

  this.props.update(user);

 }).catch(function(error) {

  var errorCode = error.code;
  var errorMessage = error.message;
  var email = error.email;
  var credential = error.credential;

 });
}

I couldn't find anything that allowed me to check if a new user was being generated in the Firebase docs. It seems to silently handle new Firebase auth user generation when logging in through Facebook for the first time. If there is no built-in way for Firebase to handle this I will just check if the user exists in my database, but I wanted to be sure there wasn't a simpler alternative.

like image 320
AcuteAvocado Avatar asked Feb 26 '18 05:02

AcuteAvocado


1 Answers

You can detect if a user is new or existing as follows:

firebase.auth().signInWithPopup(provider)
  .then(function(result) {
    console.log(result.additionalUserInfo.isNewUser);
  })
  .catch(function(error) {
    // Handle error.
  });

For more on this refer to the documentation.

like image 69
bojeil Avatar answered Oct 07 '22 22:10

bojeil