且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Firestore 中通过电子邮件登录防止创建用户帐户

更新时间:2023-12-04 10:18:16

无密码电子邮件登录允许用户证明他们有权访问某个邮箱.它本质上并没有做更多的事情.一旦用户点击链接,他们就会通过身份验证.除了启用/禁用整个登录提供商之外,您无法控制谁可以登录/验证.

Passwordless email sign in allows the user to prove they have access to a certain mail box. It does inherently do nothing more than that. Once the user clicks the link, they are authenticated. Beyond enabling/disabling the entire sign-in provider, you cannot control who can sign-in/authenticate.

之后,由您的应用程序决定允许该用户做什么.这是一个单独的步骤,通常称为授权.

After that it is up to your application to determine what this user is allowed to do. This is a separate step, typically called authorization.

Firebase 身份验证(顾名思义)仅负责身份验证.您必须在其他地方处理授权,具体取决于您为用户提供哪些服务.

Firebase Authentication takes (as its name implies) care of authentication only. You will have to handle authorization elsewhere, depending on what services you provide the users access to.

是什么让电子邮件在您的应用中注册"了?IE.管理员在哪里创建这些用户?例如,如果您将 Cloud Firestore 中的用户存储在集合 allowed_users,文档如下:

What makes an email "registered" in your app? I.e. where does the admin create those users? For example, if you store the users in the Cloud Firestore in a collection allowed_users, with documents like this:

allowed_users: // collection
  "arkade@domain,com": { ... } // document
  "puf@domain,com": { ... } // document

现在您可以使用 Firestore 的服务器端安全规则限制只有允许的用户才能访问其他数据.假设您有一组 帖子,您可以只允许这些用户阅读帖子:

Now you can limit that only allowed users can access other data with Firestore's server-side security rules. Say you have a collection of posts, you can allow only these users to read posts with:

service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{post} {
      // Make sure a 'allowed_users' document exists for the requesting user before
      // allowing any reads from the 'posts' collection
      allow read: if exists(/databases/$(database)/documents/allowed_users/$(request.auth.email))
  }
}

语法有点长,但您可以看到,如果当前用户的电子邮件地址 (request.auth.email) 作为文档存在于 allowed_users.

The syntax is a bit long, but your can see that is only allows the reading of a post if the current user's email address (request.auth.email) exists as a document in allowed_users.

在 Firestore 规则的第 2 版中,您访问当前用户的电子邮件地址的方式略有不同.您可以通过 request.auth.token.email 来完成.下面的示例还显示了如何在当前用户的文档中获取布尔属性,如果您通过电子邮件识别该用户:

In rules version 2 of the Firestore rules, you access the current user's email address a little differently. You can do it via request.auth.token.email. The example below also shows how you can get a boolean property in the current user's document, if you identify that user by email:

allow write: if get(/databases/$(database)/documents/users/$(request.auth.token.email)).data.admin == true;