Home > Blockchain >  Uncaught Error in snapshot listener:, FirebaseError: [code=permission-denied]: Missing or insufficie
Uncaught Error in snapshot listener:, FirebaseError: [code=permission-denied]: Missing or insufficie

Time:12-16

I am trying to let the user only read and write their own data. My rules are as follow(from the docs)

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

The uid for my user matches my document id but i still get the error:

Uncaught Error in snapshot listener:
FirebaseError: [code=permission-denied]: Missing or insufficient permissions.

My code for getting uid to document id

const handleSignUp = async () => {
      auth
      .createUserWithEmailAndPassword(email, password)
      .then(async (UserCredentials) => {
        const user = UserCredentials.user;
        console.log("Registered with: ", user.email);

        try {
          const uidRef = doc(db, 'users', user.uid);

          const docRef = await setDoc(uidRef, {
            name: name,
            age: age,
            currentWeight: currentWeight,
            goalWeight: goalWeight,
          });

        } catch (e) {
          console.error("Error adding document: ", e);
        }

I am really lost as I have tried many different ways and all docs / answers on here do not work for me. I am guessing the error comes when i call snapshot in this code

const getUser = async() => {

    const subscriber = onSnapshot(usersRef, (snapshot) => {
      let user = []
        snapshot.docs.forEach((doc) => {
          user.push({...doc.data(), key: doc.id })
        })
        setUser(user);
        console.log(user);
    })
    return () => subscriber();
  };

I am just unsure as to what is exactly wrong here. Is it my rules? My snapshot?

CodePudding user response:

Given that you get a QuerySnapshot result, I suspect that your code is reading the entire users collection. But as the documentation says rules are not filters, but instead merely ensure that your code only tries to access data that it is permitted to.

So your code should only try to read the document of the currently signed in user.

const getUser = async() => {
  if (getAuth().currentUser) {
    const uidRef = doc(db, 'users', getAuth().currentUser.uid);

    const subscriber = onSnapshot(uidRef, (doc) => {
      setUser({...doc.data(), key: doc.id })
    })

    ...
  }
};
  • Related