【问题标题】:Access Firestore Database without authentication无需身份验证即可访问 Firestore 数据库
【发布时间】:2020-10-24 10:20:09
【问题描述】:

在我的应用程序中,我想在用户登录之前检查是否存在具有相同电子邮件的文档(其中'email' 是我的'user_data' 集合中的文档字段)...

我已经编写了执行此操作的代码,但它需要访问我的 Firestore 数据库,即使用户尚未登录(并且在我的 Firestore 规则中我说allow read, write: if request.auth != null;

那么,如何在不向所有人允许 read 的情况下更改我的 Firestore 规则?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore firebase-security


    【解决方案1】:

    我认为将您的 Firebase 数据库安全规则更改为公开是不可取的。

    但我能理解你的情况。我可以给你一个想法。

    这就是我在不更改安全规则的情况下实现它的方式。

    点击按钮后要查看的时间:

    //SIGN UP
    
    try {
      UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: "USER ENTERED PASSWORD",
        password: "SuperSecretPassword!"
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
        // Tell User That It already exists!
      }
    } catch (e) {
      print(e);
    }
    
    // Or SIGN IN
    
    try {
     UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: "barry.allen@example.com",
        password: "SuperSecretPassword!"
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    }
    

    当您在输入电子邮件文本字段时要检查时:

    UserCredential userCredential = await FirebaseAuth.instance.signInAnonymously();
    

    您可以匿名登录并阅读数据库!读取并过滤后注销用户。

    否则,如果你还没有说服,那么你就去吧,

    参考:https://firebase.google.com/docs/rules/basics#content-owner_only_access

    read 设为公开,write 设为授权用户。

    希望这适合你的情况!

    【讨论】:

    • 谢谢!我同时使用电子邮件/密码和谷歌登录,所以我不能使用email already in use 异常,但我用匿名登录解决了:)
    【解决方案2】:

    改变

    allow read, write: if request.auth != null;
    

    allow read, write: if true;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 2019-04-17
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      相关资源
      最近更新 更多