【问题标题】:Firebase Node.JS Admin SDK send verification emailFirebase Node.JS Admin SDK 发送验证电子邮件
【发布时间】:2018-01-01 15:09:38
【问题描述】:

我正在使用 sdk 为该用户创建一个用户和一个数据库条目,这一切都可以完美运行。在创建数据库条目后,我调用了一个函数 sendEmailVerification() 但我猜这是一个客户端函数,因为它在被调用时返回 null。

直接从 admin sdk 发送验证电子邮件的过程是什么(如果可能的话)。目前我所做的是将一些 JSON 发送回客户端,以说明验证电子邮件是否发送成功。但是调用该函数不起作用,所以它没有那么远。这是我在节点中的函数。

function verifiyEmail(email, res) {

    var user = admin.auth().currentUser;
    user.sendEmailVerification().then(function() {


        // Email sent.
        var jsonResponse = {

            status: 'success',
            alertText: '1',
            email: email
        }

        res.send(jsonResponse); 

    }, function(error) {

        // An error happened.
        var jsonResponse = {

            status: 'success',
            alertText: '0',
            email: email
        }

        res.send(jsonResponse); 

    });

}

更新

我猜这是不可能的,所以我在节点中生成了一个自定义令牌并将其发送回客户端。然后,我使用返回的令牌尝试通过调用以下命令登录用户,但不会调用 signInWithCustomToken() 函数。这是我的代码我错过了什么。发送验证邮件似乎需要做很多工作!

function signInUserWithToken(token) {

    firebase.auth().signInWithCustomToken(token).catch(function(error) {

      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;

      console.log(errorCode);
      console.log(errorMessage);

      verifiyEmail();

    });
}

更新 2

我放弃了令牌的想法。我现在所做的就是使用 onAuthStateChanged() 函数并在客户端实现中处理电子邮件验证。它并不完美,因为此方法被多次调用。但是,添加标志似乎可以解决问题。如下所示。

function authListenerContractor() {
  // Listening for auth state changes.
  $('#not-verified').css('display','none'); 
  var flag = true;
  firebase.auth().onAuthStateChanged(function(user) {

        if (user) {

            // User is verified.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            console.log("Email Verified?: " + emailVerified);

            if(emailVerified) {

                  window.location.href = "http://www.my-redirect-url.com";

            } else {

                if (flag == true) {

                    $('#not-verified').css('display','inherit');
                    verifiyEmail();

                    flag = false;
                }
            }

        } else {

            console.log("User is signed out.");
        }
   });
 }

function verifiyEmail() {

    var user = firebase.auth().currentUser;
    user.sendEmailVerification().then(function() {

        // Email sent.
        console.log("Verification email sent");
        $('#not-verified').text('**Email verification sent. Please check your email now!**');

    }, function(error) {

        // An error happened.
        console.log("Email verification not sent. An error has occurred! >>" + error);

    });
}

【问题讨论】:

  • 您想在 firebase 数据库中创建某些内容后向用户发送验证吗?
  • @RahulSingh 是的,没错。
  • 您正在使用 Firebase 云功能?
  • @RahulSingh 不确定我是否关注。我只使用 node.js firebase 管理模块。
  • Node.js Admin SDK 中存在一个请求此功能的未解决问题:github.com/firebase/firebase-admin-node/issues/46。留意那张票可能会很有用。

标签: node.js firebase firebase-authentication firebase-admin


【解决方案1】:

这是使用Firebase Cloud Functions的经典案例

发送欢迎邮件示例

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
    `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);


const APP_NAME = 'My App';


exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {

  const user = event.data; // The Firebase user.

  const email = user.email; // The email of the user.
  const displayName = user.displayName; // The display name of the user.


  return sendWelcomeEmail(email, displayName);
});

function sendWelcomeEmail(email, displayName) {
  const mailOptions = {
    from: `${APP_NAME} <noreply@firebase.com>`,
    to: email
  };

  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey ${displayName || ''}! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New welcome email sent to:', email);
  });
}

查看此Link 了解更多信息,使用这些功能在此应用中触发邮件

更新

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');


const mailTransport = nodemailer.createTransport(
  `smtps://emailid:password@smtp.gmail.com`);

const APP_NAME = 'My App';

exports.sendPageCountEmail = functions.database.ref('/yournode').onWrite(event => { // here we are specifiying the node where data is created
    const data = event.data;
    return sendEmail('emailid',data);
});


// Sends a welcome email to the given user.
function sendEmail(email,body) {
  const mailOptions = {
    from:`${APP_NAME}noreply@firebase.com`,
    to: email
  };

  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Welcome to ${APP_NAME}.\n 
  return mailTransport.sendMail(mailOptions).then(() => {
      console.log('New welcome email sent to:', email);
});
}

【讨论】:

  • 谢谢。对于其他发送的电子邮件,我可能有一个用例。但我的问题只是管理员 sdk 是否有这样的功能来发送验证电子邮件,就像用户注册时客户端所做的那样,因为调用它不起作用,而且在我看来很愚蠢,考虑到这是一个“管理员”,这不会提供" sdk
  • @AlexMcPherson 当每个数据都添加到特定节点的 firebase 数据库时,它也可以发送电子邮件。更新一个这样的例子
  • 那太好了,但是我将如何在电子邮件中发送验证链接?与使用 sendEmailVerification() 函数一样,会在电子邮件正文中发送一封带有验证链接的电子邮件。如果要使用此方法,如何生成该链接?
  • 可以在创建的时候保存在节点中,然后在这个答案中触发这个函数event.data;时使用。检查该链接,它将解释如何创建此类功能并将其部署到 firebase 数据库
  • 对不起,我真的不按照我理解的 firebase 控制验证链接。简单地说,我的问题是仅使用 firebase admin sdk 即可。我不想发送欢迎电子邮件,它是 Firebase 发出的实际验证链接。
猜你喜欢
  • 2017-06-12
  • 2017-11-16
  • 2019-06-24
  • 2018-11-21
  • 1970-01-01
  • 2017-09-09
  • 2020-12-12
  • 2020-08-06
  • 2023-03-24
相关资源
最近更新 更多