GOOGLE FIREBASE DETAILED SECURITY RULES Part 2

This is follow on post from Google Firebase detailed security rules part 1.

Advanced Rules

Only allow user to edit or add their own

This prevents other users from modifying other users content. Here’s an example of Firebase Realtime Database.

"users": {
      "$user_id": {
        ".write": "data.child('user_id').val() === auth.uid || newData.child('user_id').val() === auth.uid"               
        }
}

Similarly in Firebase Storage rules. Allows authenticated users to read the users image. This example show folders and child folders to help apply different rules for each folder.

match /user-images {
      // Allow all to read each other's profile if authenticated
      allow read: if request.auth != null;
      
      match /{user_id} {
      // Only allow current user to write to its own folder
      	allow write: if request.auth.uid == user_id;
        allow read: if request.auth != null;
        
        match /{allPaths=**} {
        	allow read: if request.auth != null;
      		allow write: if request.auth.uid == user_id;
        }
      }
}

Multi-layer permission

Sometimes one key will need a different permission than the rest of the keys in the Firebase Realtime Database.

"users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        "key1": {
          ".write": "auth != null"
        },
        "key2": {
          ".write": "auth == null"
        },
        "key3": {
          ".write": "auth === auth.uid"
        },
        "key4": {
          ".write": "auth != auth.uid"
        }
      }
  }

In Firebase Storage. Allow only authenticated users to read in the /users/ folder. Then in /users/1233/ only allow the owner to write and others who are authenticated to read. In the folder /users/1233/anotherFolder/ read for all authenticated and write for owner. Last, /users/private/ only the owner is able to read and write.

match /users{
      allow read: if request.auth != null;
      
      match /{user_id} {
      	allow write: if request.auth.uid == user_id;
        allow read: if request.auth != null;
        
        match /{allPaths=**} {
        	allow read: if request.auth != null;
      		allow write: if request.auth.uid == user_id;
        }

        match /private {
      		allow write: if request.auth.uid == user_id;
        	allow read: if request.auth.uid == user_id;
      	}
      }
    }

More info checkout https://firebase.google.com/docs/database/security Don’t forget to subscribe below for more cloud engineer posts!

As always if you see any errors, mistakes, have suggestions or questions please comment below. Don’t forget to like, share, and subscribe for more! 

Advertisements

Published by

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.