Last active
May 27, 2020 20:47
-
-
Save katowulf/c2d045c00fcf39d83672bcb53f28717e to your computer and use it in GitHub Desktop.
Simple role based rules example for Firestore. See https://groups.google.com/d/msgid/firebase-talk/CAHafJBrNvAM7_DnBQioTN-CvRYJivttc_B2JHD-18FK3hDyqOA%40mail.gmail.com?utm_medium=email&utm_source=footer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assumes that group members are stored in a subcollection under /groups/{groupId}/members/{userId} | |
const memberPath = '/familyMembers/{familyMemberId}/parents/{parentId}'; | |
// Trigger updates to our generated maps if group membership changes | |
exports.memberAdded = functions.firestore.document(memberPath).onCreate(memberAdded); | |
exports.memberDeleted = functions.firestore.document(memberPath).onDelete(memberDeleted); | |
async function getAllowedDocuments(parentId) { | |
// what goes here? | |
return ['foo', 'bar']; | |
} | |
async function getDisallowedDocuments(parentId) { | |
// what goes here? | |
return ['foo', 'bar']; | |
} | |
async function memberAdded(snap, context) { | |
const [parentId] = context.params; | |
const docs = await getAllowedDocuments(parentId); | |
const batch = admin.firestore().batch(); | |
docs.forEach(docId => { | |
const doc = admin.firestore().doc(`accessMap/${parentId}/docs/${docId}`); | |
batch.set(doc, {}); | |
); | |
await batch.commit(); | |
} | |
async function memberDeleted(snap, context) { | |
const [parentId] = context.params; | |
const docs = await getDisallowedDocuments(parentId); | |
const batch = admin.firestore().batch(); | |
docs.forEach(docId => { | |
const doc = admin.firestore().doc(`accessMap/${parentId}/docs/${docId}`); | |
batch.delete(doc); | |
); | |
await batch.commit(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rules_version = '2'; | |
service cloud.firestore { | |
match /databases/{database}/documents { | |
match /docs/{docId} { | |
// accessMap/{userId}/{docId} is a map of users to documents they can access | |
allow read if exists(docPath("accessMap/$(request.auth.uid)/docs/$(docId)")); | |
} | |
/** | |
* Shortcut to simplify pathing; make sure this exists inside the match /databases block | |
*/ | |
function getPath(childPath) { | |
return path('/databases/'+database+'/documents/'+childPath) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment