简体   繁体   中英

How to differentiate between different permissions errors in Firestore

I'm building an application with Firebase, and using the client-side Javascript SDK to access Firestore data. I'm running into a problem: With my firestore rules, if a document can't be read, there's no way to determine why it couldn't be read. Any failure of the rules to allow the document to read produces the same PERMISSION_DENIED: Missing or insufficient permissions error.

Without a way to determine why access was denied, I can't present the correct way to gain access to the resource in the UI, or say what went wrong (eg You must log in to use this doodad, or You must purchase a subscription to work this widget) Coming from a node background, I've written a lot of code making use of http response codes like this (pseudo code):

if (!doc) {
    // present a 'not found' message to the user
    return {status: 404}
}
else if (!req.user) {
    // present a log in/sign up dialog
    return {status: 401}
}
else if (req.user !== doc.owner) {
    // present a no-access message
    return {status: 403}
}
else {
    return {status: 200: body: doc}
}

Short of writing a server-side layer to handle permissions instead of using firestore.rules, or create a separate collection just to handle permissions, which would have to be kept in sync manually and require 2x the reads, is there a way to write the rules so that the different reasons for failure can be differentiated? Seems like if firestore were to implement a deny keyword, this would be easy:

deny read 401: if !request.auth.uid
deny read 403: if request.auth.uid !== resource.data.owner

But alas, there is no such deny keyword.

That message cannot be customised as of now. One way around this could be not making the request as first place if the user is not logged in. For example:

if (getAuth().currentUser) {
  // fetch data
} else {
  alert("Please login")
}

It might be a bit challenging for 401 and 403 but if you could list out in what cases there maybe 403 error, then you can definitely structure your code that way.

For 404, you can use the .exists property if DocumentSnapshot is returned

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM