reactjsfirebasefirebase-realtime-databasefirebase-authenticationfirebase-security

Rules in Firebase Realtime Database for CRUD operations in React


I am using two firebase services: the Realtime Database and the Authentication in my React App. I have used the email/password authentication and a basic database for an inventory app consisting of three main nodes: inventory, batches and unfinished. In my react app, I have created a login page which lets users login through the authentication API.

const handleSignIn = async (values) => {
    signInWithEmailAndPassword(
      auth,
      values.username,
      values.password
    )
      .then((userCredential) => {
        sessionStorage.setItem("user", values.username);
        sessionStorage.setItem(
          "login",
          true
        );

        const user = userCredential.user;

        history.push("/inv");
        setMsg(null);
      })
      .catch((error) => {
        setMsg("The Email or Password is Invalid");
        console.log(error);
      });
  };

And also is there any suggestions on using the sessions storage for detecting the login status. I have used this because the website gets reloaded frequently.

My main problem is that I want the data inside the Realtime database to only be readable and writable by the authenticated users who login through the authentication.

The rules of Realtime Database are:-

  "rules": {
    ".read": "auth.uid != null",
    ".write": "auth.uid != null"
  }
}

I have tried everything which they have inside the documentation of firebase but nothing is working.


Solution

  • Is there any suggestions (...) for detecting the login status?

    The recommended approach is to "attach an observer to the global authentication object" as explained in the documentation.

    I want the data inside the Realtime database to only be readable and writable by the authenticated users who login through the authentication

    As you will see in the documentation you need to associate a rule to a path of the Realtime Database.

    Examples from the documentation:

    {
      "rules": {
        "foo": {  // <==== DB path
          ".read": true,
          ".write": false
        }
      }
    }
    

    or

    {
      "rules": {
        "parent_node": {   // <==== DB path for parent
          "child_node": {  // <==== DB sub-path for child
            ".read": <condition>,
            ".write": <condition>,
            ".validate": <condition>,
          }
        }
      }
    }