masugadesign/link-vault-craft-cms

Stop a download in the EVENT_LINK_CLICK event

Closed this issue · 2 comments

I have this code in a module which checks the totalDownloads and if it exceeds 5, to prevent the download, how do i stop the download from happening? i have tried returning null, false , i have also tried returning a 403 status code, they all still allow the download to happen.

Event::on(LinkVaultController::class,
  LinkVaultController::EVENT_LINK_CLICK,
    function (LinkClickEvent $event) {
      $user = Craft::$app->getUser()->getIdentity();
      if ($user) {
        $totalAllowedDownloads = 5;
        $totalDownloads = \Masuga\LinkVault\LinkVault::getInstance()->general->totalDownloads(['userId' => $user->id]);
        if ($totalDownloads >= $totalAllowedDownloads) {
          // stop download here
        }
    }
  }
);

When you say that you returned a 403 status code, are you doing it in the form of throwing an exception? I feel like that should be enough.

throw new \yii\web\ForbiddenHttpException("You reached the download limit.");

If that isn't enough, try overriding the Craft response, running sendAndClose() on it, then running exit() just to avoid any further manipulation of the response.

Thanks @benjaminkohl I managed to get it to work using that, i attempted the same using Craft::$app->getResponse()->setStatusCode(...); but your way worked.