代码之家  ›  专栏  ›  技术社区  ›  stop-error

根据firebase中的用户类型防止写入文档?

  •  0
  • stop-error  · 技术社区  · 2 年前

    我有一个名为shared的集合在这个集合中,我将有一个文档,作为管理员和客户端之间的连接(这样客户端可以推送他们的在线状态,管理员也可以这样做),我想做的是一个安全规则,允许管理员只修改他的文件 (onlineAdmin:true)

    和客户端只修改他们的文档(OnlineClient:{clientID:true})。 这可以通过规则来实现吗?如果是这样的话,如何将写入限制在每种用户类型上,具体取决于这种情况下的情况?

    Doc Model

    1 回复  |  直到 2 年前
        1
  •  0
  •   Frank van Puffelen    2 年前

    是的,这是完全可能的,在Firebase上的文档中有很好的介绍 role based access control 。当您在Firestore文档中定义角色时,以下是示例规则:

    service cloud.firestore {
      match /databases/{database}/documents {
        // For attribute-based access control, Check a boolean `admin` attribute
        allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
        allow read: true;
    
        // Alterntatively, for role-based access, assign specific roles to users
        match /some_collection/{document} {
         allow read: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Reader"
         allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Writer"
       }
      }
    }
    

    在自定义属性中定义角色时的以下规则:

    service cloud.firestore {
      match /databases/{database}/documents {
        // For attribute-based access control, check for an admin claim
        allow write: if request.auth.token.admin == true;
        allow read: true;
    
        // Alterntatively, for role-based access, assign specific roles to users
        match /some_collection/{document} {
         allow read: if request.auth.token.reader == "true";
         allow write: if request.auth.token.writer == "true";
       }
      }
    }
    

    我还建议您从Firebase专家那里查看以下视频: Implementing Authorization Models