Reputation: 533
I have the following Firestore security rule setup:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userID} {
allow create;
allow read, write: if request.auth.uid == userID;
}
}
}
I'm trying to save the users email, which they enter into a textfield in my SwiftUI app, and a random word generated by the app. Both are string values:
db.collection("wordOfDay").document(core.UID() ?? "").setData(["email": inputText, "word": Array(commonWords)[commonWordIndex].foreign ?? "", "date": todaysDate])
As you can see, I'm trying to use the user's ID (core.UID() ?? "") that was generated and saved to UserDefaults when they first signed up, as the way of authenticating with Firestore rules.
However, the data never gets written.
When I let anyone access the database:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
It successfully writes.
I'm sure I have an authentication problem, as I have not found any way of sending Firestore the userID for the security rules.
Upvotes: 0
Views: 46
Reputation: 598740
The allow read, write: if true;
in your last rules snippet means that anyone in the world can do whatever they want with each document, including deleting them. That's probably not what you want.
Your first set of rules only allow the user to access the document if their UID matches, which is a good example of implementing owner-only access. But your code doesn't match this requirement. Specifically the expression you call out:
core.UID() ?? ""
This says: if there is a core
value (presumably a user) then use its UID, otherwise use an empty string. But an empty string is not a valid document ID in your code, and your rules won't allow it anyway.
Instead you should check if core
has a value, and only access the database document for a user if there actually is a user signed in:
if (core != null && core.UID() != null) {
db.collection("wordOfDay").document(core.UID()!).setData(...);
}
Upvotes: 1