Skip to content

Instantly share code, notes, and snippets.

@eezis
Created August 14, 2019 17:48
Show Gist options
  • Save eezis/88d9dc427de03ea86fdfc6edcbd83438 to your computer and use it in GitHub Desktop.
Save eezis/88d9dc427de03ea86fdfc6edcbd83438 to your computer and use it in GitHub Desktop.
Code to accompany this video: Firestore Security Rules - How to Hack a Firebase App
// this is a helpful video, code is transcribed from it
// https://www.youtube.com/watch?v=b7PUm7LmAOw
rules_version = "2";
service cloud.firestore {
match /databases/{database}/documents {
// ** means to cascade down to all subcollections and anything nested
match /{document=**} {
// an exmaple of allowing everyone to read products collection
// but only logged in users can delete
// match /products/{product_id} {
// allow update: if existingData().locked == false; // alllow modification?
// allow update: if incomingData().price > 10;
// can use hasAny or hasAll in the next line for simple role based rules
// allow update: if getUserData().roles.keys().hasAny(['editor', 'admin']);
// allow read;
// allow delete: if isSignedIn()
// for throttling -- can only write once in 60 seconds
// allow write: if request.time < resoucre.data.createdAt + duration.value(60, 's');
// }
// an example on user profiles -- assumes docId is userID, like I have it
// with classes collection -- note UserId is passed as a param to isOwner
// match /user/{userId} {
// allow read: if isSignedIn();
// allow write: if isOwner(userId);
// MORE SOPHISTICATED - only if emailVerified
// allow writeL if isOwner(userId) && emailVerified();
// }
// it keeps everyone OUT of EVERYTHING
// allow read, write: if false;
// I want to allow read and write while in dev mode
// allow read, write;
// allow read and write they
// allow read, write: if request.auth != null;
allow read, write: if isSignedIn();
// allow read, write: if request.auth.uid == userId;
// read rules allow read encapsulates these
// allow get;
// allow list;
// write rules allow write encapsulates thm but we
// can break out for more granularity
// allow create;
// allow update;
// allow delete;
function isSignedIn() {
return request.auth != null
}
function isOwner(userId) {
return request.auth.uid == userId;
}
function emailVerified() {
return request.auth.token.email_verified;
}
// these next two work together
function existingData() {
return resource.data;
}
function incomingData() {
// from the incoming request
return request.resource.data;
}
function getUserData() {
return get(/databases/$(database)/documents/users/$(request.auth.uid));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment