2

I am trying to get the multiples auth to link using singinwithredirect. I grab the error .credential and use JSON.stringify to pass it through a cookie.

From there, I convert it back to an object by using JSON.parse, but when I tried to pass the credential object into result.user.link(credential), it's giving me an error stating:

firebase.js:74 Uncaught Error: link failed: First argument "credential" must be a valid credential

Do I have to convert JSON object into a Firebase object in order to pass it in the credential? What the object originally looks like:

Ef {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}

What the object looks like after converting back to JSON from cookie ('string'):

Object {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}
AL.
  • 36,815
  • 10
  • 142
  • 281
Max Stride
  • 63
  • 3

2 Answers2

4

First I recommend that you use sessionStorage instead of cookies as this contains an OAuth access token which you don't want to leak on page close.

After you parse the json object. Check the provider field. Based on that you can figure out what type of credential it is. For example if provider is facbeook.com:

var cred = firebase.auth.FacebookAuthProvider.credential(obj['accessToken');

In that case you would initialize the credential with the accessToken in the parsed object.

bojeil
  • 29,642
  • 4
  • 69
  • 76
3

You should be careful to remove cached accessToken and secret after you are done with them.

The parsed JSON is possibly not a valid firebase object to link the pending credentials. You must pass it into the firebase auth provider object first before linking.

// Read cookie
var pendingCred = document.cookie;

// Parse
var pendingCredObj = JSON.parse(pendingCred);

// Delete cookie
document.cookie ="pendingCred=" + null + "; expires=0";

// Link with appropriate auth provider object
if (pendingCredObj.provider == "twitter.com"){
    var pendingCredObjProv = firebase.auth.TwitterAuthProvider.credential(pendingCredObj.accessToken, pendingCredObj.secret);
} else if (pendingCredObj.provider == "facebook.com"){
    var pendingCredObjProv = firebase.auth.FacebookAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "google.com"){
    var pendingCredObjProv = firebase.auth.GoogleAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "password"){
    var pendingCredObjProv = firebase.auth.EmailAuthProvider.credential(pendingCredObj);
}

// Link pending credentials to original user account
auth.currentUser.link(pendingCredObjProv).then(function(user) {
    console.log("Account linking success", user);
}, function(error) {
    console.log("Account linking error", error);
});
imparante
  • 503
  • 9
  • 21