in auth-next/multi-tenancy.js [301:347]
function accountExistsRedirectTenant(auth, samlProvider, googleProvider, goToApp) {
// [START multitenant_account_exists_redirect]
const { signInWithRedirect, getRedirectResult, fetchSignInMethodsForEmail, linkWithCredential } = require("firebase/auth");
// Step 1.
// User tries to sign in to SAML provider.
auth.tenantId = 'TENANT_ID';
signInWithRedirect(auth, samlProvider);
var pendingCred;
// Redirect back from SAML IDP. auth.tenantId is null after redirecting.
getRedirectResult(auth).catch((error) => {
if (error.code === 'auth/account-exists-with-different-credential') {
// Step 2.
// User's email already exists.
const tenantId = error.tenantId;
// The pending SAML credential.
pendingCred = error.credential;
// The provider account's email address.
const email = error.email;
// Need to set the tenant ID again as the page was reloaded and the
// previous setting was reset.
auth.tenantId = tenantId;
// Get sign-in methods for this email.
fetchSignInMethodsForEmail(auth, email)
.then((methods) => {
// Step 3.
// Ask the user to sign in with existing Google account.
if (methods[0] == 'google.com') {
signInWithRedirect(auth, googleProvider);
}
});
}
});
// Redirect back from Google. auth.tenantId is null after redirecting.
getRedirectResult(auth).then((result) => {
// Step 4
// Link the SAML AuthCredential to the existing user.
// result.user.tenantId is 'TENANT_ID'.
linkWithCredential(result.user, pendingCred)
.then((linkResult) => {
// SAML account successfully linked to the existing
// user.
goToApp();
});
});
// [END multitenant_account_exists_redirect]
}