JavaScript

Firebase tips(Database rule .3)

More than 1 year has passed since last update.

FIREBASE TIPS

Validate If Specific Object exists.

database.rule.json
{
  "rules": {
    ".read": false,
    ".write": false,
    "coffeeandcode-japan":{
      "user": {
        ".read": true,
        ".write": true
      },
      "room" :{
        ".write": "root.child('coffeeandcode-japan/user/' + auth.uid).exists()"
      }
    }
  }
}

database
database.png

  • TEST1: A member who has no user info tries to make a room object.
    firebase.auth().signInWithEmailAndPassword('coffeeandcode.tokyo2@gmail.com', 'coffee').catch((error) => {
        console.log('code:' + error.code + ' message:' + error.message);
    });
    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            console.log('login success');
            database.ref('coffeeandcode-japan/room/' + 'testroom1').set(
                {
                    room_name: 'coffee'
                }
            ).catch((error) => {
                console.log('code:' + error.code + ' message:' + error.message);
            });
        } else { }

    });

result
result1.png

  • TEST2: A member who has a user info in "user" object tries to make a room object.
    firebase.auth().signInWithEmailAndPassword('coffeeandcode.tokyo@gmail.com', 'coffee').catch((error) => {
        console.log('code:' + error.code + ' message:' + error.message);
    });
    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            console.log('login success');
            database.ref('coffeeandcode-japan/room/' + 'testroom1').set(
                {
                    room_name: 'coffee'
                }
            ).catch((error) => {
                console.log('code:' + error.code + ' message:' + error.message);
            });
        } else { }

    });

result1

result2.png

result2

result3.png