简体   繁体   中英

How do I define the security rules where only logged in user can read and write all of the collections and subcollection?

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?

在此处输入图像描述

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);
      });
  };

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM