如何通过云功能了解Firebase身份验证的提供者

时间:2019-02-23 21:21:32

标签: firebase firebase-authentication google-cloud-functions

我正在使用Firebase云功能向用户创建新帐户时向用户发送欢迎电子邮件。仅当用户使用emailAndPassword身份验证创建电子邮件时,才需要发送此欢迎电子邮件,因此我需要了解用户的身份验证提供程序。现在这是我的代码:

    const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

// Your company name to include in the emails
// TODO: Change this to your app or company name to customize the email sent.
const APP_NAME = 'العب .. تعلم';

// [START sendWelcomeEmail]
/**
 * Sends a welcome email to new user.
 */
// [START onCreateTrigger]
exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
// [END onCreateTrigger]
  // [START eventAttributes]
  const email = user.email; // The email of the user.
  const displayName = user.displayName; // The display name of the user.
  // [END eventAttributes]

  return sendWelcomeEmail(email, displayName);
});
// [END sendWelcomeEmail]



// [START sendByeEmail]
/**
 * Send an account deleted email confirmation to users who delete their accounts.
 */
/* TODO :remove this comment to add goodbye email
// [START onDeleteTrigger]
exports.sendByeEmail = functions.auth.user().onDelete((user) => {
// [END onDeleteTrigger]
  const email = user.email;
  const displayName = user.displayName;

  return sendGoodbyeEmail(email, displayName);
});
// [END sendByeEmail]


*/

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

  // The user subscribed to the newsletter.
  mailOptions.subject = `welcome in our app! `;
  const startText = `Welcome in our app! We hope you enjoy it. To know the latest news about the app and the latest competitions please join the following facebook page : `;
  const groupLink = `https://www.facebook.com/2057244580979539/`;
  mailOptions.text = startText + `\n\n` + groupLink;//TODO : add new line instead of space
  return mailTransport.sendMail(mailOptions).then(() => {
    return console.log('New welcome email sent to:', email);
  });
}

此代码将向所有在应用程序中创建电子邮件的用户发送欢迎电子邮件,只有当他使用emailAndPasswordProvider在应用程序中创建新电子邮件时,我才需要向该用户发送电子邮件。

1 个答案:

答案 0 :(得分:0)

您有2个选择: 您可以检查用户记录providerData数组。每个条目都有一个providerId

exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
  console.log(user.providerData[0].providerId); // This will be 'password'
  ...
});

不过,上述内容对于电子邮件链接登录以及电子邮件/密码也具有相同的价值。

另一种选择是使用客户端Node.js SDK并调用:

firebase.auth().fetchSignInMethodsForEmail(user.email)
  .then((signInMethods) => {
    if (signInMethods.indexOf('password') !== -1) {
      // Email corresponds to email/password user.
      // Email link user will have 'emailLink' in the array.
    }
  })