LoginSignup
9
6

More than 5 years have passed since last update.

Firebase Storage でメタデータを設定してセキュリティルールに利用する

Posted at

Firebase Storage の閲覧・更新などの権限を細かく設定できます。今回は Storage にアップロードされているファイルのメタデータに基づいて権限を設定する方法を残しておきます。

仕様

  • read は誰でもできる
  • create は認証済みユーザなら誰でもできる
  • update, delete は create したユーザしかできない

ルール

service firebase.storage {
  match /b/{bucket}/o {
    match /json/{allPaths=**} {
      allow read;
      allow create: if request.auth != null;
      allow update, delete: if resource.metadata.owner == request.auth.uid;
    }
  }
}

createif request.auth != null で認証済みユーザのみ許可しています。

update deleteif resource.metadata.owner == request.auth.uid で設定されているメタデータからオーナ ID を参照して一致すれば許可しています。

カスタムメタデータの設定

customMetadata というキーが任意に設定できるフィールドなので、ここに Object を保存することでルールファイルから resource.metadata で参照が可能です。

const meta = {
  cacheControl: 'public,max-age=300',
  contentType: 'application/json',
  customMetadata: { owner: userId }
}
const storageRef = firebase.storage().ref(`json/${id}.json`)
storageRef.putString(JSON.stringify(json), 'raw', meta).then(async () => {
  const url = await storageRef.getDownloadURL()
  console.log(url)
}).catch(err => {
  console.log(err)
})

以上です。

9
6
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
9
6