-
Notifications
You must be signed in to change notification settings - Fork 2
BEG-223: Add session expiry warning modal #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aligent-lturner
merged 7 commits into
main
from
feature/BEG-223_Add_session_expiry_warning_modal
Oct 21, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c879472
BEG-223: Add session expiry warning modal
brettlaishley a519ccc
BEG-223: Move to ALL admin views, and use ViewModel
brettlaishley 8e8e90a
BEG-223: Delete renamed variable
brettlaishley ac78bb8
BEG-223: Add view_model to block arguments and update class
brettlaishley f388141
BEG-223: Improve docblock wording choice
brettlaishley 9fd0847
BEG-223 - Add an endpoint to extend the admin session, and make it ca…
aligent-lturner 47a5169
BEG-223 - Use mage/translate being required instead of .mage.__
aligent-lturner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Aligent\Pci4Compatibility\Controller\Adminhtml\Session; | ||
|
|
||
| use Magento\Backend\App\Action; | ||
| use Magento\Backend\App\Action\Context; | ||
| use Magento\Backend\Model\Auth\Session as AuthSession; | ||
| use Magento\Framework\App\Action\HttpPostActionInterface; | ||
| use Magento\Framework\Controller\Result\Json; | ||
| use Magento\Framework\Controller\Result\JsonFactory; | ||
| use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator; | ||
| use Magento\Framework\Exception\LocalizedException; | ||
| use Psr\Log\LoggerInterface; | ||
|
|
||
| /** | ||
| * Controller to extend the admin session via AJAX | ||
| */ | ||
| class ExtendSession extends Action implements HttpPostActionInterface | ||
| { | ||
|
|
||
| /** | ||
| * @param Context $context | ||
| * @param JsonFactory $resultJsonFactory | ||
| * @param AuthSession $authSession | ||
| * @param FormKeyValidator $formKeyValidator | ||
| * @param LoggerInterface $logger | ||
| */ | ||
| public function __construct( | ||
| Context $context, | ||
| private readonly JsonFactory $resultJsonFactory, | ||
| private readonly AuthSession $authSession, | ||
| private readonly FormKeyValidator $formKeyValidator, | ||
| private readonly LoggerInterface $logger | ||
| ) { | ||
| parent::__construct($context); | ||
| } | ||
|
|
||
| /** | ||
| * Execute action to extend the admin session | ||
| * | ||
| * @return Json | ||
| */ | ||
| public function execute(): Json | ||
| { | ||
| $result = $this->resultJsonFactory->create(); | ||
|
|
||
| try { | ||
| // Validate form key for CSRF protection | ||
| if (!$this->formKeyValidator->validate($this->getRequest())) { | ||
| throw new LocalizedException(__('Invalid form key. Please refresh the page.')); | ||
| } | ||
|
|
||
| // Verify the user is still authenticated | ||
| if (!$this->authSession->isLoggedIn()) { | ||
| throw new LocalizedException(__('Session has expired. Please log in again.')); | ||
| } | ||
|
|
||
| // Accessing session data automatically refreshes the session timeout | ||
| // The session lifetime is extended by making this authenticated request | ||
| $this->authSession->prolong(); | ||
|
|
||
| $this->logger->info( | ||
| 'Admin session extended', | ||
| ['user_id' => $this->authSession->getUser()?->getId()] | ||
| ); | ||
|
|
||
| return $result->setData([ | ||
| 'success' => true, | ||
| 'message' => __('Your session has been extended.') | ||
| ]); | ||
| } catch (LocalizedException $e) { | ||
| $this->logger->warning('Failed to extend admin session: ' . $e->getMessage()); | ||
| return $result->setData([ | ||
| 'success' => false, | ||
| 'message' => $e->getMessage() | ||
| ]); | ||
| } catch (\Exception $e) { | ||
| $this->logger->error('Error extending admin session: ' . $e->getMessage()); | ||
| return $result->setData([ | ||
| 'success' => false, | ||
| 'message' => __('An error occurred while extending your session. Please try again.') | ||
| ]); | ||
| } | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Aligent\Pci4Compatibility\ViewModel; | ||
|
|
||
| use Magento\Backend\Model\UrlInterface; | ||
| use Magento\Framework\App\Config\ScopeConfigInterface; | ||
| use Magento\Framework\View\Element\Block\ArgumentInterface; | ||
|
|
||
| class Modal implements ArgumentInterface | ||
| { | ||
| /** | ||
| * @param ScopeConfigInterface $scopeConfig | ||
| * @param UrlInterface $backendUrl | ||
| */ | ||
| public function __construct( | ||
| private readonly ScopeConfigInterface $scopeConfig, | ||
| private readonly UrlInterface $backendUrl, | ||
| ) { | ||
| } | ||
|
|
||
| /** | ||
| * Returns the duration in ms after refresh when the session expiry warning modal should appear | ||
| * | ||
| * @return int | ||
| */ | ||
| public function getModalPopupTimeout(): int | ||
| { | ||
| // This value is in seconds | ||
| $sessionTimeout = $this->scopeConfig->getValue( | ||
| 'admin/security/session_lifetime', | ||
| ScopeConfigInterface::SCOPE_TYPE_DEFAULT | ||
| ); | ||
|
|
||
| // Then we want the popup to appear one minute before timeout | ||
| return ($sessionTimeout - 60) * 1000; | ||
| } | ||
|
|
||
| /** | ||
| * Get the session lifetime in seconds | ||
| * | ||
| * @return int | ||
| */ | ||
| public function getSessionLifetime(): int | ||
| { | ||
| return (int) $this->scopeConfig->getValue( | ||
| 'admin/security/session_lifetime', | ||
| ScopeConfigInterface::SCOPE_TYPE_DEFAULT | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Get URL for extending admin session | ||
| * | ||
| * @return string | ||
| */ | ||
| public function getExtendSessionUrl(): string | ||
| { | ||
| return $this->backendUrl->getUrl('pci4/session/extendsession'); | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| <?xml version="1.0"?> | ||
| <!-- | ||
| /** | ||
| * Copyright © Aligent. All rights reserved. | ||
| */ | ||
| --> | ||
| <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> | ||
| <router id="admin"> | ||
| <route id="pci4" frontName="pci4"> | ||
| <module name="Aligent_Pci4Compatibility"/> | ||
| </route> | ||
| </router> | ||
| </config> |
brettlaishley marked this conversation as resolved.
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| <?xml version="1.0" ?> | ||
| <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> | ||
| <body> | ||
| <referenceContainer name="page.main.actions"> | ||
| <block class="Magento\Backend\Block\Template" name="session.expiry.modal" as="modal" template="Aligent_Pci4Compatibility::modal.phtml"> | ||
| <arguments> | ||
| <argument name="view_model" xsi:type="object">Aligent\Pci4Compatibility\ViewModel\Modal</argument> | ||
| </arguments> | ||
| </block> | ||
| </referenceContainer> | ||
| </body> | ||
| </page> |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| use Aligent\Pci4Compatibility\ViewModel\Modal; | ||
| use Magento\Backend\Block\Template; | ||
| use Magento\Framework\Escaper; | ||
|
|
||
| /** | ||
| * @var Template $block | ||
| * @var Escaper $escaper | ||
| * @var Modal $viewModel | ||
| */ | ||
| $viewModel = $block->getViewModel(); | ||
| $modalTimeout = $viewModel->getModalPopupTimeout(); | ||
| $sessionLifetime = $viewModel->getSessionLifetime(); | ||
| $extendSessionUrl = $viewModel->getExtendSessionUrl(); | ||
|
|
||
| ?> | ||
|
|
||
| <div id="session-expire-warning-modal"> | ||
| <p style="font-size:48px;color:#FF0000">⚠</p> | ||
| <p id="session-warning-message"> | ||
| <?= __( | ||
| 'Your session will expire in one minute. ' . | ||
| 'Please save your changes or extend your session to continue working.' | ||
| ) ?> | ||
| </p> | ||
| <input type="hidden" id="session-extend-url" value="<?= $escaper->escapeUrl($extendSessionUrl) ?>"/> | ||
| <input type="hidden" id="session-lifetime" value="<?= $escaper->escapeHtmlAttr((string)$sessionLifetime) ?>"/> | ||
| </div> | ||
|
|
||
| <script> | ||
| require( | ||
| [ | ||
| 'jquery', | ||
| 'Magento_Ui/js/modal/modal', | ||
| 'mage/translate' | ||
aligent-lturner marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ], | ||
| function( | ||
| $, | ||
| modal, | ||
| $t | ||
| ) { | ||
| let sessionTimeoutHandle = null; | ||
| const sessionLifetime = parseInt($('#session-lifetime').val()) || 900; | ||
| const warningOffset = 60; // Show warning 60 seconds before expiry | ||
|
|
||
| /** | ||
| * Initialize and show the session expiry warning modal | ||
| */ | ||
| function initSessionWarningModal() { | ||
| const options = { | ||
| type: 'popup', | ||
| innerScroll: true, | ||
| title: $t('Session Expiring Soon'), | ||
| modalClass: 'modal-admintimeout', | ||
| buttons: [ | ||
| { | ||
| text: $t('Extend Session'), | ||
| class: 'action-primary', | ||
| click: function () { | ||
| extendSession(this); | ||
| } | ||
| }, | ||
| { | ||
| text: $t('Close'), | ||
| class: 'action-secondary', | ||
| click: function () { | ||
| this.closeModal(); | ||
| } | ||
| } | ||
| ] | ||
| }; | ||
|
|
||
| modal(options, $('#session-expire-warning-modal')); | ||
| } | ||
|
|
||
| /** | ||
| * Schedule the session warning modal to appear | ||
| */ | ||
| function scheduleSessionWarning() { | ||
| // Clear any existing timeout | ||
| if (sessionTimeoutHandle) { | ||
| clearTimeout(sessionTimeoutHandle); | ||
| } | ||
|
|
||
| // Calculate delay: (sessionLifetime - warningOffset) * 1000 milliseconds | ||
| const delay = (sessionLifetime - warningOffset) * 1000; | ||
|
|
||
| sessionTimeoutHandle = setTimeout(function() { | ||
| $('#session-expire-warning-modal').modal('openModal'); | ||
| }, delay); | ||
| } | ||
|
|
||
| /** | ||
| * Extend the admin session via AJAX | ||
| */ | ||
| function extendSession(modalContext) { | ||
| const $message = $('#session-warning-message'); | ||
| const originalMessage = $message.text(); | ||
|
|
||
| // Show loading state | ||
| $message.text($t('Extending your session...')); | ||
|
|
||
| $.ajax({ | ||
| url: $('#session-extend-url').val(), | ||
| type: 'POST', | ||
| dataType: 'json', | ||
| data: { | ||
| form_key: window.FORM_KEY | ||
| }, | ||
| success: function(response) { | ||
| if (response.success) { | ||
| // Show a success message | ||
| $message.text($t('Session extended successfully!')); | ||
|
|
||
| // Close modal after a short delay | ||
| setTimeout(function() { | ||
| modalContext.closeModal(); | ||
| $message.text(originalMessage); | ||
|
|
||
| // Reschedule the warning modal | ||
| scheduleSessionWarning(); | ||
| }, 1500); | ||
| } else { | ||
| // Show error message | ||
| $message.text(response.message || $t('Failed to extend session. Please try again.')); | ||
|
|
||
| // Restore the original message after delay | ||
| setTimeout(function() { | ||
| $message.text(originalMessage); | ||
| }, 3000); | ||
| } | ||
| }, | ||
| error: function() { | ||
| // Show error message | ||
| $message.text($t('An error occurred. Please refresh the page.')); | ||
|
|
||
| // Restore the original message after delay | ||
| setTimeout(function() { | ||
| $message.text(originalMessage); | ||
| }, 3000); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Initialize on document ready | ||
| $(document).ready(function() { | ||
| initSessionWarningModal(); | ||
| scheduleSessionWarning(); | ||
| }); | ||
| } | ||
| ); | ||
| </script> | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.