我想在 firebase/firestore 中创建唯一的用户名 [英] I want to make unique usernames in firebase/firestore

查看:28
本文介绍了我想在 firebase/firestore 中创建唯一的用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app : {
    users: {
       "some-user-uid": {
            email: "test@test.com"
            username: "myname"
       }
    },
    usernames: {
        "myname": "some-user-uid"
    }
}

我想创建唯一的用户名,如下所示:我将所有用户名存储在 firebase 的集合中,然后检查具有该用户名的文档是否存在.这工作得很好,但是当我同时在 2 个帐户上创建同名的用户名时,用户 1 生成文件,然后用户 2 覆盖该文件.

I want to make unique usernames, like this: I would store all the usernames in a collection in firebase and than check if that doc with that username exists. This works perfectly fine but when I make a username with the same name on 2 accounts at the same time, user 1 makes the file and then user 2 overwrites that file.

我该如何解决这个问题?

How can I get around this?

这不是所问问题的副本,所有答案都回答了如何制作唯一用户名,但此错误存在于所有答案中.

This is not a copy of an asked question, all the answers answer how to make unique usernames but this bug is in all of them.

推荐答案

为了防止有人能够覆盖现有的用户名文档,您可以使用 Firebase 的安全规则:

To prevent somebody being able to overwrite an existing username document, you'd use Firebase's security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /usernames/{username} {
      allow create: if !exists(/databases/$(database)/documents/usernames/$(username))
    }
  }
}

上面的示例允许创建尚不存在的文档.因此,第二次写入将被拒绝.

The above example allows creating the document if it doesn't exist yet. So with this the second write will be rejected.

您可能希望对此进行扩展,以允许用户仅使用自己的 UID 声明,并且也取消声明名称.要详细了解如何执行此操作,我建议阅读有关 安全规则的 Firebase 文档.

You'll probably want to expand this to allow a user to only claim with their own UID, and unclaim a name too. To learn more on how to do that, I recommend reading the Firebase documentation on security rules.

这篇关于我想在 firebase/firestore 中创建唯一的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆