Reputation: 3278
These are the rules for saying only a logged in user can access a document named with their user id in realtime db. I'm asking how to do this in Firestore, except the name of the documents isn't the userid, but the username (which is the first part of the email)
I have seen this done before when the document names are the uid
, but my documents names are the username of the user, and the username is stored as the part before the @
in the authentication email.
For example, I have these users:
and my firestore is:
collection: users
john
jane
Only a user logged in as [email protected]
should be able to write to the john document in users. I couldn't figure out how to get the email out of the auth
variable.
Is there a way to do this without renaming my documents to user id?
Upvotes: 1
Views: 2609
Reputation: 3278
I found out you can get the email of the user with request.auth.token['email']
. I'm able to just use this for allowing anyone to read, only people who aren't authenticated to create, and for updating and deleting user can only update/delete their own document (with emails):
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{email} {
allow read;
}
match /users/{email} {
allow update, delete: if request.auth.token['email'] == email;
allow create: if request.auth.uid != null;
}
}
}
Upvotes: 6