Access child node in Firebase

1

I have 2 users. User twelve and user thirteen.

Each user created a project, as you can see in the image.

How do I get user Twelve to only access the projects he has created, and thirteen only the projects he created?

In the images you can see how my structure is in Firebase, how I'm calling DatabaseReference and my method of "selecting" the data "

    
asked by anonymous 03.01.2019 / 22:10

2 answers

2

Oops, all right!?

Every time you create a user, it does not generate an id (these nodes below projects)? save this id or retrieve it:

To recover this id you can do the following:

Declare the following variables:

private FirebaseAuth mAuth;
String mID;

In your onCreate assign values:

mAuth = FirebaseAuth.getInstance();
mID = mAuth.getUid();

Now in your project recover, you will pass the path + child ("project") + the user id of the logged in user, it will look like this:

DataSnapshot perfil = dataSnapshot.child("projeto").child(mID);

You will now have a Snapshot of just the user in question.

    
10.01.2019 / 12:31
0

You need to set up business rules:

{
  "projeto": { //Acessa o nó onde será feita a validação
    "$chave": { //$chave representa, nesse caso, os ids criados pelo próprio Firebase ao adicionar itens
      //Se houver um usuário autenticado pelo serviço de Auth e o id desse usuário for igual ao id salvo
      ".read": "auth != null && auth.uid === data.child('idUsuario').val()"
      //Se houver um usuário autenticado pelo serviço de Auth e, ou se já existe esse nó (se for uma operação de alteração) e o id do usuário autenticado for igual o id salvo, ou se não existir o dado (operação de criação) e o id do usuário autenticado for igual o id salvo
      ".write": "auth != null && (data.exists() && auth.uid === data.child('idUsuario').val() || !data.exists() && auth.uid === newData.child('idUsuario').val())"
    }
  }
}

In addition to setting the access rules for read ( .read ) and write ( .write ) it is important to configure the validation rules, so only data that is correctly formatted is written

Take a look at the documentation for more information.

    
03.01.2019 / 22:48