Firebase规则:仅允许特定子节点注册用户写入指定位置
Solution for Dynamic Game Key Write Permissions in Firebase Realtime Database
Absolutely, this is totally achievable with Firebase Realtime Database's flexible security rules! The key here is using wildcard variables (like $gamekey) to handle dynamic game IDs, instead of hardcoding specific keys.
Here's how to structure your rules to meet your exact requirement:
{ "rules": { "liveLocations": { ".read": "auth != null", "$gamekey": { "$uid": { ".write": "auth != null && $uid === auth.uid && exists(/databases/$(database)/games/$gamekey/players/$uid)" } } }, "games": { "$gamekey": { "players": { // Adjust this based on how users register for games // Example: Allow users to add themselves to a game's players list "$uid": { ".write": "auth != null && $uid === auth.uid" } } } } } }
Breakdown of the Rules:
- Wildcard
$gamekey: This matches any dynamic game ID in theliveLocationsnode, so you don't need to hardcode specific keys like-LA3H25IA1hiyxL-TCWE. - Write Permission Checks:
auth != null: Ensures only authenticated users can write.$uid === auth.uid: Guarantees users can only write to their own UID node under the game'sliveLocationspath.exists(/databases/$(database)/games/$gamekey/players/$uid): Verifies the user has "registered" by checking their UID exists in the correspondinggames/$gamekey/playersnode.
Notes:
- If your
playersnode uses a different structure (e.g., storing player objects with auidfield instead of using UIDs as keys), you'll need to adjust theexists()check. For example, if each player entry has auidproperty, you could use a query-based check—but using UIDs as direct keys is more efficient for this scenario. - Make sure your
games/$gamekey/playersrules allow users to register themselves (or be added by an admin) first—otherwise theexists()check will always fail.
内容的提问来源于stack exchange,提问作者Maor
相关产品推荐
相关产品推荐

