Access child node in Firebase

Asked

Viewed 89 times

1

I have 2 users. Twelve user and thirteen user.

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

How do I make the twelve user access only the projects he created, and the thirteen only the projects he created?

In the images you can see how is my structure in Firebase, as I am calling the Databasereference and my method of "selecting" the data"inserir a descrição da imagem aqui inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • Do not add images of your code, always copy and paste the text

2 answers

0

It is necessary to configure the 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 configuring access rules for reading (.read) and recording (.write) it is important to configure the validation rules, so only data is written that are properly formatted

From a look at documentation for more information

0

Whoa, that’s all right!?

Every time you create a user, does it not generate an id (these below project nodes)? save that id or recover it:

to recover this id you can do the following:

Declare the following variables:

private FirebaseAuth mAuth;
String mID;

In your onCreate assign the values:

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

Now in your recoverProjects, you will pass the path + Child("project") + the logged-in user id, will look like this:

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

Now you will only have a Snapshot of the user in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.