0

I am using the below code for google sign in flutter app with firebase, which is working successfully.

How should I check that whether the email id used is already existing in the firebase authentication?

This I need to ensure that I update the user information in the firestore database accordingly.

Future<User> _handleSignIn() async {

    User user;
    bool userSignedIn = await _googleSignIn.isSignedIn();  

    setState(() {
      isUserSignedIn = userSignedIn;
    });

    if (isUserSignedIn) {
      user = _auth.currentUser;
    }
    else {
      final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      user = (await _auth.signInWithCredential(credential)).user;
      userSignedIn = await _googleSignIn.isSignedIn();
      setState(() {
        isUserSignedIn = userSignedIn;
      });
    }

    return user;
  }

Please guide me for this

  • Does this answer your question? [Check if given email exists](https://stackoverflow.com/questions/40093781/check-if-given-email-exists) – Arpit Porwal Nov 30 '20 at 10:06
  • do you want to make user document or data in firestore after login – Yashir khan Nov 30 '20 at 10:07
  • @ArpitPorwal, no it does not answer my question as it is related with Android only, I am working with Flutter app –  Nov 30 '20 at 10:09
  • @Yashirkhan yes, I want to make user document / update data depending upon whether the google-sign in email id already exists or not –  Nov 30 '20 at 10:10

2 Answers2

1

There is a Generic exception related to Firebase Authentication. which is the class FirebaseAuthException. It comes with codes related to errors including email already exists so you would write something like:

try {
 //your signIn method here
//i assumed handleSignIn
handleSignIn();
 
} on FirebaseAuthException catch (e) {
   //exception that occurs if e-mail already exists
   if (e.code == 'email-already-in-use') {
    // the rest of your code here
  }
} 
Ferdinand
  • 513
  • 1
  • 3
  • 9
  • Sorry Ferdinand, I tried the above solution but it didn't resolve the purpose –  Nov 30 '20 at 10:54
1

Then this is the method you should use I have used to solve my problem

this is my auth.dart file

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:gfd_official/User/User.dart';
import 'package:gfd_official/services/database.dart';
import 'package:google_sign_in/google_sign_in.dart';

String photoUrl;

class AuthService {
   final FirebaseAuth _auth = FirebaseAuth.instance;

 // create user obj based on firebase user
Userdat _userFromFirebaseUser(User user) {
return user != null ? Userdat(uid: user.uid) : null;
}

// auth change user stream
 Stream<Userdat> get user {
  return _auth
    .authStateChanges()
    //.map((FirebaseUser user) => _userFromFirebaseUser(user));
    .map(_userFromFirebaseUser);
  }

Future signInWithGoogle() async {
  GoogleSignIn googleSignIn = GoogleSignIn();
  final acc = await googleSignIn.signIn();
  final auth = await acc.authentication;
  final credential = GoogleAuthProvider.credential(
    accessToken: auth.accessToken, idToken: auth.idToken);
try {
  final res = await _auth.signInWithCredential(credential);
  User user = res.user;
  photoUrl = user.photoURL;
  UserHelper.saveUser(user);
  return _userFromFirebaseUser(user);
} catch (e) {
  print(e.toString());
  return null;
}
}

Future logOut() {
try {
  GoogleSignIn().signOut();
  return _auth.signOut();
 } catch (e) {
  print(e.toString());
  return null;
}
}
}

class UserHelper {
  static FirebaseFirestore _db = FirebaseFirestore.instance;

 static saveUser(User user) async {
   Map<String, dynamic> userData = {
   "name": user.displayName,
   "email": user.email,
   "role": "basic",
  };
  try {
  final userRef = _db.collection("users").doc(user.uid);
  if ((await userRef.get()).exists) {
    await userRef.update({});
  } else {
    await _db
        .collection("users")
        .doc(user.uid)
        .set(userData, SetOptions(merge: true));
  }
} catch (e) {
  print(e.toString());
}
}
}

In this the save user function will create database for new user and if user already exist then it will let it remain same as it is. I am creating a document for every user with his/her uid.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Yashir khan
  • 478
  • 4
  • 16
  • Yasir thanks for this answer, but will it not rewrite the same record by using `set` method?? –  Dec 01 '20 at 12:56
  • don't worry it will work you must try as seen it will check if user have data or not if yes it will do nothing with data and get the same data if not then it will create a new document for the user, and as merge is true it will not cause any problem. – Yashir khan Dec 01 '20 at 13:13
  • Yes I tried but it didn't worked for me, then I tried the other way around which resolved the issue –  Dec 05 '20 at 15:49
  • Hey, great can you please tell me that other method. – Yashir khan Dec 15 '20 at 04:16