As the title says I have a Custom Module with a Custom Field that does some AJAX requests (for example delete in helper database table of the module). The AJAX itself works:
field.php:
...
private function buildRow(\stdClass $eventData):string
{
$rowHtml = "<div data-event-id='{$eventData->id}' class='event-card card bg-light mb-3'><div class='card-body'><div class='row'>";
$rowHtml .= "<div class='col-sm'><b>{$eventData->summary}</b></div>";
$rowHtml .= "<div class='col-sm'>{$eventData->dtstart}</div>";
$rowHtml .= "<div class='col-sm'>{$eventData->dtend}</div>";
$rowHtml .= "<div class='col-sm'><div class='text-end'><button class='btn btn-sm btn-danger remove-event-btn' data-event-id='{$eventData->id}'><i class='fa-solid fa-trash'></i></button></div></div>";
$rowHtml .= "</div></div></div>";
return $rowHtml;
}
...
Script:
...
function deleteEvent(eventId) {
const request = {
'eventId': eventId,
'format': 'json',
'option': 'com_ajax',
'module': 'nxd_nce',
'method': 'deleteEvent'
};
return jQuery.ajax({
url: '/index.php',
type: 'POST',
data: request,
});
}
...
As you can see every event element from the helper table will be listed and has a delete button with event-id data attr. The helper PHP code awaits these AJAX calls like this (inwork does nothing atm):
public function deleteEventAjax(): AjaxResponseModel
{
$input = Factory::getApplication()->input;
$eventId = $input->get('eventId', null, 'number');
error_log("Delete Event Ajax");
error_log("EventId: " . $eventId);
$ajax = new AjaxResponseModel();
$ajax->success = true;
$ajax->msg = "Events Deleted";
$ajax->data = [$eventId];
return $ajax;
}
My question is: How can i secure this AJAX call? I've seen a lot about Session and Form Token but have no clue on how to embed it - i Think a Form Token could be set by adding it directly to the URL call (using a token attribute in the field PHP on the button and get it that way in JS to place it in the URL) would that be the trick?
Edit: I've found. the "Issue" why i cannot simply can use the following in the AJAX Method:
...
$identity = Factory::getApplication()->getIdentity();
...
Since the AJAX Method in the Helper is for the Frontend i can call it also from within the backend but when Shared Sessions are disabled The current User cannot be identified because the Session Cookie is missing because it is not valid in the Frontend...