处理Firebase中的关联帐户 [英] Handling linking accounts in Firebase

查看:214
本文介绍了处理Firebase中的关联帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Firebase关于社交登录的说明。下面是我正在使用的一个例子,从登录认证的角度来看,这一切都工作正常。



但是,Google和Facebook登录都是独立工作的。 / p>

现在我想要做的是链接帐户。你可以在下面看到这个可能会发生的地方( ):
$ b


如果你使用多个


我已经尝试了许多我认为应该放在这里的变体,但无济于事。任何人都可以指导我关于他们认为应该去的地方吗?

 函数initFBApp(){
//来自重定向认证流程的结果。
// [START getidptoken]
firebase.auth()。getRedirectResult()。then(function(result){
if(result.credential){
//你可以使用它来访问Facebook API
var token = result.credential.accessToken;
// [START_EXCLUDE]
document.getElementById('FBquickstart-oauthtoken ').textContent = token;
}
else {
document.getElementById('FBquickstart-oauthtoken')。textContent ='null';
// [END_EXCLUDE]

//登录用户信息
var user = result.user;
})catch(function(error){
// Handle Errors here 。
var errorCode = error.code;
var errorMessage = error.message;
//使用的用户帐户的电子邮件
var email = error.email;
// firebase.auth.AuthCredential类型那是用过的
var credential = error.credential;
// [START_EXCLUDE]
if(errorCode ==='auth / account-exists-with-different-credential'){
alert('您已经注册了一个不同的auth该电子邮件的提供者。');
//如果您在应用程序中使用多个授权提供程序,则应该在此处处理
//用户帐户的链接。
}
else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END getidptoken]
//监听auth状态变化。
// [START authstatelistener]
firebase.auth()。onAuthStateChanged(函数(用户){
if(user){
//用户登录
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user。 isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// [START_EXCLUDE]
document.getElementById('FBquickstart-sign-in-status' ).textContent ='签入';
document.getElementById('FBquickstart-sign-in')。textContent ='注销';
document.getElementById('FBquickstart-account-details')。 textContent = JSON.stringify(user,null,'');
// [END_EXCLUDE]
}
else {
//用户退出
// [START_EXCLUDE]
document.getElementById('FBquickstart-sign-in-status')。textContent ='已注销';
document.getElementById('FBquickstart-sign-in')。textContent ='用Facebook登录';
document.getElementById('FBquickstart-account-details')。textContent ='null';
document.getElementById('FBquickstart-oauthtoken')。textContent ='null';
// [END_EXCLUDE]
}
// [START_EXCLUDE]
document.getElementById('FBquickstart-sign-in')。disabled = false;
// [END_EXCLUDE]
});
// [END authstatelistener]
document.getElementById('FBquickstart-sign-in')。addEventListener('click',toggleFBSignIn,false);


解决方案

如何处理auth / account-exists-with-different-credential:
如果您登录到使用已存在的其他帐户的电子邮件的新Facebook帐户,将会出现该错误。假设现有的帐户是一个Google帐户。



您将在 getRedirectResult()。catch中捕获该错误(function(error){})



错误还会包含电子邮件和凭证字段。
您将需要保存凭据(使用推荐的sessionStorage)。检查这个帖子的更多内容:
Firebase身份验证Javascript:setCookie for pending Credential for redirect


$ b 然后您可以调用firebase.auth()。fetchProvidersForEmail(error.email) 确定该电子邮件已经存在的提供者。

然后,您将登录到其中一个现有提供程序,并声明该电子邮件与error.email相同。成功的话,你将会从sessionStorage中加载未完成的凭证,并按照其他文章中的描述进行重新初始化,并将其链接到当前用户:

  firebase.auth()currentUser.link(savedCred)。 

现在您将拥有两个帐户关联。请记住,现有的提供者可能是密码类型。在这种情况下,您不需要保存凭据,只需要求用户输入密码并使用相同的电子邮件error.email登录即可。然后你可以直接用error.credential调用链接。

顺便说一下,我建议firebaseui-web为你处理所有这些:
https://github.com/firebase/firebaseui-web


I am following Firebase's instruction on social login. Below is an example of what I am using and it is all working fine from a login authentication perspective.

I have, however, both Google and Facebook login working independently.

What I would like now to be able to do is link the accounts. You can see below in fact where this might go (see the comment):

If you are using multiple auth providers on your app you should handle linking the user's accounts here.

I have tried many variations of what I think should go here, but to no avail. Can anyone guide me in relation to what they think should go here? Thanks!

function initFBApp() {
    // Result from Redirect auth flow.
    // [START getidptoken]
    firebase.auth().getRedirectResult().then(function (result) {
        if (result.credential) {
            // This gives you a Facebook Access Token. You can use it to access the Facebook API.
            var token = result.credential.accessToken;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-oauthtoken').textContent = token;
        }
        else {
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // The signed-in user info.
        var user = result.user;
    }).catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // [START_EXCLUDE]
        if (errorCode === 'auth/account-exists-with-different-credential') {
            alert('You have already signed up with a different auth provider for that emails.');
            // If you are using multiple auth providers on your app you should handle linking
            // the user's accounts here.
        }
        else {
            console.error(error);
        }
        // [END_EXCLUDE]
    });
    // [END getidptoken]
    // Listening for auth state changes.
    // [START authstatelistener]
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            // User is signed in.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed in';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log out';
            document.getElementById('FBquickstart-account-details').textContent = JSON.stringify(user, null, '  ');
            // [END_EXCLUDE]
        }
        else {
            // User is signed out.
            // [START_EXCLUDE]
            document.getElementById('FBquickstart-sign-in-status').textContent = 'Signed out';
            document.getElementById('FBquickstart-sign-in').textContent = 'Log in with Facebook';
            document.getElementById('FBquickstart-account-details').textContent = 'null';
            document.getElementById('FBquickstart-oauthtoken').textContent = 'null';
            // [END_EXCLUDE]
        }
        // [START_EXCLUDE]
        document.getElementById('FBquickstart-sign-in').disabled = false;
        // [END_EXCLUDE]
    });
    // [END authstatelistener]
    document.getElementById('FBquickstart-sign-in').addEventListener('click', toggleFBSignIn, false);
}

解决方案

These are roughly the steps on how to handle auth/account-exists-with-different-credential: You will get that error if you are signing in to a new Facebook account that uses the email of another account that already exists. Let's say the existing account is a google account.

You will get that error in getRedirectResult().catch(function(error) {})

The error will also contain an email and credential field. You will need to save the credential (using the recommended sessionStorage). Check this post for more on that: Firebase Authentication Javascript: setCookie for pending Credential for redirect

You then call firebase.auth().fetchProvidersForEmail(error.email) to determine the providers that already exist for that email.

You will then sign in to one of those existing providers and assert that the email is the same as error.email. On success, you will load the pending credential from sessionStorage, re-initialize as described in the other post and link it to the currentUser:

firebase.auth().currentUser.link(savedCred);

You will now have both accounts linked. Keep in mind the existing provider could be a password type. In that case you don't need to save the credential, you just ask the user for the password and sign them in using the same email error.email. You can then call link directly with the error.credential.

BTW, I recommend firebaseui-web which takes care of all this for you: https://github.com/firebase/firebaseui-web

这篇关于处理Firebase中的关联帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆