Firebase 实时数据库 - 确定用户是否有权访问路径

Firebase Realtime Database - Determine if user has access to path

我更新了我的 Firebase 实时数据库访问规则,并注意到一些客户端现在试图访问他们无权访问的路径。这没关系 - 但我的问题是我的代码在无法读取受限节点后停止。

我在控制台中看到以下错误,随后停止加载后续数据:

permission_denied at /notes/no-access-node

我首先从 /access_notes/uid 收集访问节点,然后继续读取 /notes/noteId 的所有数据。 我从以下数据库中收集 notes 的代码:

//*** 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) })

我不希望客户端在 permission_denied!

停止

有没有办法在不引发错误的情况下查看用户是否可以访问节点 /notes/no_access_note

亲切的问候/K

I do not want the client to halt on permission_denied!

您正在使用 Promise.all,其中 MDN documents 为:

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

您可能需要查看 Promise.allSettled(),其中 MDN documents 为:

[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?

据我所知,SDK 总是记录数据访问权限错误,并且无法抑制。

尝试访问用户无权访问的数据被视为 Firebase 中的编程错误。在正常操作中,您的代码应确保它永远不会遇到此类错误。

这意味着您的数据访问应该遵循访问它知道可以访问的数据的快乐路径。因此,您存储用户有权访问的笔记列表,然后从该列表访问每个单独的笔记。

因此,在您的情况下,我建议找出您尝试阅读用户无权访问的注释的原因,而不是试图从控制台隐藏消息。