Firebase Storage Rules with Custom Claims

前端 未结 3 1165
野趣味
野趣味 2021-01-15 11:06

I am unable to get Firebase Storage work with custom rules and using custom claims.

In my Python Admin panel, I do the following to create the user and assign a clai

3条回答
  •  没有蜡笔的小新
    2021-01-15 11:20

    Custom claims are the only way to do this right now. Rules should look like this:

    service firebase.storage {
      match /b/{bucket}/o {
        function isAuth() {
          return request.auth != null && request.auth.uid != null
        }
        function isAdmin() {
          return isAuth() &&
          request.auth.token.admin == true;
        }
        function clientMatch(clientId) { // expects user's "client" field to be ID of client
          return isAuth() &&
          clientId == request.auth.token.clientId;
        }
        match /storage/path/{clientId}/{allPaths=**} {
            allow read, write: if isAdmin() || clientMatch(clientId)
        }
    

    where we use two custom fields on the auth token: admin and clientId. The cloud function to sync with the db can look something like this:

    exports.updateUser = functions.firestore
      .document('users/{userId}')
      .onWrite( async (change, context) => {
        // change.before and change.after are DocumentSnapshot objects
        const userid=context.params.userId // (from {userId} above)
        const isDeleted = !change.after.exists
        const isNew = !change.before.exists
        let customClaims = {}
        if (!isDeleted) {
          let newData = change.after.data()
          let oldData = change.before.data()
          // do we need to update anything?
          if (isNew ||
              newData.admin !== oldData.admin ||
              newData.client !== oldData.client) {
            customClaims.admin = Boolean(newData.admin)
            customClaims.clientId = newData.client
          }
        }
        else {
          let oldData = change.before.data()
          customClaims.admin = false
          customClaims.clientId = null
        }
        // now do the update if needed
        if (customClaims !== {}) {
          // See https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth
          await admin.auth().setCustomUserClaims(userid, customClaims)
          console.log(`Updating client for ${isNew?"new":"existing"} user ${userid}: ` +
                      `${JSON.stringify(customClaims)}`)
        }
      })
    

    That runs on any change to the user document, and syncs it to the auth's custom claims.

提交回复
热议问题