Miguel Lara
Miguel Lara

Reputation: 233

How to send an email for use in Firebase's "EmailAuthProvider.credentialWithLink()"?

I'm using Firebase in an Angular 7 app, in order to allow users to login with the email/link option.

Now I need to allow users to delete their own account if they want.

Before permit the user delete the account I should re-authenticate it using a "credential".

To get that credential, I need to use

firebase.auth.EmailAuthProvider.credentialWithLink(email, emailLink) 

The first parameter "email" is already stored in localStorage, but I don't know how to obtain the second parameter "emailLink".

const user = firebase.auth().currentUser;
const credential = firebase.auth.EmailAuthProvider.credentialWithLink(
      '[email protected]',
      'HOW TO GET THIS PARAM???'
    );

user
.reauthenticateAndRetrieveDataWithCredential(credential)
.then(function() {
        // DELETE USER HERE.
      });

I need to know the process of obtaining the "emailLink" parameter. Thanks.

Upvotes: 1

Views: 992

Answers (2)

Long.H
Long.H

Reputation: 61

The example is kinda confusing but I figured it out. After the user is redirected from the sign-in link, the user should continue from that window. So at the browser window.location.href will receive a new URL from Firebase. You can use it to create credential and keep continue from here.

Upvotes: 0

bojeil
bojeil

Reputation: 30838

Email link sign-in consists of 2 steps:

You need to first send the email link.

const linkId = randomId();
const actionCodeSettings = {
  url: 'https://www.example.com/finishSignUp?linkId=' + linkId,
  // This must be true.
  handleCodeInApp: true
};

firebase.auth().sendSignInLinkToEmail(email, actionCodeSettings)
  .then(function() {
    window.localStorage.setItem('emailForSignIn', email);
    window.localStorage.setItem('linkId', linkId);
  })
  .catch(function(error) {
    // Some error occurred, you can inspect the code: error.code
  });

You then need to complete sign-in or re-auth with the link which contains an OTP on the page https://www.example.com/finishSignUp.

You should confirm the email was opened on the same device and is an email sign-in link:

if (firebase.auth().currentUser &&
    firebase.auth().currentUser.email === window.localStorage.getItem('emailForSignIn') &&
    firebase.auth().isSignInWithEmailLink(window.location.href) &&
    window.localStorage.getItem('linkId') === getLinkIdFromUrl()) {
  // Complete sign-in and re-auth.
}

In the case of re-auth:

const credential = firebase.auth.EmailAuthProvider.credentialWithLink(
  window.localStorage.getItem('emailForSignIn'),
  window.location.href
);

user.reauthenticateAndRetrieveDataWithCredential(credential)
  .then(function() {
    return user.delete();
  });

Upvotes: 1

Related Questions