LoginSignup
5
5

More than 3 years have passed since last update.

Cloud Firestore のセキュリティルールでよくやる書き方

Posted at

今回は、Cloud Firestore のセキュリティルールでよく書く記法などをまとめていきたいと思います。(他にもでてきたら随時更新していく)

認証系

認証しているユーザのみ読み取りが可能になります。

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

アクセスするドキュメントID がリクエストの uid と一致する場合に読み取りが可能になります。つまり自分のデータだった場合に読み取りが可能になります。

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

Cloud Firestore はドキュメントデータに基づいてルールを動的に作ることが可能なので下記のようなこともできます。便利ですね😄
ちなみに、コメントアウトしてる部分のように絶対パスを指定し、get 関数でドキュメントを取得することも可能です。

service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow update: if resource.data.teacherId == request.auth.uid;
      // allow update: if get(/databases/$(database)/documents/posts/$(postId)).data.teacherId == request.auth.uid;
    }
  }
}

バリデーション系

リクエストのデータに email が存在する場合はドキュメントを作成することができます。

service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow create: if ('email' in request.resource.data);
    }
  }
}

リクエストのデータの emailString だった場合はドキュメントを作成することができます。また、is を使って確認できるデータ型は下記の通りです。詳しくはこちらを参照してください。

  • string
  • int
  • float
  • bool
  • null
  • timestamp
  • list
  • map
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow create: if (request.resource.data.email is string);
    }
  }
}

リクエストのデータの email のサイズが3文字以上かつ254文字以下だった場合はドキュメントを作成することができます。

service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow create: if (request.resource.data.email.size() >= 3) && (request.resource.data.email.size() <= 254);
    }
  }

その他

User テーブルに自分の uid と一致するテーブルが存在するユーザのみ読み取りが可能になります。

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read: if exists(/databases/$(database)/documents/users/$(request.auth.uid));
    }
  }
}

下記は使用頻度が高いのでカスタム関数として切り出しておくと便利です。

    function isAuthenticated() {
      return request.auth != null;
    }
    function isUserAuthenticated(userId) {
      return request.auth != null && userId == request.auth.uid;
    }
    function requestData() {
      return request.resource.data;
    }

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5