【问题标题】:Sending Verification email to existing users向现有用户发送验证电子邮件
【发布时间】:2021-05-12 20:09:18
【问题描述】:

我正在开发一个拥有现有用户群的网络应用程序。电子邮件验证最初并未在登录流程中实施。
我已经成功添加了为所有新注册发送验证电子邮件的代码,但我还想制作一个小页面(或模态),当前用户将看到一个按钮,将验证链接发送到他们的收件箱

我使用createUserWithEmailAndPassword 创建用户的当前注册流程我能够访问user.user.sendEmailVerification 方法来执行此操作,但找不到任何方法来访问此方法以实现现有用户的功能。

有没有办法在创建用户后访问sendEmailVerification 方法?

我假设它在 onAuthStateChange 触发器中可用,但实施这将导致糟糕的用户体验(因为我不想在用户每次登录时都提示他们)

编辑:

我知道文档声明我们可以使用firebase.auth().currentUser 来获取当前用户,但是,由于某种原因不起作用。 另外,我在网上发现 references 建议不再使用该方法,他们提到改用 onAuthStateChange 方法,这就是我研究这种方法的原因

【问题讨论】:

    标签: firebase authentication firebase-authentication email-verification


    【解决方案1】:

    你可以试试这个方法:

    const btnVerifyEmail = document.getElementById("btn-verify-id")
    btnVerifyEmail.onclick = function () {
      const user = firebase.auth().currentUser;
    
      user.sendEmailVerification().then(function() {
        // Email sent.
        console.log("Email Sent")
      }).catch(function(error) {
        // An error happened.
        console.log(error)
      });
    }
    

    在文档中提到过here

    【讨论】:

    • 我知道那里提到了它,但这不起作用。后来发现大部分人都有这个问题,一般建议不要这样使用,而是使用onAuthStateChange。编辑问题以解释相同
    【解决方案2】:

    不应在onAuthStateChanged 事件中调用sendEmailVerification(),因为如果用户的电子邮件未经过验证,它会在每次页面加载时爆出一封电子邮件。

    如果User.emailVerified 为假,您应该在页面上显示一条通知,其中包含用于向用户发送电子邮件的链接。

    这是一个工作示例:

    // On page load watch for auth state changes
    firebase.auth().onAuthStateChanged(function(user) {
        // If the user is logged in
        if (user) {
            // If the user's email isn't verified
            if (!user.emailVerified) {
                // Show the notification bar that informs the user that they need to validate
                // their email by clicking a link.  Let's pretend the link looks like this:
                // <a href="#" onclick="sendEmailVerification">Send me a verification email</a>
                showNotification();
            }
        }
    });
    
    // Function attached to your link's onclick event
    function sendEmailVerification() {
        // Retrieve the current user
        const user = firebase.auth().currentUser;
    
        // If user's email is already verified, exit
        if (user.emailVerified) {
            return;
        }
    
        // Tell Firebase to send the verification email and discard the promise
        user.sendEmailVerification().then().catch();
    }
    

    Dharmaraj 的回答很好,但这是一个完整的例子。

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2019-10-29
      • 2014-09-18
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 2019-05-11
      相关资源
      最近更新 更多