获取现有用户的 Google Firebase

huangapple go评论66阅读模式
英文:

Firebase Get Existing User Google

问题

我想检查用户(在Google登录时)是否已经存在于Firebase中。在我的应用程序中,当用户注册时,我调用了signinwithgoogle,该方法运行我的代码中的以下部分:

Future<User?> signInWithGoogle() async {
  await Firebase.initializeApp();

  User? user;

  if (kIsWeb) {
    GoogleAuthProvider authProvider = GoogleAuthProvider();

    try {
      final UserCredential userCredential =
          await _auth.signInWithPopup(authProvider);

      user = userCredential.user;
    } catch (e) {
      print(e);
    }
  } else {
    try {
      final GoogleSignIn googleSignIn = GoogleSignIn();

      final GoogleSignInAccount? googleSignInAccount =
          await googleSignIn.signIn().catchError((onError) => print(onError));

      if (googleSignInAccount != null) {
        final GoogleSignInAuthentication googleSignInAuthentication =
            await googleSignInAccount.authentication;

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

        try {
          final UserCredential userCredential =
              await _auth.signInWithCredential(credential);

          user = userCredential.user;
        } on FirebaseAuthException catch (e) {
          if (e.code == 'account-exists-with-different-credential') {
            print('The account already exists with a different credential.');
          } else if (e.code == 'invalid-credential') {
            print('Error occurred while accessing credentials. Try again.');
          }
        } catch (e) {
          print(e);
        }
      }
    } catch (e) {
      print(e);
    }
  }

  if (user != null) {
    uid = user.uid;
    name = user.displayName;
    userEmail = user.email;
    imageUrl = user.photoURL;

    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('auth', true);
    prefs.setString('id', user.uid);
    prefs.setString('name', user.displayName!);
  }

  return user;
}

然而,这不告诉我用户是否已经存在。当我调用这个方法时,我希望它告诉我用户是新用户,还是只是意外完成了整个注册过程。如果用户是意外完成注册过程的,那么在使用Google注册时,他应该自动重定向到主页。我该如何检查这一点?

翻译结束,没有代码部分。

英文:

I want to check if the user (when google signing in) already exists in firebase. In my app, when the user signs up, I call signinwithgoogle, which runs this method in my code

Future&lt;User?&gt; signInWithGoogle() async {
  await Firebase.initializeApp();

  User? user;

  if (kIsWeb) {
    GoogleAuthProvider authProvider = GoogleAuthProvider();

    try {
      final UserCredential userCredential =
          await _auth.signInWithPopup(authProvider);

      user = userCredential.user;
    } catch (e) {
      print(e);
    }
  } else {
    try {
      final GoogleSignIn googleSignIn = GoogleSignIn();

      final GoogleSignInAccount? googleSignInAccount =
          await googleSignIn.signIn().catchError((onError) =&gt; print(onError));
      ;

      if (googleSignInAccount != null) {
        final GoogleSignInAuthentication googleSignInAuthentication =
            await googleSignInAccount.authentication;

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

        try {
          final UserCredential userCredential =
              await _auth.signInWithCredential(credential);

          user = userCredential.user;
        } on FirebaseAuthException catch (e) {
          if (e.code == &#39;account-exists-with-different-credential&#39;) {
            print(&#39;The account already exists with a different credential.&#39;);
          } else if (e.code == &#39;invalid-credential&#39;) {
            print(&#39;Error occurred while accessing credentials. Try again.&#39;);
          }
        } catch (e) {
          print(e);
        }
      }
    } catch (e) {
      print(e);
    }
  }

  if (user != null) {
    uid = user.uid;
    name = user.displayName;
    userEmail = user.email;
    imageUrl = user.photoURL;

    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(&#39;auth&#39;, true);
    prefs.setString(&#39;id&#39;, user.uid);
    prefs.setString(&#39;name&#39;, user.displayName!);
  }

  return user;
}

HOWEVER, this doesn't tell me if the user already exists. When I call this method, I want it to tell me if the user is new, or just went through the entire sign up process by accident. If the user went through the sign up process by accident, when signing up with google he should automatically be redirected to the home page. How would I check that?

答案1

得分: 0

你可以使用这个方法:

Future<bool> checkExistUser(String email) async {
  final response = await FirebaseAuth.instance.fetchSignInMethodsForEmail(email);
  return response.isNotEmpty;
}

这段代码对我有效。

英文:

You can use this method:

   Future&lt;bool&gt; checkExistUser(String email) async {
    final response = await FirebaseAuth.instance.fetchSignInMethodsForEmail(email);
    return response.isNotEmpty;
  }

this code works for me.

huangapple
  • 本文由 发表于 2023年5月30日 06:51:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定