Updating users roles via Netlify Serverless function (When logged in as another user)

So, according to the discussion we had, the code was working fine for a small number of users. But, @carvill had around 14k users where this code was failing. Chances are, the size of the users array was getting more than what a serverless function could handle. Thus, the solution was to store the identity user ID in an external database which you can query. Then, you just have to pass the ID with the payload and in the function, change role like:

const fetch = require('node-fetch')

exports.handler =  async (event, context) => {
  const payload = JSON.parse(event.body)
  const identity = context.clientContext.identity
  return fetch(`${identity.url}/admin/users/${payload.netlifyId}`, {
    method: 'put',
    body: JSON.stringify({
      app_metadata: {
        roles: [payload.role]
      }
    }),
    headers: {
      Authorization: `Bearer ${identity.token}`
    }
  }).then(response => {
    return response.json()
  }).then(updatedUser => {
    return {
      statusCode: 200,
      body: JSON.stringify(updatedUser)
    }
  })
}
1 Like