Very new to Firestore and can't seem to fix the problem I have. I am registering the user with the phone, then prompt the user to edit data in app. However, I am encountering the error, and don't know how to fix it.
The error:
I/flutter ( 7502): [firebase_storage/unauthenticated] User is unauthenticated. Authenticate and try again.
W/Firestore( 7502): (23.0.3) [WriteStream]: (b2291d0) Stream closed with status: Status{code=NOT_FOUND, description=No document to update:
projects/blahblah/databases/(default)/documents/users/CrxXOi8vajhUYfevbPbMRjAHQqrv5, cause=null}.
E/flutter ( 7502): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: [cloud_firestore/not-found] Some requested document was not found.
Authentication works fine, as I see the user with the uid in users. However, not in the Firestore collection 'Users'. My rules are very simple:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{id} {
allow read, delete, update, create: if request.auth != null;
}}}
My storage rules are set to:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}}
edit profile method is:
String currentUid() {
return firebaseAuth.currentUser.uid;
}
updateProfile(
{File image,
String username,
String email,
String sex,
String dob,
String phone}) async {
DocumentSnapshot doc = await usersRef.doc(currentUid()).get();
var users = UserModel.fromJson(doc.data());
users.username = username;
users.email = email;
users.phone = phone;
users.dob = dob;
users.sex = sex;
if (image != null) {
users.photoUrl = await uploadImage(profilePic, image);
}
await usersRef.doc(currentUid()).update(
{'username': username, 'photoUrl': users.photoUrl, 'phone': phone,
'dob': dob, 'email': email, 'sex': sex});
return true;
}
Help appreciated very much!
I finally learned that enforcing the AppCheck storage access was not recommended this early in development. Unenforced the AppCheck for storage and it worked! Will be watching their videos from now on!
Your error is coming from Storage, not FireStore.
Go to storage and edit the rules there.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
I found a solution regarding this issue.
pub get firebase_app_check: ^0.0.3 this package.
and simply call this app check class-
await FirebaseAppCheck.instance.activate();
For my scenario I solved this issue this way.
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);
}
}
}
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
These are my firestore rules. As you can see, I am allowing read/write access to everyone. However, when I run the app, I get an error "[cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation."
I don't understand. Which part should I check?
Change Your rules like this
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
I solved the problem. The cause was the problem of going back and forth between the local emulator and the actual firestore.
After logging in from the Firebase emulator, I didn't log out. And because I tried to connect to the actual Firebase, an error occurred.
if (FirebaseAuth.instance.currentUser != null) {
await FirebaseAuth.instance.signOut();
}
I tried logging out with this code and it worked.
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;