0
votes

I'm trying to secure my data in Firestore. I have read the documentation and watch some videos but I still have some difficulties getting it right.

What I have built is a project app. With a data structure like this:

"School": {
    school1:
    school2: {
        "Users": {
            userId: {
                "SchoolName": "school2"
            }
        }
        "Projects": {
            projectId: {
            }
       }
    }
}

Only authenticated users can read and write to the whole database and only users in the same school can read and write data to that school. For example, only users in school2 can add a project to school2.

I tried something like this but it didn't work

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
    match /School/{schoolName} {
        allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{userId}).data.SchoolName[(schoolName)]
    }
  }
}

Can someone please show me how to do this and maybe some good explanation on how to think about security rules. Thank you very much in advance!

1

1 Answers

0
votes

you made just one mistake, replace this line:

 allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{userId}).data.SchoolName[(schoolName)]

with this :

 allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{request.auth.uid}).data.SchoolName == "school2"