简体   繁体   中英

Is it possible to just grant users access to documents that are named after their uid in firestore using security rules?

My question is how can i make this work.

rules_version: "2";
service cloud.firestore { //define used service
  match /databases/{databases}/documents { //not a specific database (important)
    match /{document == request.auth.token.sub} { //how can this work?
      //some more conditions and allows
    }
  }
}

Users should be able to access a number of databases but all the documents are named after the users UID, which is request.auth.token.sub, or so i think. The UID and the documents name should match. How can I write this in firebase-security-rules-language?

Edit

Here is my working solution:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow create: if request.auth != null;
    }
    match /{database}/{userId}/{document=**} {
      allow read, update, delete: if request.auth != null && 
      request.auth.uid == userId;
    }
  }
}

Well, yes, but you're using the wrong field and wrong test. From firestore's documentation, you'd want it more like:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

See: https://firebase.google.com/docs/firestore/security/rules-conditions

Have a look at the Firebase documentation oncontent-owner access , which contains this example for Firestore:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /some_collection/{userId}/{documents=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM