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.
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.
You will have to create a custom extension, I have shared an example below
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
});
});
Thanks! That looks promising. Although a bit unfortunate that this needs an extension. Could you by any chance help me out a bit with how I could make this limitation only apply to users with a specific access policy?
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”)
I've looked at the guide, but it seems really weird. It sets up permissions to access ticket messages for agents, but never for users. Thus users can't see or create messages in their ticket, which is what I'd need.
My bad, i just realized what exactly is going on (the failed links drew too much of my attention). Backcrawling of a M2O relationship seems still not to be supported. I think you have to use a custom hook as @ahmad_quvor proposed.
You will have to create a custom extension, I have shared an example below
– ahmad_quvor