Flutter Google Sign in data save to Firebase Cloud Firestore

Viewed 2781

I've implemented google_sign_in package in my flutter application. I'm registering with google and saving the data in Cloud Firestore Database. I can save the data properly.

What I want is that, the next time someone try use register with google again with the same email it will check from database and show that he already have an account and ask to 'login' with google instead.

The reason I'm trying to do this is that, I will update the user data and logout.

And if I login/register again with the same Google email it replaces my updated data with details from google profile. I want the updated data in the Firestore to stay, not update each time I login.

Can anyone help me with this please. Thanks!

2 Answers

This Function returns true if the user is new , already stored in users collection

`Future<bool> isNewUser(FirebaseUser user) async {
QuerySnapshot result = await firestore
        .collection("users")
        .where("email", isEqualTo: user.email)
        .getDocuments();
    final List<DocumentSnapshot> docs = result.documents;
    return docs.length == 0 ? true : false;
  }`

first cheek if the users is new using the above function the if the user is new add the user detail to users collection like

`Future<void> addUserToDb(FirebaseUser currentuser) async {
    user = User(
        uid: currentuser.uid,
        email: currentuser.email,
        name: currentuser.displayName,
        profilePhoto: currentuser.photoUrl,
         );
    firestore
        .collection("users")
        .document(currentuser.uid)
        .setData(user.toMap(user));
  }`

and if the user is not a new user show login screen

there are basically several methods, I will describe ones I know here

1) firebase_auth

Actually it should be handled automatically by Firebase (unless you use the second option, http requests)

But generally firebase_auth should do the trick

authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );

Then if you put that in try {} on PlatformException catch(error) {} block you can tap into it by error.message to get the human readable message

2) http request

Or, if you like to do it through http request

You will need to handle it manually

await Provider.of<Auth>(context, listen: false).signup(
          _authData['email'],
          _authData['password'],
        );

Also, if you put that in try {} on HttpExceptions catch(error) {} block you can tap into it by error.toString().contains(ERROR_TYPE) (where ERROR_TYPE can be ERROR_INVALID_EMAIL, INVALID_EMAIL, or ERROR_EMAIL_ALREADY_IN_USE, etc.) and define your cases manually.

All in all, I would recommend the first option as it removes many burdens from you

Hope it helps!

Related