How to determine if the user signed in to Firebase with email and password or with google sign in?

馋奶兔 提交于 2019-12-05 00:34:42

问题


I am working on a log in for a web application, and I have made it so the user can sign in manually with their email and password or by using a google sign in. Is there a way to determine which method they used? Preferably by using the Firebase authentication state change function.

`firebase.auth().onAuthStateChanged(firebaseUser => {....`

I know you can tell how they signed in when you go into the Firebase console log but is there a way to determine it using JavaScript code?

When using firebase.auth().currentUser.providerData the following:


回答1:


You can determine by using currentUser https://firebase.google.com/docs/reference/js/firebase.UserInfo

Like this:

firebase.auth().currentUser.providerData[0].providerId

Hope this helps.




回答2:


@mjrdnk's answer is correct, but there is a caveat, a user could have multiple providers linked. So using firebase.auth().currentUser.providerData[0].providerId will always yield the same provider even when another linked provider was used to sign in. The most accurate way to determine the current provider used to sign is by inspecting the ID token's field: firebase.sign_in_provider.




回答3:


Currently @mjdnk asnwer depracated, because it will gives always first provider not the last logged in.

So most recent solution is:

As noted here

var uiConfig = {
        callbacks: {
          signInSuccessWithAuthResult: function(authResult, redirectUrl) {
            var providerId = authResult.additionalUserInfo.providerId;
            localStorage.setItem("firebaseProviderId", providerId)
            //...
          },
          //..
       }

and for display in page

firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
        user.getIdToken().then(function (idToken) {

          $('#user').text(welcomeName + "(" + localStorage.getItem("firebaseProviderId")+ ")");
          $('#logged-in').show();
        }
    }
});


来源:https://stackoverflow.com/questions/47225100/how-to-determine-if-the-user-signed-in-to-firebase-with-email-and-password-or-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!