[英]How should i structure my firestore security rules?
我正在制作一個基於 web 的小井字游戲作為項目,以在我的投資組合網站上展示。 我希望訪問該網站的人能夠創建游戲,然后另一個玩家加入該游戲。
創建游戲的人在我的 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 規則來實現這一目標?
聽起來你正在尋找這個:
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
,則允許創建文檔,如果您是player1
或player2
,或者如果還沒有player2
並且您正在設置自己,則允許更新文檔作為player2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.