0

I am new to Flutter/Dart but I have been trying to figure out the DB rules for a project that I am working on. I know that there are numerous posts on SO about Firebase DB rules but everything that I have found and tried has not worked. In the particular case below I want anyone to be able to read the data but only the author to be able to write and edit it. I set the Doc ID to be the uid and that works fine with permissions removed but I cannot get anything to work when I add restricted rules. What am I doing wrong?

Stack Trace Message

I/flutter (17900): PlatformException(Error performing setData, PERMISSION_DENIED: Missing or insufficient permissions., null)
E/flutter (17900): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _RegisterState#1360e(lifecycle state: defunct, not mounted)

My Firebase Rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /brews/{userId} {
      allow read: if request.auth.uid != null;
      allow write: if request.auth.uid == userId;
    }
  }
}

Database Code

class DatabaseService {
  final String uid;
  DatabaseService({this.uid});

  //Collection reference
  final CollectionReference brewCollection =
      Firestore.instance.collection('brews');

  Future updateUserData(String sugars, String name, int strength) async {
    return await brewCollection.document(uid).setData({
      'sugars': sugars,
      'name': name,
      'strength': strength,
    });
  }

  //brew list from snapshot
  List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.documents.map((doc) {
      return Brew(
        name: doc.data['name'] ?? '',
        strength: doc.data['strength'] ?? 0,
        sugars: doc.data['sugars'] ?? '0',
      );
    }).toList();
  }

  //userData from snapshot
  UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
    return UserData(
      uid: uid,
      name: snapshot.data['name'],
      sugars: snapshot.data['sugars'],
      strength: snapshot.data['strength'],
    );
  }

  //Get the collection stream
  Stream<List<Brew>> get brews {
    return brewCollection.snapshots().map(_brewListFromSnapshot);
  }

  //get user doc stream
  Stream<UserData> get userData {
    return brewCollection.document(uid).snapshots().map(_userDataFromSnapshot);
  }
}

Authentication Code:

class Authenticate extends StatefulWidget {
  @override
  _AuthenticateState createState() => _AuthenticateState();
}

class _AuthenticateState extends State<Authenticate> {
  bool showSignIn = true;
  void toggleView() {
    setState(() {
      showSignIn = !showSignIn;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (showSignIn) {
      return SignIn(toggleView: toggleView);
    } else {
      return Register(toggleView: toggleView);
    }
  }
}
1
  • 2
    The code you shared is both reading and writing. Which one doesn't work? What happens when that code runs? Any error message/stack trace? In addition: since you require the user to be authenticated in your rules, you'll need them to sign in in the code. The code you shared doesn't show that/how the user signs, nor does it check whether the user is signed in before reading/writing. Please spend some time isolating a single problem, as that increases the chances someone can help. Commented Jan 23, 2020 at 23:21

1 Answer 1

1

Your rules are correct, and your update function is correct. Your authentication code doesn't show us if you perform a firebase auth login though.

The only thing that could stop it from working is if you are not logged in (authenticated via firebase authentication) OR you passed the wrong uid String to your DatabaseService class. If that's the case you wont have a request.auth.uid so the rule will fail.

You can test your rules in the console, or you can try isolate the exact payload in your code to provide us more info.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.