Skip to content

Instantly share code, notes, and snippets.

@prometeusweb
Last active May 12, 2022 09:40
Show Gist options
  • Select an option

  • Save prometeusweb/85ecb7e2ef1bcb647f7cedefd27d9ee3 to your computer and use it in GitHub Desktop.

Select an option

Save prometeusweb/85ecb7e2ef1bcb647f7cedefd27d9ee3 to your computer and use it in GitHub Desktop.
[Encrypt / Decrypt strings from twig or php] Encrypt or decrypt a string #craft #encrypt #encryption #decrypt #twig #php
{% set token = craft.app.request.get('tkn') %}
{% set decryptedObject = craft.app.security.unmaskToken(token)|json_decode %}
{% set linkValidityIntervalInMinutes = 30 %}
{% set timestamp = ("now"|date('U')) + (60 * linkValidityIntervalInMinutes) %}
{% set objectToBeEncrypted = {"timestamp": timestamp, "assetId": asset.id} %}
{% set token = 'tkn=' ~ craft.app.security.maskToken(objectToBeEncrypted|json_encode) %}
<a href="myurl?{{ token }}">Link</a>
<?php
namespace brilliance\cpxcustomfeatures\controllers;
use Craft;
use craft\elements\Asset;
use craft\web\Controller;
class FileDownloadController extends Controller
{
protected $allowAnonymous = ['secure-download'];
public function actionSecureDownload()
{
$encryptedString = Craft::$app->request->getParam('tk');
$forceDownload = Craft::$app->request->getParam('download') == 'true';
if($encryptedString){
$decryptedString = Craft::$app->security->unmaskToken($encryptedString);
$obj = json_decode($decryptedString);
if($obj->timestamp !== null && $obj->assetId !== null){
$currentTimestamp = time();
if($obj->timestamp > $currentTimestamp){
$storagePath = Craft::getAlias('@root/protected-files');
$asset = Asset::find()->id($obj->assetId)->one();
if($asset){
return Craft::$app->response->sendFile($storagePath . '/' . $asset->filename, $asset->filename, ['inline' => false]);
}
}
else {
return 'The current url validity has expired';
}
}
}
return 'The current url is not valid.';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment