Firestore Check Is Admin Security Rules

March 6, 2019

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.

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

NOTE: 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).

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.