Firebase Node.JS Admin SDK发送验证邮件

时间:2017-07-26 10:37:08

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

我正在使用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);

    });
}

1 个答案:

答案 0 :(得分: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);
});
}