Ad

How To Limit (Flutter) String Min/max Length With Security Rules In Firebase

I'm using Firestore Database and I'm now trying to add security rules after building many of the pages without security rules. That was definitely a huge mistake. I have reviewed a lot of the documentation and watched a bunch of the Firebase security rules videos which are all clear but as a beginner I still need guidance. I have also reviewed SO threads which have helped get me to this point.

My goal is to have client side validation and server side validation that requires a minimum of 3 characters and allows a maximum of 20 characters when a user creates a new account and adds their userName. And the same rules should apply when they update their userName. Here is an image of the database.

enter image description here

My security rules are:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
    allow read, write, update: if request.auth != null
    && request.auth.uid == userId
    && resource.data.username.length >= 3
    && resource.data.username.length <= 30
    && resource.data.undername is string;
    }

In the Rules Playground I get an error message:

Error running simulation — Error: simulator.rules line [10], column [28]. Null value error.

And in the console I get a similar error message:

Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

I can't figure out where I am going wrong with my rules code. Any help would be greatly appreciated. Thanks

Ad

Answer

You must be checking request.resource.data which contains incoming data and not resource.data which holds existing data from the document. Also try using size() instead of .length to check string length:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, update: if request.auth != null
        && request.auth.uid == userId
        && request.resource.data.username.size() >= 3
        && request.resource.data.username.size() <= 30
        && request.resource.data.undername is string;
    }
  }
}

For example, if current value of username is 'Jim' in the document and you are trying to update it to 'James', value of resource.data.username.size() would be 3 (length of existing name) and request.resource.data.username.size() would be 5 (length of new name). It's length of the new name that you are supposed to measure so you need to use request.resource.

Ad
source: stackoverflow.com
Ad