directus

How can I make changes to a collection in a custom endpoint that is called without proper permissions?


I have an endpoint that is publicly available (accessed by a webpage). Now, I would like to be able to update a certain field of the requested item without having to give the public user overall "write" permissions to that collection. I also do not want to do any authentication because it seems unnecessary. In a way it is not the public user who makes this change but rather "the system".

This is a minimal example which does (obviously) not work because the accountability of the request is passed on and therefore does not have the required permissions to do the update.

export default (router, { services }) => {
  router.get('/getItem/:id', async (req, res) => {
    const itemssService = new services.ItemsService('items', { schema: req.schema, accountability: req.accountability })
    const item = await itemsService.readOne(req.params.id)
    await itemsService.updateOne({
      id: req.params.id,
      last_access: new Date()
    })
    res.send({ item })
  })
}

I am suspecting that my approach might not be best practise but I cannot think of a good alternative. If I understand correctly, emitting an event or calling an action does not "upgrade" permissions in any helpful way. Or am I wrong?


Solution

  • I found a solution to my scenario. Apparently it is neccessary (and possible!) to simply override the authentication:

    export default (router, { services }) => {
      router.get('/getItem/:id', async (req, res) => {
        const itemssService = new services.ItemsService('items', {
          schema: req.schema,
          // use the id of a user with proper permissions
          accountability: { id: '...', admin: true }
        })
        const item = await itemsService.readOne(req.params.id)
        // now changes can be made
        await itemsService.updateOne({
          id: req.params.id,
          last_access: new Date()
        })
        res.send({ item })
      })
    }
    

    It makes sense that some user will be "responsible" for having made the changes to the collection. If this had only been in the docs somewhere ...