Skip to content

Instantly share code, notes, and snippets.

@ryanpbrewster
Created April 18, 2019 05:33
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 ryanpbrewster/f0bc4b1cd6acdf17604e39b61a4589f7 to your computer and use it in GitHub Desktop.
Save ryanpbrewster/f0bc4b1cd6acdf17604e39b61a4589f7 to your computer and use it in GitHub Desktop.
service cloud.firestore {
match /databases/{database}/documents {
function isValidRoomName(roomName, userId) {
return roomName.matches(".*" + userId + ".*");
}
match /users/{userId} {
allow read;
allow write: if isValidRoomName(request.resource.data.room[4], userId);
}
}
}
const firebase = require("@firebase/testing");
const fs = require("fs");
/*
* ============
* Setup
* ============
*/
const projectId = "firestore-emulator-example";
const coverageUrl = `http://localhost:8080/emulator/v1/projects/${projectId}:ruleCoverage.html`;
const rules = fs.readFileSync("firestore.rules", "utf8");
/**
* Creates a new app with authentication data matching the input.
*
* @param {object} auth the object to use for authentication (typically {uid: some-uid})
* @return {object} the app.
*/
function authedApp(auth) {
return firebase
.initializeTestApp({ projectId, auth })
.firestore();
}
/*
* ============
* Test Cases
* ============
*/
beforeEach(async () => {
// Clear the database between tests
await firebase.clearFirestoreData({ projectId });
});
before(async () => {
await firebase.loadFirestoreRules({ projectId, rules });
});
after(async () => {
await Promise.all(firebase.apps().map(app => app.delete()));
console.log(`View rule coverage information at ${coverageUrl}\n`);
});
it("doc refs are paths", async () => {
const db = authedApp(null);
const profile = db.collection("users").doc("alice");
const alices_room = db.collection("rooms").doc("alice's hangout");
const bobs_room = db.collection("rooms").doc("bob's hangout");
await firebase.assertFails(profile.set({ birthday: "January 1", room: bobs_room }));
await firebase.assertSucceeds(profile.set({ birthday: "January 1", room: alices_room }));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment