Raj Dhakad
Raj Dhakad

Reputation: 932

Flutter: How to get Firebase Auth Credentials to update email and password

So, In my flutter app, I am trying to add functionality to change email.

I used userData.updateEmail(email) method, but it gives this error:

Unhandled Exception: PlatformException(ERROR_REQUIRES_RECENT_LOGIN, This operation is sensitive and requires recent authentication. Log in again before retrying this request., null)

On surfing for a solution on the Internet I got to know, I need to reauthenticate user by this method: userData.reauthenticateWithCredential(credential)

But I can't find a way to get credential to pass to reauthenticateWithCredential method.

Some code snippets (tho I feel they are unnecessary):

initUserData() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();

    setState(() {
      userData = user;
    });
  }

updateEmail(String value) async {
    // value is the email user inputs in a textfield and is validated
    userData.updateEmail(value);

  }

Note: I am using both login with google and password-email login.

Upvotes: 7

Views: 22050

Answers (4)

Atri
Atri

Reputation: 66

It is working for me

Future resetEmail(String newEmail) async {
    var message;
    FirebaseUser firebaseUser = await _firebaseAuth.currentUser();
    firebaseUser
        .updateEmail(newEmail)
        .then(
          (value) => message = 'Success',
        )
        .catchError((onError) => message = 'error');
    return message;
  } 

Upvotes: 4

Austris Cirulnieks
Austris Cirulnieks

Reputation: 1179

There is a re-authenticate method. You just need to obtain the user's password for calling the method.

FirebaseUser user = await FirebaseAuth.instance.currentUser();
AuthResult authResult = await user.reauthenticateWithCredential(
  EmailAuthProvider.getCredential(
    email: user.email,
    password: password,
  ),
);

// Then use the newly re-authenticated user
authResult.user

Upvotes: 17

Johanh
Johanh

Reputation: 120

I had this problem too and I found the solution. You can get the AuthCredential for the providers you're using like this:

EmailAuthProvider.getCredential(email: 'email', password: 'password');

and

GoogleAuthProvider.getCredential(idToken: '', accessToken: '')

Both methods return what you're looking for.

Upvotes: 9

Guillaume Roux
Guillaume Roux

Reputation: 7308

When you want to change sensitive informations on Firebase you need to re-authenticate first to your account using your current credentials then you can update it. Currently flutter has no reAuthenticate method for Firebase so you need to call signInWithEmailAndPassword or any other signIn method.

Upvotes: 1

Related Questions