Skip to content

Instantly share code, notes, and snippets.

@katowulf
Last active May 27, 2020 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katowulf/c2d045c00fcf39d83672bcb53f28717e to your computer and use it in GitHub Desktop.
Save katowulf/c2d045c00fcf39d83672bcb53f28717e to your computer and use it in GitHub Desktop.
// 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();
}
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