Friday, 28 September 2018

Only authenticate with Google Auth Provider if user exists

I am using Firebase to authenticate users in our app using GoogleAuthProvider. But I don't want a new user to sign in if they are not already an authenticated user.

If the user exists then sign them in and console.log('user ' + user.email + ' does exist!');.

However, if the user does not exist. Then do not allow authentication and console.log('user ' + user.email + ' does not exist!')

var googleProvider = new firebase.auth.GoogleAuthProvider();
export const doSignInWithGoogle = () => auth.signInWithPopup(googleProvider);

googleLogin = () => {
    auth
      .doSignInWithGoogle()
      .then(result => {
        var user = result.user;
        const userRef = db.collection('users').doc(user.uid);
        userRef.get().then(docSnapshot => {
          if (docSnapshot.exists) {
            userRef.onSnapshot(() => {
              console.log('user ' + user.email + ' does exist!');
            });
          } else {
            console.log('user ' + user.email + ' does not exist!');
          }
        });
      })
      .catch(error => {
        this.setState(updateByPropertyName('error', error));
      });
  };

I thought referencing the user records in Firestore would be a simple approach to this. However, perhaps Firebase Auth already have a way to do this. I cannot find documentation or any example.

In the above code, nothing gets logged and the user is either created or logged in.

How can I stop new users from signing up, whilst still allowing current users to sign in?



from Only authenticate with Google Auth Provider if user exists

No comments:

Post a Comment