Last active
May 12, 2022 09:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {% set token = craft.app.request.get('tkn') %} | |
| {% set decryptedObject = craft.app.security.unmaskToken(token)|json_decode %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {% 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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