I have a front-end form where logged users can upload and delete their personal files.
These users have the strict minimum permissions required to interact with this form. They can only Create, Publish and Delete their own entries in the section where the form create these entries.
In order to be able to delete these files from Craft (and not from only the field they're linked in this entry), I have created this custom action in a module:
<?php
namespace modules\mymodule\controllers;
use Craft;
use craft\web\Controller;
use craft\elements\Asset;
class DefaultController extends Controller
{
public function actionDeleteAsset()
{
$this->requireAcceptsJson();
$this->requireLogin();
$currentUser = Craft::$app->getUser()->getIdentity();
if (!$currentUser) {
return $this->asErrorJson(Craft::t('app', 'Only a logged in user can delete an asset.'));
} else {
$request = Craft::$app->getRequest();
$assetId = $request->getParam('assetId', '');
$asset = Craft::$app->getAssets()->getAssetById($assetId);
if (!empty($asset)) {
if (!Craft::$app->getUser()->checkPermission('deleteFilesAndFoldersInVolume:' . $asset->volumeId)) {
return $this->asErrorJson(Craft::t('app', 'You don\'t have permission to delete this asset.'));
} else {
Craft::$app->getElements()->deleteElementById($asset->id, Asset::class);
return $this->asJson([
'success' => true
]);
}
} else {
return $this->asErrorJson(Craft::t('app', 'This asset does not exists or has already been deleted.'));
}
}
}
}
The problem is that Craft::$app->getUser()->checkPermission('deleteFilesAndFoldersInVolume:' . $asset->volumeId)
is not entirely appropriate:
- I need to add Volume permissions (View volume + Remove files and folders) to these users to allow them to delete their assets from the front-end form ;
- By adding these permissions, they have access to other users' assets, which is a security problem ;
So how can I check if user has the permissions to delete only his own assets? In other words, this user can only interact with the assets he has uploaded.
users
field to the asset and relate it to all users that may delete it. If the user is not related to the asset -> he can't delete it