简体   繁体   English

如何在firebase auth中更改电子邮件?

[英]How to change email in firebase auth?

I am trying to change/update a user's email address using :我正在尝试使用以下方式更改/更新用户的电子邮件地址:

firebase.auth().changeEmail({oldEmail, newEmail, password}, cb)

But I am getting ...changeEmail is not a function error.但我得到...changeEmail 不是函数错误。 I found the referencehere from the old firebase docu.我从旧的firebase文档中找到了参考资料。

So how to I do it in the 3.x version?那么如何在 3.x 版本中做到这一点呢? Because I cant find a reference in the new documentation.因为我在新文档中找不到参考。

You're looking for the updateEmail() method on the firebase.User object: https://firebase.google.com/docs/reference/js/firebase.User#updateEmail您正在firebase.User对象上寻找updateEmail()方法: https ://firebase.google.com/docs/reference/js/firebase.User#updateEmail

Since this is on the user object, your user will already have to be signed in. Hence it only requires the password.由于这是在用户对象上,因此您的用户必须已经登录。因此它只需要密码。

Simple usage:简单用法:

firebase.auth()
    .signInWithEmailAndPassword('you@domain.example', 'correcthorsebatterystaple')
    .then(function(userCredential) {
        userCredential.user.updateEmail('newyou@domain.example')
    })

If someone is looking for updating a user's email via Firebase Admin , it's documented over here and can be performed with:如果有人正在寻找通过Firebase Admin更新用户的电子邮件,它会记录在这里并且可以通过以下方式执行:

admin.auth().updateUser(uid, {
  email: "modifiedUser@example.com"
});

FOR FIREBASE V9 (modular) USERS:对于 FIREBASE V9(模块化)用户:

The accepted answer will not apply to you.接受的答案将不适用于您。 Instead, you can do this, ie, import { updateEmail } and use it like any other import.相反,您可以这样做,即导入{ updateEmail }并像使用任何其他导入一样使用它。 The following code was copy/pasted directly from the fb docs at https://firebase.google.com/docs/auth/web/manage-users以下代码直接从https://firebase.google.com/docs/auth/web/manage-users上的 fb 文档复制/粘贴

Happy coding!快乐编码!

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

You can do this directly with AngularFire2, you just need to add "currentUser" to your path.您可以直接使用 AngularFire2 执行此操作,只需将“currentUser”添加到您的路径。

this.af.auth.currentUser.updateEmail(email)
.then(() => {
  ...
});

You will also need to reauthenticate the login prior to calling this as Firebase requires a fresh authentication to perform certain account functions such as deleting the account, changing the email or the password.您还需要在调用它之前重新验证登录,因为 Firebase 需要重新验证才能执行某些帐户功能,例如删除帐户、更改电子邮件或密码。

For the project I just implemented this on, I just included the login as part of the change password/email forms and then called "signInWithEmailAndPassword" just prior to the "updateEmail" call.对于我刚刚实现的项目,我只是将登录作为更改密码/电子邮件表单的一部分,然后在“updateEmail”调用之前调用“signInWithEmailAndPassword”。

To update the password just do the following:要更新密码,只需执行以下操作:

this.af.auth.currentUser.updatePassword(password)
.then(() => {
  ...
});

updateEmail needs to happen right after sign in due to email being a security sensitive info updateEmail 需要在登录后立即发生,因为电子邮件是安全敏感信息
Example for Kotlin Kotlin 的示例

 // need to sign user in immediately before updating the email 
        auth.signInWithEmailAndPassword("currentEmail","currentPassword")
        .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success now update email                
                    auth.currentUser!!.updateEmail(newEmail)
                        .addOnCompleteListener{ task ->
                        if (task.isSuccessful) {
               // email update completed
           }else{
               // email update failed
                    }
       }
       } else {
                    // sign in failed
                }
            }
async updateEmail() {
const auth = firebase.auth();
try {
  const usercred = await auth.currentUser.updateEmail(this.email.value);
  console.log('Email updated!!')
} catch(err) {
  console.log(err)
}
}

You can use this to update email with Firebase.您可以使用它通过 Firebase 更新电子邮件。

You can use the following with full works like validation and email verification. 您可以将以下内容与验证和电子邮件验证等完整功能结合使用。

Variable Declaration 变量声明

// Widgets
private EditText etOldEmail, etNewEmail;
private Button btnChangeEmail;

// Firebase
private FirebaseAuth mAuth;
private FirebaseUser fbUser;

onCreate onCreate

// Widgets
etOldEmail = findViewById(R.id.a_change_email_et_old_email);
etNewEmail = findViewById(R.id.a_change_email_et_new_email);
btnChangeEmail = findViewById(R.id.a_change_email_btn_change_email);

// Firebase
mAuth = FirebaseAuth.getInstance();
fbUser = mAuth.getCurrentUser();

Function To Change Email Address 更改电子邮件地址的功能

private void changeEmailAddress() {

    String oldEmail = etOldEmail.getText().toString();
    String newEmail = etNewEmail.getText().toString();

    if (TextUtils.isEmpty(oldEmail)) {

        Toast.makeText(mContext, "Please Enter Your Old Email", Toast.LENGTH_SHORT).show();

    } else if (TextUtils.isEmpty(newEmail)) {

        Toast.makeText(mContext, "Please Enter Your New Email", Toast.LENGTH_SHORT).show();

    } else {

        String email = fbUser.getEmail();

        if (!oldEmail.equals(email)) {

            Toast.makeText(mContext, "Wrong Current Email, Please Check Again", Toast.LENGTH_SHORT).show();

        } else {

            fbUser.updateEmail(newEmail).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()) {

                        fbUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                Toast.makeText(mContext, "Verification Email Sent To Your Email.. Please Verify and Login", Toast.LENGTH_LONG).show();

                                // Logout From Firebase
                                FirebaseGeneral firebaseGeneral = new FirebaseGeneral();
                                firebaseGeneral.logoutUser(mContext);

                            }
                        });

                    } else {

                        try {
                            throw Objects.requireNonNull(task.getException());
                        }

                        // Invalid Email
                        catch (FirebaseAuthInvalidCredentialsException malformedEmail) {
                            Toast.makeText(mContext, "Invalid Email...", Toast.LENGTH_LONG).show();

                        }
                        // Email Already Exists
                        catch (FirebaseAuthUserCollisionException existEmail) {
                            Toast.makeText(mContext, "Email Used By Someone Else, Please Give Another Email...", Toast.LENGTH_LONG).show();

                        }
                        // Any Other Exception
                        catch (Exception e) {
                            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();

                        }
                    }

                }
            });

        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM