Home > Enterprise >  How to make firebase rule to prevent write by property size?
How to make firebase rule to prevent write by property size?

Time:09-10

I have chat rooms with messages structure like this:

messages                          // collection
messages/docId                    // docId is Id of the room
messages/docId/roomMessages       // collection
messages/docId/roomMessages/docId // actual message

message example:
{
  fromUid: "",
  messageText: "",
  sentAt: date
}

match /messages/{docId} {
      allow read: if isloggedIn(request);
      allow create: if isloggedIn(request);
      
      match /roomMessages/{docId} {
        allow read: if isloggedIn(request);
        allow create: if canCreateMessage(request);
        allow write: if canCreateMessage(request);
      }
    }

function canCreateMessage(request) {
      let isSignedIn = request.auth.uid != null;
      let isOwner = request.auth.uid == request.resource.data.fromUid;
      let isNotTooLong = request.resource.data.messageText.size() < 5;
      return isSignedIn && isOwner && isNotTooLong;
}

but I still can save message that is longer than 5 characters. But not idea why?
Code that write message

const messageRef = firestore()
  .collection('messages')
  .doc(roomId)
  .collection('roomMessages')
  .doc();

await firestore().runTransaction(async transaction => {
  transaction.set(messageRef, {
    fromUid: authenticatedUser.uid,
    messageText: message,
    sentAt: firestore.FieldValue.serverTimestamp(),
  });
})

First part to show where I put rules maybe previous rules mess up:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  
    match /{document=**} {
      allow read; 
      allow write: if isloggedIn(request);
      allow create: if isloggedIn(request);
      allow update: if isloggedIn(request);
      allow delete: if isloggedIn(request);
    }
    
    match /messages/{docId} {
        allow read: if isloggedIn(request);
      allow create: if isloggedIn(request);
      
      match /roomMessages/{docId} {
        allow read: if isloggedIn(request);
        allow create: if canCreateMessage(request);
        allow write: if canCreateMessage(request);
      }
    }

CodePudding user response:

The match /{document=**} is a recursive wildcard that applies to all the collections in your entire database. This rule just checks if user is logged in and then allows the request. Any other rules won't be checked if one rule allowed the operation. So other rules are ineffective as long as you keep that.

Checkout this video to learn more about security rules.

  • Related