Home > Net >  How do I define the security rules where only logged in user can read and write all of the collectio
How do I define the security rules where only logged in user can read and write all of the collectio

Time:04-06

I have these collections of category, products, and orders. And then under the products I have a subcollection of history. Also in my app, there is only 1 type of user which I add here directly in the Firebase console. How can I define the security rules where only logged in user can read and write on these collections and subcollections?

enter image description here

For the logging in, I am using Firebase Authentication:

const handleSubmit = async (e) => {
    e.preventDefault();
    const auth = getAuth();
    console.log(email, password, "1");
    setIsLoading(true);
    signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in

        const user = userCredential.user;
        setIsLoading(false);
        navigate("/Homepage");
        // ...
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        setIsLoading(false);
        alert(errorMessage);
      });
  };

CodePudding user response:

How can I define the security rules where only logged in user can read and write on these collections and subcollections?

The following rule is using a wildcard and should allow any user that is authenticated to read and write to any document in Firestore:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

If you want to lock it down at some point, because you introduce a collection that not all users should have access to, you can make it explicit:

service cloud.firestore {
  match /databases/{database}/documents {
    match /category/{id} {
      allow read, write: if request.auth != null;
    }

    match /products/{id} {
      allow read, write: if request.auth != null;
    }

    match /logs/{id} {
      allow read, write: if false;
    }
  }
}

For further information, start here in the docs and use the Playground in Firebase Console to test your rules before deploying them.

  • Related