LoginSignup
14
8

More than 5 years have passed since last update.

Firebase Storage,RealtimeDatabaseの設定ファイルを書いてみた

Last updated at Posted at 2016-10-27

Firebase Storage/RealtimeDatabase
のアクセシビリティルールを自分なりに書いたものです。

public ... 誰でもアクセス・読み書き可能。アプリだけでなく、外部からもアクセス可
common ... アプリからのアクセスは(ユーザ認証していれば)誰でも読み書き可能。チャットなど
settings ... アプリからの読み込みのみ、(ユーザ認証していれば)誰でも可能。設定ファイル、アップデートデータなど
user ... ユーザ自身のみ読み書き可能。セーブデータなど
admin ... 管理者のみ読み書き可能
private ... 誰も読み書きできない(何に使うのか?)

RealtimeDatabaseについては、簡単ですがインデックスも貼っています。
common/game以下に検索したいデータがあり、データのユニークID,ユーザID、作成日時でselectするという想定です。
インデックスはいくつでも貼ることができますが、複合キーは使えません。

Storage

service firebase.storage {
  match /b/xxxx.appspot.com/o {
    match /public/{allPaths=**} {
      allow read, write;
    }
    match /common/{allPaths=**} {
      allow read, write: if request.auth != null;
    }
    match /settings/{allPaths=**} {
      allow read: if request.auth != null;
    }
    match /user/{userId}/{allPaths=**} {
      allow read, write: if request.auth.uid == userId;
    }
    match /admin/{allPaths=**} {
      allow read, write: if request.auth.uid == "管理者のユーザID";
    }
    match /private/{allPaths=**} {
      allow read, write: if false;
    }
    match /{allPaths=**} {
      allow read, write: if false;
    }
  }
}

RealtimeDatabase

{
  "rules": {
    "public": {
        ".read" : true,
        ".write": true,
    },
    "common": {
        ".read" : "auth != null",
        ".write": "auth != null",
        "game":{
          ".indexOn": ["id", "user_id", "created_date"]
        }
    },
    "settings": {
        ".read" : "auth != null",
        ".write": false,
        "game":{
          ".indexOn": ["id", "user_id", "created_date"]
        }
    },
    "user": {
      "$user_id": {
        ".read" : "$user_id === auth.uid",
        ".write": "$user_id === auth.uid",
      }
    },
    "admin": {
        ".read"  : "auth.uid === '管理者のユーザID'",
        ".write" : "auth.uid === '管理者のユーザID'",
    },
    "private": {
        ".read" : false,
        ".write": false,
    },
    ".read" : false,
    ".write": false,
  }
}

インデックスについて

ちなみにインデックスは、自身より深いディレクトリのキーに対して貼ることも可能です。
例えば以下のようなデータ構造になっているとして(NoSQLとして良い構造ではありません)

common
  +-- user
    +-- <$USER_ID>
      +-- id
      +-- item_history
        +-- <$ITEM_ID>
          +-- buy_date
    +-- <$USER_ID>
      +-- id
      +-- item_history
        +-- <$ITEM_ID>
          +-- buy_date

指定のアイテムを指定の日時以降に購入したユーザを検索したいというような時、userディレクトリで buy_dateの値を元に検索クエリを発行することになりますが、その場合

    "user": {
        ".indexOn": ["item_history/<$ITEM_ID>/buy_date"]
    },

と記述することで、クエリを発行することができます。

14
8
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
14
8