Custom parameter as a security rule – Firestore

  android, c#, firebase, javascript, xamarin

I am testing some security rules for my database in Firebase Firestore, I have tried several variants following tutorials and outside of Open Access and Closed Access none works for me.

The idea of ‚Äč‚Äčthis rule that I am trying to create is that all users can read, but only the owner of the profile can Create, Update and Delete his own information.

Case example: Update my username. But someone else can’t update my
username.

rules_version = '2';
service cloud.firestore 
{
  match /databases/{database}/documents 
  {
  
    match /MyUsers/{uid} 
    {
      allow read: if request.auth != null;
      allow create: if request.auth != null && Owner();
      allow delete: if request.auth != null && Owner();
      allow update: if request.auth != null && Owner();
    }
    
    function Owner()
    {
      return request.resource.data.uid == request.auth.uid;    
    }
    
  }
}

Also I would like to validate if the current authenticated email is the same than the email field of the collection I’m now trying to update.
So, I tried it this:

rules_version = '2';
service cloud.firestore 
{
  match /databases/{database}/documents 
  {
  
    match /MyUsers/{MyEmail} 
    {
      allow read: if request.auth != null;
      allow create: if request.auth != null && Owner();
      allow delete: if request.auth != null && Owner();
      allow update: if request.auth != null && Owner();
    }
    
    function Owner()
    {    
     return request.resource.data.MyEmail== request.auth.token.email; 
    }
    
  }
}

Most of the tutorials I have seen use uid, but I think it is important to mention that I do not have any field in my collection that is called uid. The fields in MyUsers‘ collections are:

Collection Name: MyUsers

MyName       string
MyEmail      string
MyUserName   string
MyCountry    string

Source: Ask Javascript Questions

LEAVE A COMMENT