Firestore Check Is Admin Security Rules

We need to access request.auth to validate against signin users, so Firebase Authentication is required.

Solution 1: hard code

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    function isLogin() {
      return request.auth != null
    }

    function isAdmin() {
      return isLogin() && request.auth.uid == 'QYHqCKCGSbY3qqMSliqNhR3j9QC2'
    }

    match /tests/{testId} {
      allow read: if isLogin()
      allow write: if isAdmin()
    }
  }
}

Solution 2: users collection

We can create a users collection to perform roles checking.

name: "Desmond"
roles: ["user", "admin"]

NOTE: Document ID is the User ID.

function isAdmin() {
  return isLogin() &&
    'admin' in get(/databases/$(database)/documents/users/$(request.auth.uid)).data.roles
}

or

name: "Desmond"
admin: true
function isAdmin() {
  return isLogin() &&
    get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}

Solution 3: Firebase Auth Custom Claims

Use Firebase Auth Custom Claims for Access Control and Firestore Security Rules.

function isAdmin() {
  return isLogin() &&
    request.auth.token.is_admin == true
}

NOTE: is_admin is a custom token property created by you.

NOTE: This solution required a secure backend environment to create the custom token, and any changes to the token is applied only after 1 hour (or when user login/logout).

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.