Skip to content
Advertisement

Firebase Realtime Database – Determine if user has access to path

I have updated my Firebase Realtime Database access rules, and have noticed some clients now tries to access paths they do not have access to. This is ok – but my problem is that my code stops after being unable to read a restricted node.

I see below error in my console, and then loading of subsequent data stops:

permission_denied at /notes/no-access-node

I begin by collecting access nodes from /access_notes/uid and continue to read all data from /notes/noteId. My code for collecting notes from the database below:

//*** SUBSCRIPTION */
database.ref(`access_notes/${uid}`).on('value', (myNotAccessSnaps) => {
  let subscrPromises = []
  let collectedNots = {}
  // Collect all categories we have access to
  myNotAccessSnaps.forEach((accessSnap) => {
    const noteId = accessSnap.key
    subscrPromises.push(
      database.ref(`notes/${noteId}`)
      .once('value', (notSnap)=>{
        const notData = notSnap.val()
        const note = { id: notSnap.key, ...notData}
        collectedNotes[note.id] = note
      }, 
      (error) => { 
        console.warn('Note does not exist or no access', error) 
      })
    )
  })

  Promise.all(subscrPromises)
  .then(() => {
    const notesArray = Object.values(collectedNotes)
    ...
  })
  .catch((error) => { console.error(error); return Promise.resolve(true) })

I do not want the client to halt on permission_denied!

Is there a way to see if the user has access to a node /notes/no_access_note without raising an error?

Kind regards /K

Advertisement

Answer

I do not want the client to halt on permission_denied!

You’re using Promise.all, which MDN documents as:

Promise.all() will reject immediately upon any of the input promises rejecting.

You may want to look at Promise.allSettled(), which MDN documents as:

[Promise.allSettled()] is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you’d always like to know the result of each promise.


Is there a way to see if the user has access to a node /notes/no_access_note without raising an error?

As far as I know the SDK always logs data access permissions errors and this cannot be suppressed.

Trying to access data that the user doesn’t have access to is considered a programming error in Firebase. In normal operation you code should ensure that it never encounters such an error.

This means that your data access should follow the happy path of accessing data it knows it has access to. So you store the list of the notes the user has access to, and then from that list access each individual note.

So in your situation I’d recommend finding out why you’re trying to read a note the user doesn’t have access to, instead of trying to hide the message from the console.


Advertisement