firebasefluttergoogle-cloud-firestorefirebase-authenticationrole-based-access-control

Hide content from app for unauthorized user - Flutter Firebase


So i want to show a special button. The button should only work (or be seen) when the user is logged in with the right permissions.

I saw that i can somehow do this with flutter firestore. How can i implement this to my code? If you need more code or infos (screens) from my firestore database just ask in the comments. :)

//serverstatuspage

    final serverstatuspage = Material(
        elevation: 5,
        borderRadius: BorderRadius.circular(30),
        color: Colors.green,
        child: MaterialButton(
            padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
            minWidth: MediaQuery.of(context).size.width,
            onPressed: () {
              serverstatusbutton(context);
            },
            child: Text(
              "Admin Dashboard",
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 20,
                  color: Colors.white,
                  fontWeight: FontWeight.bold),
            )));

Solution

  • You can add new fields in your user documents according to your permissions and then check them before displaying the widget, or at onPressed of your button. For example, add a new boolean field 'isAdmin' in the user documents and assign either true or false to it. Now you get this value and make the button functional only if isAdmin is true, like this:

    First get the field value

    bool isAdmin = false;
    Future<void> getRole() {
      return FirebaseFirestore.instance
          .collection('users')
          .doc('yourCurrentUserDocumentID')
          .get()
          .then((snapshot) {
        if (snapshot.exists) {
          isAdmin= snapshot.data()!['isAdmin'];
        } else {
          print('Document does not exist on the database');
        }
      });
    }
    

    Now use this method at onPressed()

    final serverstatuspage = Material(
    elevation: 5,
    borderRadius: BorderRadius.circular(30),
    color: Colors.green,
    child: MaterialButton(
    padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
    minWidth: MediaQuery.of(context).size.width,
    onPressed: () async {
      await getRole();
      isAdmin ? serverstatusbutton(context) : null; //onPressed will only work if isAdmin is true
    },
    child: Text(
      "Admin Dashboard",
      textAlign: TextAlign.center,
      style: TextStyle(
          fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
    ),
    ),
    );
    

    You can check this previously discussed topic here. If you want some more explanation on this topic, a guide using Cloud Functions can be useful to get the whole idea, and in case you want to go deep into it, the roled-based login architecture can help you with that.