Creation permission based on relation?

Hey there,

I want to create what is more or less a ticket system using Directus.

I have a ticket model and a ticket_message model. There’s a one-to-many relation between the two.

How would I set up the permissions so that users can only create ticket messages related to their own tickets?

I’ve tried to set up an access policy, but there I can only create a validation for the ticket_id itself, not for the user_created field on the related item.

Hello,

You can set the field as mentioned in the below image, in that way whoever is creating the ticket it will be stored that user ID

Yes, that’s the approach I currently have for creating tickets.
What I am talking about however is creating ticket messages. I only want users to be able to create messages related to tickets that they have created.


import { defineHook } from '@directus/extensions-sdk';

export default defineHook(({ filter }, { services }) => {
  const { ItemsService } = services;

  filter('ticket_messages.items.create', async (payload, { database, schema, accountability }) => {
    const currentUserId = accountability?.user;

    if (!currentUserId) {
      throw new Error('Unauthorized: No user found in request.');
    }

    const ticketId = payload.ticket_id;

    if (!ticketId) {
      throw new Error('ticket_id is required.');
    }

    const ticketService = new ItemsService('ticket', {
      database,
      schema,
      accountability,
    });

    const ticket = await ticketService.readOne(ticketId, {
      fields: ['id', 'user_created'],
    });

    if (ticket.user_created !== currentUserId) {
      throw new Error('You can only post messages to your own tickets.');
    }

    return payload; // required
  });
});

If you want to solve this solely with permissions, there is an Directus Dev blog post describing a pretty similar use case. (There seems to be a strange redirect for the provided link in place. The url is: https://docs.directus.io/blog/building-a-support-system-in-the-directus-data-studio.html but i guess you have to google for “directus dev blog ticket system”)
(Maybe someone from Directus @bryantgillespie :waving_hand: can figure out, why this url is redirected to https://directus.io/docs/tutorials)

Basically you are looking for a rule limiting the update permission to $CURRENT_USER dynamic variable
(Even this link doesn’t seem to work atm. google for “directus filter rules”)