On this page: Content-owner only access there is an example of content owner only access security rule:
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /some_collection/{userId}/{documents=**} {
allow read, write: if request.auth != null && request.auth.uid == userId
}
}
}
Why should we check for request.auth != null
since it is redundant with request.auth.uid == userId
?
Why should we check for request.auth != null since it is redundant with request.auth.uid == userId?
It's not redundant.
Technically, request.auth.uid == userId
will generate an error in the case where access is coming from an unauthenticated client. The error is because request.auth
will be null, and you can't access a property of a null object (just like JavaScript). The error will cause the rule to immediately reject access (because that's generally what happens with errors in the rule system). However, it is still classified as an error, and that immediate rejection might not be what you want, as it will stop other rules from evaluating. The only safe way to handle this case is to check request.auth
for non-null before accessing its properties.
For this simple example you've shown, it doesn't much matter either way in practice. You get the same result. But with more complicated rules, you might not want an error to short circuit the evaluation of other conditions in the rule you've written.
It's entirely up to you to decide if you want to write the extra condition or not. Just be sure to test your rules so you can be sure they work the way you expect.
If you really want to dive in to the Common Expression Language spec that explains how errors work, read the documentation.