【问题标题】:How should i structure my firestore security rules?我应该如何构建我的 Firestore 安全规则?
【发布时间】:2021-08-30 06:36:40
【问题描述】:

我正在制作一个基于网络的小井字游戏,作为一个项目展示在我的投资组合网站上。我希望访问该网站的人能够创建游戏,然后另一个玩家加入该游戏。

创建游戏的人在我的 Firestore 数据库中的“游戏”集合下创建一个文档,该集合由该接口定义:

type Player = 'x' | 'o'
type GameFieldValue = null | Player;
type Coordinate = [number, number]
type Row = [GameFieldValue, GameFieldValue, GameFieldValue];

interface IGameDoc {
    playerTurn: Player;
    playerTwoUid: string | null
    gameState: {
        rowOne: Row
        rowTwo: Row
        rowThree: Row
    };
}

文档与创建游戏的用户的 ID 一起存储,例如

因此,我的 firebase firestore 中创建游戏的规则就是您需要登录(我只是在有人访问该网站时匿名登录)

rules_version = '2';
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
  match /databases/{database}/documents {

    match /Games/{gameId} {
      

      allow read, write: if request.auth != null;
      
    }
  }
}

现在玩家可以将 gameId 发送给其他可以加入游戏的人。然后两个玩家可以监听游戏状态的实时更新并相应地更新 UI。

现在我的问题是弄清楚如何让第二个玩家加入游戏。

第二个玩家最初需要能够更新文档并将他的 uid 插入到playerTwo 字段中。在后续请求更新文档时,应该只允许创建游戏的玩家以及第二个玩家这样做。

我希望我在这里表达清楚了。

谁能帮助我如何构建我的 Firestore 规则来实现这一点?

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore firebase-security


    【解决方案1】:

    听起来你正在寻找这个:

    allow create: if (resource.data.player1 == request.auth.uid);
    allow update: if (resource.data.player2 == null && request.resource.data.player2 == request.auth.uid)
                  || (resource.data.player1 == request.auth.uid)
                  || (resource.data.player2 == request.auth.uid)
    

    换句话说:如果您将自己的 UID 设置为 player1,则允许创建文档,如果您是 player1player2,则允许更新文档,或者如果有还没有player2,您将自己设置为player2

    【讨论】:

    • 这完全有道理。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2019-07-05
    • 2021-03-15
    • 2021-04-21
    • 2021-03-17
    • 2023-02-09
    • 2020-06-19
    • 1970-01-01
    相关资源
    最近更新 更多