Firebase:根据用户访问不同的部分

时间:2016-11-11 13:48:11

标签: swift firebase firebase-realtime-database firebase-security

这是我如何允许特定用户访问其分配的商店的方法。宾语。

func shopFetch() {

        self.shop.removeAll()
        let shopRef = FIRDatabase.database().reference().child("shop").child(someIDforShop).child("menu")
        shopRef.observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let something1 = dictionary["some1"]
                let something2 = dictionary["some2"]

                let shopper = Shop(some1: something1, some2: something2)
                self.shop.insert(shopper, at: 0)

                self.collection.reloadData()
            }

            }, withCancel: nil)

    }

这些是我的安全规则

rules: {
  "users": {
    "$uid": {
      ".read": "auth != null || auth.uid == $uid",
      ".write": "auth != null && auth.uid == $uid",
        "$yourShop": {
          ".read": "true"
    }
  },

  "shop": {
    "$yourShop": {
      ".read": "root.child('users').child(auth.uid).child($yourShop).val() == true",
      ".write": "root.child('users').child(auth.uid).child($yourShopManager).val() == true || root.child('users').child(auth.uid).child('isAdmin').val() == true"
      }
   },
}

让我说我的数据库中有这个:

<app-name>: {
    "shop": {
      "shop1": {
        "menu": {
          "some1": "thing1",
          "some2": "thing2"
        }
      },
      "shop2": {
        "menu": {
          "some1": "thing1",
          "some2": "thing2"
        }
      },
      "shop3": {
        "menu": {
          "some1": "thing1",
          "some2": "thing2"
        }
      },
      "users": {
       "K4of4ofp32kfoE": {
         "shop": {
           "shop1": true
         }
      },
      "fj3i53ogF34oGf329ieQ": {
         "shop": {
           "shop2": true
         }
      },

}

我应该在let shopRef的{​​{1}}写一下什么? 这样做,将允许每个用户访问他/她的商店&#39;。我尝试使用someIDforShop,假设它将获取相对于用户的数据,如规则中所指定。但是当childByAutoID()

询问时,shopFetch()没有返回任何内容

1 个答案:

答案 0 :(得分:0)

我找到了为每个用户获取每个商店的变量名称的方法。

import UIKit
import Firebase

let shopVar = ""

override func viewDidLoad() {
    super.viewDidLoad()

    let userReference = DataService.instance.REF_USERS.child((user?.uid)!).child("shop")
        userReference.observe(.value, with: { (snapshot) in       

        if let dict = snapshot.value as? [String:AnyObject] {

                let shopName = dict["name"] as! String
                print(shopName)

                self.shopVar = shopName

            }

        }, withCancel: nil)
}

规则更改

"users": {
       "K4of4ofp32kfoE": {
         "shop": {
           "name": "coolShop"
         }
      },
      "fj3i53ogF34oGf329ieQ": {
         "shop": {
           "name": "fancyShop"
         }
      },
}

然后我替换shopVar - &gt; someIDforShop

中的shopFetch()

现在每个用户都会收到他/她自己的个人“商店”商品。