如何使用Firebase规则来允许用户和管理员写入权限?

时间:2016-09-20 19:21:36

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

我正在使用Firebase规则设置权限,但我无法设置规则以允许写入权限包含用户和任何管理员。

以下是我尝试为以下内容设置权限的数据库:

'rules': {
    'rankings': { 
        'user': {
            'userShortenedAuthId': { //user's rankings },
            'anotherShortenedAuthId': { //another user's rankings }
        }
    },
    'admin': {
        'adminAuthId': true
    },
    'users': {
        'userAuthId': {
            'rank': 'userShortenedAuthId'
        },
        'anotherAuthId': {
            'rank': 'anotherShortenedAuthId'
        }
    }
}

以下是这些数据的规则:

"rankings":{
    "user":{
        "$rankId": {
            ".read": true,
            ".write": "auth != null && ((root.child('users/' + auth.uid + '/rank').val() == $rankId) || root.child('admin/' + auth.uid).exists())"
        }
    }
}

我正在尝试在管理员下登录时写入'排名/用户/ userShortenedId',但我从Firebase获得了权限被拒绝错误。 (登录为用户工作正常)。该错误位于'rankings / user / $ rankId / .write'规则中。令我感到困惑的是,我一直在其他地方使用'root.child('admin /'+ auth.uid).exists())'规则获得管理员权限,这似乎也可以正常工作。

以下是产生权限错误的代码。

firebase.database().ref('rankings/' + userShortenedAuthId).update({newPlayerKey:totalPlayers}))
    .then(function(){
        console.log('successfully updated user ranking');
    })
    .catch(function(err){
        console.log('error updated user ranking', err);
    }); 

1 个答案:

答案 0 :(得分:1)

找到我自己的问题的答案。尝试更新时引用的firebase引用URL

firebase.database().ref('rankings/' + userShortenedAuthId).update({newPlayerKey:totalPlayers}))

实际应该是

firebase.database().ref('rankings/user/' + userShortenedAuthId).update({newPlayerKey:totalPlayers}))

因此规则实际上正常运作。我只是想写错地方。

相关问题