Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cloud_firestore] Cloud Firestore for WEB throwing FirebaseError: Missing or insufficient permissions. (permission-denied) #3095

Closed
eduardothiesen opened this issue Aug 4, 2020 · 11 comments
Labels
plugin: auth resolution: fixed A fix has been merged or is pending merge from a PR.

Comments

@eduardothiesen
Copy link

eduardothiesen commented Aug 4, 2020

Describe the bug
I'm unable to access the Cloud Firestore database on Web (it works perfectly on Android and iOS) and used to work in previous versions on web too.

I tried in channels Dev and Beta, and tested using specific version in the beta channel 1.15.17

I also tried modifying the permissions on Cloud Firestore Rules directly (accepting all requests) but it did not work.

To Reproduce
Steps to reproduce the behavior:

  1. Run flutter project with firebase_auth and cloud_firestore for web
  2. Login in the application
  3. Request any data using the logged user to firestore
  4. See the error: FirebaseError: Missing or insufficient permissions. (permission-denied)

Expected behavior
Request returns the data

Additional context
My pubspec.yaml (Using cloud_firestore bellow 0.13 keeps loading firestore requests forever)

name: my_companies_manager
description: A new Flutter project.
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  firebase_core: 0.4.4+3
  firebase_auth: 0.15.5+2
  cloud_firestore: 0.13.4+2
  font_awesome_flutter: 8.7.0
  provider: 4.0.4
  mask_text_input_formatter: ^1.0.5
  connectivity: ^0.4.6+2
  device_info: ^0.4.1+4
  modal_progress_hud: ^0.1.3
  intl: ^0.16.1
  csv: ^4.0.3
  flutter_share: ^1.0.2+1
  path_provider: ^1.6.5
  autocomplete_textfield:

dev_dependencies:
  flutter_test:
    sdk: flutter
  uses-material-design: true

Index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="my_companies_manager">
  <link rel="apple-touch-icon" href="/icons/Icon-192.png">

  <title>my_companies_manager</title>
  <link rel="manifest" href="/manifest.json">
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-storage.js"></script>
<!-- This script installs service_worker.js to provide PWA functionality to
     application. For more information, see:
     https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
    // TODO: Replace the following with your app's Firebase project configuration.
    // See: https://support.google.com/firebase/answer/7015592
    var firebaseConfig = {
      apiKey: "XXXXXX",
      authDomain: "example.firebaseapp.com",
      databaseURL: "https://example.firebaseio.com",
      projectId: "example",
      storageBucket: "exaple.appspot.com",
      messagingSenderId: "0000000000",
      appId: "1:45536682746:web:0000000f000000"
    };

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>

<script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function () {
        navigator.serviceWorker.register('/flutter_service_worker.js');
      });
    }
  </script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

Flutter doctor
Run flutter doctor and paste the output below:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel unknown, v1.15.17, on Mac OS X 10.15.5 19F101, locale en-BR)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.0)
[✓] Connected device (2 available)

• No issues found!

Thanks in advance.

@kroikie
Copy link
Collaborator

kroikie commented Aug 4, 2020

@eduardothiesen given that the error it would be useful to provide some information about:

  • the requests for the document
  • the rules gating access to the document in question

@kroikie kroikie added plugin: cloud_firestore blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Aug 4, 2020
@eduardothiesen
Copy link
Author

@kroikie sorry about that. Below you can see the request and the rules:

Future<User> getUser(FirebaseUser user) async {
    try {
      print('AuthService - getUser(${user.uid})');
      var doc = await _firestore.collection('users').document(user.uid).get();
      print('AuthService - getUser - doc:$doc');

      return User.fromFirestore(doc);
    } catch (e) {
      print('getUser: $e');

      return null;
    }
  }
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {  
    match /users/{userId} {
    	allow create: if request.auth.uid != null;
      allow read, write: if request.auth.uid == userId;
      allow read, write: if request.auth.uid == resource.data.systemId;
    }

    match /systems/{sId}/{document=**} {
    	allow create, update, read, write, delete: if getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data.systemId == sId;
    }
  }
}

I also tried with these rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

Both rules work for iOS and Android but not for Web.

Regards,

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Aug 4, 2020
@kroikie
Copy link
Collaborator

kroikie commented Aug 4, 2020

Thanks for the update, you mentioned

I also tried modifying the permissions on Cloud Firestore Rules directly (accepting all requests) but it did not work.

So even with setting read to true without any restrictions the web app is not able to read the document?

@kroikie kroikie added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Aug 4, 2020
@eduardothiesen
Copy link
Author

@kroikie Actually I just tested again with this rule:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2021, 4, 5);
    }
  }
}

And it worked. I'm sorry for the misinformation!
What I noticed is: the firebase user uid is always returning the same id 'IZNDDgQgbFTAnLX1xX6ZvBw3SvX2' for any user. So that's why it was not working with the Cloud Firestore rules set and now with 'read true' it returns null.

For example if I log in with the email: [email protected] and run this code:

print('AuthService - login - user: ${user.user.uid}');
print('AuthService - login - user: ${user.user.email}');

The output will be:

AuthService - login - user: IZNDDgQgbFTAnLX1xX6ZvBw3SvX2
AuthService - login - user: [email protected]

and If I log with a different email, lets say [email protected] the output would be

AuthService - login - user: IZNDDgQgbFTAnLX1xX6ZvBw3SvX2
AuthService - login - user: [email protected]

Different email for the FirebaseUser object but still same uid.

OBS: I use the firebase user id to map the id of the user in the database.
So the problem is probably in the firebase_auth?

Thanks in advance.

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Aug 4, 2020
@kroikie
Copy link
Collaborator

kroikie commented Aug 5, 2020

I agree, this does look like an Auth issue. How are you switching users, signing out then back in?

@kroikie kroikie added blocked: customer-response Waiting for customer response, e.g. more information was requested. plugin: auth and removed Needs Attention This issue needs maintainer attention. plugin: cloud_firestore labels Aug 5, 2020
@eduardothiesen
Copy link
Author

As I was not able to access the system, I just killed the process in Android Studio and cleared all the chrome data. I tested it now by logging out but the problem persists.

my logout code:

FirebaseAuth.instance.signOut (). WhenComplete (() {
                                 Navigator.pop (context);

                                 Navigator.push (
                                   context,
                                   MaterialPageRoute (
                                     builder: (context) =>
                                         AuthenticationModule (),
                                   ),
                                 );

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Aug 5, 2020
@kroikie
Copy link
Collaborator

kroikie commented Aug 5, 2020

@eduardothiesen thanks for sharing that. Could you confirm that you are signing in with different credentials and getting the same user ID: IZNDDgQgbFTAnLX1xX6ZvBw3SvX2? Could you also share your signin code?

@kroikie kroikie added blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed Needs Attention This issue needs maintainer attention. labels Aug 5, 2020
@eduardothiesen
Copy link
Author

@kroikie Yes, I have several accounts with different credentials and logging with all of them returns the same firebase user id. I also tried creating a new one but it still returns the same id.
My signin code:

RaisedButton(
                      child: Text('ACESSAR A CONTA'),
                      onPressed: () async {
                        FocusScope.of(context).requestFocus(FocusNode());

                        shouldShowSpinner(true);

                        final user = await _authService.login(
                            _scaffoldKey, email.trim(), password);

                        if (user != null) {
                          print('will login');
                          FirebaseUser _firebaseUser =
                              await AuthService().getFirebaseUser();
                          User _user =
                              await AuthService().getUser(_firebaseUser);

                          print('FirebaseUser $_firebaseUser');
                          print('User $_user');

                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => MyFinances(
                                _firebaseUser,
                                _user,
                              ),
                            ),
                          );
                        }

                        shouldShowSpinner(false);
                      },
                    ),
Future<AuthResult> login(GlobalKey<ScaffoldState> scaffoldKey, String email,
      String password) async {
    print('AuthService - login($email, $password)');
    try {
      final user = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
      
      print('AuthService - login - user: ${user.user.uid}');
      print('AuthService - login - user: ${user.user.email}');
      return user;
    } on PlatformException catch (e) {
      print('AuthService - login - error: $e');
      String errorMessage = '';

      switch (e.code) {
        case 'ERROR_INVALID_EMAIL':
          errorMessage = 'E-mail inválido. Verifique a digitação';
          break;
        case 'ERROR_WRONG_PASSWORD':
        case 'ERROR_USER_NOT_FOUND':
          errorMessage = 'Usuário ou senha errados.';
          break;
        case 'ERROR_USER_DISABLED':
        case 'ERROR_TOO_MANY_REQUESTS':
        case 'ERROR_OPERATION_NOT_ALLOWED':
          errorMessage = 'Algo deu errado. Tente novamente mais tarde';
          break;
      }
      final SnackBar snackBar = SnackBar(
        content: Text(errorMessage),
      );

      scaffoldKey.currentState.showSnackBar(snackBar);

      return null;
    } catch (e) {
      print('AuthService - login - error: $e');

      return null;
    }
  }

@google-oss-bot google-oss-bot added Needs Attention This issue needs maintainer attention. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Aug 5, 2020
@kroikie
Copy link
Collaborator

kroikie commented Aug 5, 2020

It looks like signInWithEmailAndPassword is not yet supported on web it should be in firebase_auth_web.dart. This could explain the issue you are running into.

I can confirm it is in the update we are working on so this should be available very soon.

@kroikie kroikie added resolution: fixed A fix has been merged or is pending merge from a PR. and removed Needs Attention This issue needs maintainer attention. labels Aug 5, 2020
@eduardothiesen
Copy link
Author

@kroikie Great. Thanks for the help!

@Salakar
Copy link
Member

Salakar commented Aug 25, 2020

Hey 👋

Our rework of the firebase_auth plugin as part of the FlutterFire roadmap was published over a week ago with a ton of fixes and new features including signInWithEmailAndPassword support on Web. Please could you try the new version and see if this is still an issue for you? If it is then please submit a new up to date GitHub issue.

For help migrating to the new plugins please see the new migration guide: https://firebase.flutter.dev/docs/migration

@Salakar Salakar closed this as completed Aug 25, 2020
@firebase firebase locked and limited conversation to collaborators Sep 25, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
plugin: auth resolution: fixed A fix has been merged or is pending merge from a PR.
Projects
None yet
Development

No branches or pull requests

4 participants