0

I have a collection admins in my firestore, where i add document IDs of users with admin roles.

In other to grant users admin role, i need to check if their users ID (documentID) is found under admin collection.

here is my code:

isAdmin() async {
await getUser.then((user) async {
  final adminRef = await _db.collection("admins").doc(user?.uid).get();
  if (adminRef.exists) {
    admin.value = true;
  } else {
    admin.value = false;
  }
  update();
}); }

It keeps returning false where as the document of the current user exist under admins.

when i replace the collection in the query by users, it works fine.

i don't know where i'm going wrong. any clue please?

here is admins collection image image of admins collection

here is users collection image image of users collection

Clid3
  • 9
  • 3
  • 1
    Add a screenshot of your admins collection... also just a recommendation, Firebase Custom Claims are ideal for adding such roles. – Dharmaraj Apr 29 '21 at 15:02
  • 2
    @Dharmaraj While custom claims are a valid option for storing the role of a user, storing the information in the database is equally valid. In fact, the latter is an approach we document here: https://firebase.google.com/docs/firestore/solutions/role-based-access – Frank van Puffelen Apr 29 '21 at 15:08
  • @FrankvanPuffelen Thanks. I just mentioned it if he isn't aware of Admin SDK and waiting on the database structure. – Dharmaraj Apr 29 '21 at 15:13
  • @Dharmaraj i have added an image of `admins collection` – Clid3 Apr 29 '21 at 15:46
  • @Clid3 just for confirmation, can you please log the `adminRef` ? To see if it is not null – Dharmaraj Apr 29 '21 at 15:52
  • @Dharmaraj it says `Instance of 'DocumentSnapshot'` – Clid3 Apr 29 '21 at 16:35
  • can you add your getUser() method in question. I think it is having some problem – Dhananjay Gavali Apr 29 '21 at 17:19
  • does the user have permission to read inside the admins document? if not, it'll fail regardless of the client. if this is not the client, there is no need to tag flutter. – DIGI Byte Apr 30 '21 at 04:28

1 Answers1

0

This will work. data() method will return null if no document present and return {} when the blank / empty document present.

isAdmin() async {
await getUser.then((user) async {
  final adminRef = await _db.collection("admins").doc(user).get();
  if (adminRef.data() == {}) {
    admin.value = true;
  } else {
    admin.value = false;
  }
  update();
}); }

I didn't get why you are creating empty documents inside the collection. Instead you can store the userId of admin in the each document and assign userId as a documentId. and you can check it by using where queries.

Dhananjay Gavali
  • 251
  • 3
  • 13