使用Firebase Auth for Google将匿名用户转换为注册用户

时间:2018-04-08 17:12:55

标签: javascript firebase vue.js firebase-authentication

我使用Firebase Auth和VueJS,我需要将anonymous auth user转换为registered one with Google

我在示例中使用此代码:

  fromAnonymousToGoogle: function () {
  // Authenticate with the first user then save the currentUser to a local variable
    var previousUser = Firebase.auth().currentUser

  // Authenticate with a second method and get a credential
    var credential = Firebase.auth.GoogleAuthProvider()

    previousUser.link(credential)
    .catch(function (error) {
     // Linking will often fail if the account has already been linked. Handle these cases manually.
      alert(error)
    })

    // OAuth providers authenticate in an asynchronous manner, so you’ll want to perform the link account link in the callback.
    // previousUser = Firebase.auth().currentUser;
    Firebase.auth().signInWithPopup(new Firebase.auth.GoogleAuthProvider())
     .then(function (result) {
       return previousUser.link(result.credential)
     })
     .catch(function (err) {
       // Handle error
       alert(err)
     })
  },

我尝试将帐户关联到Google时收到此错误:

  

[Vue警告]:事件处理程序错误"点击":" TypeError:this.ta不是函数"

我的代码中没有名为 this.ta 的功能。如何解决此错误?

1 个答案:

答案 0 :(得分:5)

要回答您的上一个问题,您遇到此错误的原因是因为您实际上并未获得var credential = Firebase.auth.GoogleAuthProvider()的凭据,而是提供商ID。因此,当您尝试使用提供者ID link()时,它根本无法正常工作(由于代码的这一部分,我验证了运行相同的错误)。

您实际上不想使用Google凭据登录用户,因为这会签署您的匿名用户并使用Google登录。您只想将当前用户与某些Google凭据相关联,您只需使用linkWithPopup方法即可完成(我重命名变量以使其更有意义)。

fromAnonymousToGoogle: function () {
            // Authenticate with the first user then save the currentUser to a local variable
            var anonUser = Firebase.auth().currentUser

            // Authenticate with a second method and get a credential
            var provider = new Firebase.auth.GoogleAuthProvider();

            anonUser.linkWithPopup(provider).then(function(result) {
                googleToken = result.credential;
                console.log(googleToken);
            }).catch(function(error) {
                console.error("Google sign in failed", error);
            });
    },

我自己对此进行了测试,这似乎是使用popup进行链接的方式,与您最初提供的代码最匹配。