You need to check auth !== null
if you want the data restricted to any authenticated user.
You need to check for auth.uid == $uid
when you want the data restricted to the currently authenticated user. You don't need to check for auth == null && auth.uid != $uid
because auth.uid == $uid
will evaluate to false if the auth
variable is null. But you can still include both to be thorough.
So essentially, auth != null
is restricts the data to any authenticated user, and auth.uid != null
restricts to the single currently authenticated user.
Now for some extra curricular information.
Use the Bolt compiler to simplify common rules.
Security Rules are flexible, but they don't have much convenience for reproducing common rules. For that, you can use the Bolt compiler.
The Bolt compiler allows you to create types and assign them to paths in your Firebase database. These types act as schema. You can also create functions that abstract common rules.
I wrote a blog post on securing user data with Bolt. It goes through what you need to know to keep user data secured with types and functions in Bolt.
isCurrentUser(uid) = auth != null && auth.uid == uid;
isAuthenticated() = auth != null
path /users/$uid {
read() = isAuthenticated() // any authenticated user can read
write() = isCurrentUser($uid);
}
In the example above we reuse the isCurrentUser()
function three separate times. This will make changes moving forward much easier to deal with.