I was trying to access data from Cloud Firestore, but the access is denied.
My flutter code
FirebaseAuth _auth = FirebaseAuth.instance;
final logineduser = _auth.currentUser!.uid;
final QuerySnapshot result = await FirebaseFirestore.instance
.collection('product_details').get();
final List<DocumentSnapshot> documents = result.docs;
print(documents[0]);
The Cloud Firestore Security rules
rule_version='2'
service colud.firestore{
match /databases/{database}/documents {
match /user_details/{emailId}{
allow read,write;
}
match /user_activities/{userId}{
allow read,write;
}
match /product_details/{Id}{
allow read,write;
}
match /purchase_details/{Id}{
allow read,write;
}
match /{document=**}{
allow read,write:if request.auth.uid !=null;
}
}
}
This says to allow read or write if the authentication is not null.. So unless the user is authenticated you will not be able to access data except for the queries you have written above this. You can either implement login or to make it public you can write
allow read,write;
Please note it is NOT a good practice to keep it public. Maybe for learning you can try this.
Related
Can someone please help me I am a complete noob to FireStore and FireBase and am trying to do something simple and FireBase is saying I do not have permission to do it? I am using Flutter. I have the following rules set up in FireBase rules console. I only have one project and one firestore database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow write: if request.auth != null;
allow read: if true;
}
}
}
I have a collection of users setup which has a uid as the collection parameter and running the following code after signing into flutter anonymously which does not throw an error. UserID is set to a valid value.
void createUser(String userID, String userName, String password) async {
final CollectionReference _users =
FirebaseFirestore.instance.collection("Users");
final data = {"Created": DateTime.now(), "LastLoggedIn": DateTime.now()};
_users.doc(userID).set(data, SetOptions(merge: true));
}
I am getting the following error message
10.3.0 - [FirebaseFirestore][I-FST000001] Write at Users/QUIEvBpJeAgprgEan0S736aKjdk2 failed: Missing or insufficient permissions.
I am using anonymous log ons
even when I use the following rules which is supposed to allow all reading and writing of the data I get the same error:
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
I allowed several minutes to go by between when I set the permissions and before testing. Thanks.
Have you tried the default rule with timestamp :
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if
request.time < timestamp.date(2023, 11, 25);
}
}
}
I need to combine the rules for firebase firestore. If I use the standard method,
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
the usual method of registering users with a username, email and password works, & everething is perfect, and everything suits me.
But the facebook login method stops working. Most likely due to the fact that the user is not yet logged in to the server but is already trying to write data to the users collection. As a result, I can see it in the list of authorized users, but in firestore, its email field remains nil. If I use the standard rule that allows everyone to write data from the Internet)(i know it's bad practice)
allow read, write: if true;
everything works fine. So I need to somehow add a rule that allows everyone to write data to my users collection? A trigger is used to create a document during registration
exports.createAccountDocument = functions.auth.user().onCreate(async user => {
const { uid, displayName, email } = user
const username = displayName;
const profileImageUrl = uid;
const str = username;
const qwery = [];
for (let i = 0; i < str.length; ++i) {
qwery[i] = str.substring(0, i + 1).replace(/\s/g, "").toLowerCase();
}
const keywords = qwery;
const bio = "";
return await admin
.firestore()
.collection("users")
.doc(uid)
.set({ bio, keywords, email, profileImageUrl, uid, username })
})
Maybe it will be correct like this?
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
match /users/{document=**} {
allow read, write: if true ;
}
}
?
Code running in Cloud Functions using the server SDKs (including the Firebase Admin SDK) for Firestore always bypass security rules. The code you're showing here in the onCreate trigger will always be able to write to Firestore regardless of what you write in your security rules.
Security rules only apply to direct access from web and mobile clients. Your rules should focus on access controlled by Firebase Authentication.
I'm receiving this error when I try to read one of my Firestore collections:
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.
This is my Firestore Inicialization:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
And this is my try to access my collections:
Future initFirestore() async {
var firestore = FirebaseFirestore.instance;
//firestore.settings(timestampsInSnapshotsEnabled: true);
QuerySnapshot resultado = await firestore.collection("users").get();
print(resultado);
}
(I see some people talking about something that fix this, but Stackoverflow don't let me ask how to get in the document that those people were)
Please send help. You, stackoverflow, is the last hope
Allowing your users to read and write to your DB can be manipulated by updating the rules to your Cloud Firestore. (Found in console.firebase.google.com => Cloud Firestore => Rules)
If you would like to have all access (Nice to use while testing, but probably should be updated when you go live)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: true;
}
}
}
If you want only auth'd users to access your DB you can add the following
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
Here are the docs for the rules that you can brush up on to finetune your rules.
I am not able to read/write data to firestore with rules in place.
I can access my data and do operations on it with no rules set as shown below:
match /{document=**} {
allow read, write: if true;
}
But I am getting the "permission denied" error with following rules.
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
Here is my dart code:
if (uid == null) {
user = await a.currentUser();
uid = user.uid;
}
DocumentReference docRef = firestore.collection('users').document(uid);
CollectionReference locations = docRef.collection('locations');
await locations.document().setData(<String, double>{
'latitude': latitude,
'longitude': longitude,
});
I can think of two scenarios in which this request fails:
request.auth.uid == null. But I have a user logged in with firebase auth before this query.
My security rules and query doesn't match.
Please help me debug this issue.
Edit 1:
I have user authenticated during my firebase query as I changed the code to enter only if the user is authenticated as below:
User u = await a.onAuthStateChanged.first;
if (u != null) {....}
I was able to read/write with authentication using firebase simulator.
Is there anyway I can print the actual request being sent to the firebase from dart using cloud_firestore package?
Edit 2
Firestore.instance is working with rules
Firebaseapp configured to my specific app using configure,options isn't working.
Any help on why this might be happening?
Just change your rules to as below if you want to allow anybody to upload the documents.
allow read, write;
If you want to allow only authenticated users to allow upload the files or documents to your firebase change your rules to
allow read, write: if request.auth != null;
change your rules to allow read,write: if request.auth !=null;
In Firestore I wan't to allow a read, if the targeted document does not exists. I have tried the following:
service cloud.firestore {
match /databases/{database}/documents {
match /reports/{report} {
allow read: if !exists(/databases/$(database)/documents/reports/{report});
}
}
}
It does not work, the respons is: Missing or insufficient permissions..
In case you're doing this server-side, you might instead query the document's existence using the admin SDK (firestore rules are only applied to the client SDK):
const snapshot = await adminFirestore.doc('reports/non-existent-item').get();
if (!snapshot.exists) {
// handle gracefully
}
This seems to be working.
allow get: if resource == null;