Firebase security rules, ensure one “array remove” only, and only to userId

后端 未结 2 337
粉色の甜心
粉色の甜心 2021-01-18 14:33

I have notification records where there is a text and a list of users (max 10).

{text: \"Beware of the dog\", users: [ uid1, uid2, uid3, ... ]}
相关标签:
2条回答
  • 2021-01-18 15:08

    I don't think this is possible without a loop, which doesn't exist in security rules. Well: if you know all users, you might be able to enumerate all options, essentially unfolding the impossible loop. But even if this is possible in security rules, the rules are going to be incredibly verbose.

    I'd recommend creating a subcollection where each UID is stored in a separate document. In that subcollection you can then implement your requirement by only allowing the user to only delete their own document.

    0 讨论(0)
  • 2021-01-18 15:27

    I had a similar situation and it was quite a brain teaser. This is what did the trick for me:

    allow update: if 
        request.auth.uid != null 
        && request.resource.data.diff(resource.data).affectedKeys().hasOnly([data])
        && request.resource.data.users.size() == resource.data.users.size() - 1
        && resource.data.users.removeAll(request.resource.data.users)[0] == request.auth.uid
    

    Specifically:

    1. The first rule is the one you had - checks for user authentication
    2. The second rule checks the difference between the new and the old document and makes sure that the only key affected is the one named data
    3. The third rule makes sure that the new array is exactly 1 item shorter than the old one (so that only 1 item can be removed at a time)
    4. The fourth rule subtracts the new array (now reduced by 1 uid) from the old one with removeAll() and returns an array with their difference. In this case, it returns an array which contains only the single uid that you chose to arrayRemove(). Then we simply check that uid - which can only exist at position [0] - and make sure it is equal to the uid of the authenticated user.
    0 讨论(0)
提交回复
热议问题