@@ -182,3 +182,61 @@ function unlink(providerId) {
182182 } ) ;
183183 // [END auth_unlink_provider]
184184}
185+
186+ function accountExistsPopup ( auth , facebookProvider , goToApp , promptUserForPassword , promptUserForSignInMethod , getProviderForProviderId ) {
187+ // [START account_exists_popup]
188+ const { signInWithPopup, signInWithEmailAndPassword, linkWithCredential } = require ( "firebase/auth" ) ;
189+
190+ // User tries to sign in with Facebook.
191+ signInWithPopup ( auth , facebookProvider ) . catch ( ( error ) => {
192+ // User's email already exists.
193+ if ( error . code === 'auth/account-exists-with-different-credential' ) {
194+ // The pending Facebook credential.
195+ const pendingCred = error . credential ;
196+ // The provider account's email address.
197+ const email = error . customData . email ;
198+
199+ // Present the user with a list of providers they might have
200+ // used to create the original account.
201+ // Then, ask the user to sign in with the existing provider.
202+ const method = promptUserForSignInMethod ( ) ;
203+
204+ if ( method === 'password' ) {
205+ // TODO: Ask the user for their password.
206+ // In real scenario, you should handle this asynchronously.
207+ const password = promptUserForPassword ( ) ;
208+ signInWithEmailAndPassword ( auth , email , password ) . then ( ( result ) => {
209+ return linkWithCredential ( result . user , pendingCred ) ;
210+ } ) . then ( ( ) => {
211+ // Facebook account successfully linked to the existing user.
212+ goToApp ( ) ;
213+ } ) ;
214+ return ;
215+ }
216+
217+ // All other cases are external providers.
218+ // Construct provider object for that provider.
219+ // TODO: Implement getProviderForProviderId.
220+ const provider = getProviderForProviderId ( method ) ;
221+ // At this point, you should let the user know that they already have an
222+ // account with a different provider, and validate they want to sign in
223+ // with the new provider.
224+ // Note: Browsers usually block popups triggered asynchronously, so in
225+ // real app, you should ask the user to click on a "Continue" button
226+ // that will trigger signInWithPopup().
227+ signInWithPopup ( auth , provider ) . then ( ( result ) => {
228+ // Note: Identity Platform doesn't control the provider's sign-in
229+ // flow, so it's possible for the user to sign in with an account
230+ // with a different email from the first one.
231+
232+ // Link the Facebook credential. We have access to the pending
233+ // credential, so we can directly call the link method.
234+ linkWithCredential ( result . user , pendingCred ) . then ( ( userCred ) => {
235+ // Success.
236+ goToApp ( ) ;
237+ } ) ;
238+ } ) ;
239+ }
240+ } ) ;
241+ // [END account_exists_popup]
242+ }
0 commit comments