首页 > 解决方案 > 如何使用 Firebase 发送唯一的注册链接?

问题描述

我想构建一个应用程序,用户可以在其中注册“邀请”。已经拥有帐户的用户可以向指定的电子邮件地址发送邀请,然后应用程序发送一封电子邮件,其中包含指向注册的链接,其中有一个令牌,并且只能使用指定的电子邮件地址。

那么首先,如何从firebase“自动”发送电子邮件,其次,如何为URL生成一个唯一的注册令牌?

标签: javascriptfirebasegoogle-cloud-functions

解决方案


要从 Firebase 发送电子邮件,您可以使用Cloud Function。关于这个主题有一个官方示例:https ://github.com/firebase/functions-samples/tree/Node-8/email-confirmation

正如 Martin Zeitler 所说,您可以使用该push()方法生成唯一令牌并使用相应的电子邮件创建记录。然后当新用户尝试注册时,您可以在注册之前检查他的电子邮件是否与令牌对应。您可以通过不同的方式做到这一点:再次使用云函数,例如使用 HTTPS 云函数(请参阅https://firebase.google.com/docs/functions/http-events)或通过在数据库中创建触发云函数(请参阅https://firebase.google.com/docs/functions/database-events)。在这两种情况下,您都将使用 Admin SDK 注册/创建用户,请参阅https://firebase.google.com/docs/reference/admin/node/admin.auth.Authhttps://firebase.google.com/docs/auth/admin/manage-users#create_a_user

根据您的评论更新

例如,您可以有一个表单,要求受邀用户输入他的电子邮件和他收到的唯一令牌(您可以通过电子邮件中发送的链接打开并预先填写此表单)。提交此表单时,它会在实时数据库中创建一个节点,并且此节点创建将触发一个云函数,该函数:

  • 首先,将检查令牌和电子邮件是否对应(并可能检查它们以前没有使用过)并且;
  • 其次,如果之前的检查没问题,将注册(即创建)用户到您的 Firebase 应用程序。

具体来说,让我们想象一下,在提交表单时,我们创建了以下节点:

- registrationRequests
    -UID
       -email: .....
       -token: .....

您可以按照以下方式使用云功能:

exports.createInvitedUser = functions.database.ref('/registrationRequests/{requestId}')
    .onCreate((snap, context) => {
      const createdData = snap.val();
      const email = createdData.email;
      const token= createdData.token;

      //First action, verify email and token by reading the node of the database where you initially stored the email/token

     //Second action, register the user by using admin.auth().createUser({})
     //See https://firebase.google.com/docs/auth/admin/manage-users#create_a_user

    })

推荐阅读