Firebase security read and write rules

47 Views Asked by At

I am changing the firebase security rules from

allow write: if true;

to

allow write: if request.auth.uid !=null;

but it only works if the user signed in via username and password auth BUT if the user signs in via google sign in, it does not allow the user to write into the DB.

Any help??? Thanks

allow write: ????????    to allow the user signed in via google sign in to access the DB

Once a button is pressed, this function is called

login() {
     googleSignIn.signIn();
  }

In the initState, this code is listening to the login

    googleSignIn.onCurrentUserChanged.listen(      
      (account) {
        functionToSignin(account);
      },
      onError: (err) {
        print('Error signing in: $err');
      },
    );

    googleSignIn.signInSilently(suppressErrors: false).then(
      (account) { functionToSignin(account);
      },
    ).catchError((err) { print('Error');   
    });

//-----
functionToSignin(account) async {
    if (account != null) {
      print('got an account from google');
      print('User signed in: $account');
      await addUserInFirestore();// call this function to create and add //users in DB firestore**** 

      setState(() {
        isAuth = true; 
      });
    } else {
      setState(() {
        isAuth = false; 
      });
    }
  }

The code that query the DB is:

final userReference = FirebaseFirestore.instance.collection('users');
final userr = googleSignIn.currentUser;
DocumentSnapshot doc = await userReference.doc(userr?.id).get();

if (!doc.exists) {
userReference .doc(userr?.id).set({
        "id": userr?.id,        
      });

doc = await userReference .doc(userr?.id).get();

Thank you so much for your time and help!!

1

There are 1 best solutions below

2
Doug Stevenson On

Firebase security rules only work when the user is signed in using Firebase Authentication. It seems you are using the Google signin SDK directly, which will not work at all with security rules. If you want the user to sign in using Google while also using security rules, you must follow the instructions for allowing Google sign-ins with Firebase Authentication. This will create a Firebase Auth user account that's linked to their Google account.