12
votes

Firestore security rules do not work. Help me. Document data of users/userid could not be read.

----------Security Rule------------

service cloud.firestore {
 match /databases/{database}/documents {
  match /users/{userId=**} {

  // Missing or insufficient permissions.
    allow read, write: if request.auth.uid == userId

  // this is work.
  //allow read, write: if request.auth != null

}

} }

--------------main.js--------------------

import Vue from 'vue'
import Quasar from 'quasar'
import firebase from 'firebase'
import 'firebase/firestore'

Vue.config.productionTip = false
Vue.use(Quasar)


let app;
firebase.initializeApp({
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: ""
})


firebase.auth().onAuthStateChanged(user=> {
  if (user) {
    let ref = firebase.firestore().collection('users').doc(user.uid)
    ref.get().then(snapshot=>{
      // Error !! : Missing or insufficient permissions.
    }
  }
  if(!app){
    Quasar.start(() => {
      app = new Vue({
        el: '#q-app',
        render: h => h(require('./App').default)
      })
    })
  }

})

firebase ^4.8.0 vue ^2.5.0

Apparently, require.auth.uid does not seem to work properly. Where is there a mistake in me?

2
did you saved the auth.uid key as users key?Hareesh
@ShinyaUeda - request.auth != null is not working for me. I'm having this issue for Android using com.google.firebase:firebase-firestore:17.1.0 despite being logged in on the app and seeing the User UID in the Firebase Auth console.Adam Hurwitz
@Hareesh, any suggestions for debugging if request.auth != null is not working?Adam Hurwitz

2 Answers

11
votes

I was able to solve it self

 match /users/{user} {
   allow read, write: if request.auth.uid == user
   match / {docs = **} {
      allow read, write: if request.auth.uid == user
   }
 }

3
votes

I followed the example I found here (under the User tab) and it's working great:

// Grants a user access to a node matching their user ID
service firebase.storage {
  match /databases/{database}/documents {
    match /users/{userId}/{documents=**} {
      allow read, write: if isOwner(userId);
    }
  }

  function isOwner(userId) {
    return request.auth.uid == userId;
  }
}