0
votes

I have setup firebase rules for users to read and write data to the database. Now I want to add another rule for admin user.

I am allowing users access through the auth.uid and want to set another level for an admin user.

Here's my current rule:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

And I'm fetching data by pass the $uid in the url like so:

`https://blablabla.firebaseio.com/users/${uid}/places.json?auth=` + authToken

Users are signing up by email and password. Is there a way I can add a specific user as an admin and setup another rule to access all the data?

1
firebase.google.com/docs/database/security/… this might be helpful; another way would be to have user info stored in Firestore with a role field and checking it with these rules: firebase.google.com/docs/firestore/security/…. - Crazy Barney
Depending on your requirements you can also do: ".read": "auth.uid === specific UID" - André Kool
@AndréKool, I have tried this but I'm not still getting the data. ".read": "auth.uid === 'specificUID' ", - Israel Z Kollie

1 Answers

1
votes

I typically create a isAdmin function in my rules that I then can call from everywhere. Here is an example from a recent project:

function isAdmin(request) {
  return request.auth.uid == "KqEizsqUQ6XMkUgLUpNxFnzLm4F3"
      || request.auth.uid == "zYXmog8ySOVRrSGVt9FHFr4wJb92"
      || (request.auth.token.email_verified && request.auth.token.email.matches(".*@google.com"))
      ;
}

So in this project the group of admins consists of two UIDs and anyone who signs in with a verified Google email address.

Now I can use this function in any other rules like this:

match /users/{uid} { 
  allow read: if true;
  allow create: if request.auth.uid == uid;
  allow delete: if isAdmin(request);
}

So anyone can read documents in the users collection, each user can create their own user doc, but only an admin can delete these documents.