Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore security rules check if reference exists

I'm wondering how I could check if a document value is a reference to another document and the document exists using firebase security rules.

What I tried:

function validate(document) {
    return exists(document.reference)
}

match /collection/{document} {
    allow read: if request.auth != null;
    allow create, update: if isAdmin(request.auth.uid) && validate(request.resource.data);
}

As this didn't work, I tried to figure out what type document.ref is. Unfortunately, it doesn't seem to have any type of the listed ones here: https://firebase.google.com/docs/firestore/reference/security/?authuser=0#data_types

I tried path as it's the most obvious one to work with exists. I didn't expect it to work. Another guess was maybe map or string. Both were incorrect.

As I don't have a clue what this could be and there is nothing documented how I can convert the reference to a path, I now have to ask here.

Has anyone found a solution to this?

TL;DR:

I need to check using Firestore security rules whether a reference saved in a document is present and it exists in the database.

Thanks, Dennis

like image 498
Ichor de Dionysos Avatar asked Jan 05 '18 17:01

Ichor de Dionysos


1 Answers

In this line:

allow create, update: if isAdmin(request.auth.uid) && validate(request.resource.data)

instead of calling "request.resource.data", you should just call "resource.data":

allow create, update: if isAdmin(request.auth.uid) && validate(resource.data)

As mentioned here, the resource variable represent the Firestore document, whereas the "request" variable represents the request being made at that path, thus not containing information about the actual values in the document.

Give it a try and let me know if it doesn't work for your.

like image 181
Gerardo Avatar answered Oct 03 '22 15:10

Gerardo