我有以下数据结构:

cars: {
  $uid: {
     brand: "Brand here",
     model: "Model here etc"
   },
   $uid: {
     brand: "Another brand here",
     model: "Another model here etc"
   }
}


任何人都可以读取此数据,例如:firebase.com/cars/uniqueIDHere.json-这是一个公共API
firebase.com/cars.json-无法访问。

现在,规则设置如下:

"cars": {
      "$uid": {
        ".read": "true",
        ".write": "auth != null"
    }
}  


我想要以下授权规则:只有创建“汽车”的用户才可以编辑/删除它。
有了现在的规则,我认为所有登录的用户都可以这样做(如果他们知道汽车的$ uid)。
可以制定什么规则,以便只有所有者才能“编写”。我知道以下规则:

"$uid": {
   ".read": "true",
   ".write": "auth.uid === $uid"
}


$ uid是用户的uid,但我不希望这样做,因为它将在公共API URL中公开
我可以采取什么方法?有任何想法吗?

最佳答案

我认为您需要将用户和汽车分开。

像这样的结构:

root
 |
 +-- cars
 |     |
 |     +-- $carId
 |           |
 |           +-- brand: $brand
 |           |
 |           +-- model: $model
 |
 +-- users
 |     |
 |     +-- $userId
 |           |
 |           +-- cars
 |                 |
 |                 +-- $carId: true


规则将如下所示:

{
    "rules": {
        "cars": {
            "$carId": {
                ".read": "true",
                ".write": "auth != null && root.child('users').child(auth.uid).child("cars").child($carId).val() === true"
            }
        },
        "users": {
            "$userId": {
                ".read": "auth != null && auth.uid === $userId",
                ".write": "auth != null && auth.uid === $userId"
            }
        }
    }
}

07-24 19:11
查看更多