|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace MarkShust\DisableTwoFactorAuth\Plugin; |
| 5 | + |
| 6 | +use Closure; |
| 7 | +use Magento\Framework\App\Config\ScopeConfigInterface; |
| 8 | +use Magento\Framework\Exception\AuthenticationException; |
| 9 | +use Magento\Framework\Exception\InputException; |
| 10 | +use Magento\Framework\Exception\LocalizedException; |
| 11 | +use Magento\Integration\Api\AdminTokenServiceInterface; |
| 12 | +use Magento\TwoFactorAuth\Model\AdminAccessTokenService; |
| 13 | + |
| 14 | +/** |
| 15 | + * Class BypassWebApiTwoFactorAuth |
| 16 | + * @package MarkShust\DisableTwoFactorAuth\Plugin |
| 17 | + */ |
| 18 | +class BypassTwoFactorAuthForApiTokenGeneration |
| 19 | +{ |
| 20 | + const XML_PATH_CONFIG_ENABLE_FOR_API_TOKEN_GENERATION = 'twofactorauth/general/enable_for_api_token_generation'; |
| 21 | + |
| 22 | + /** @var ScopeConfigInterface */ |
| 23 | + private ScopeConfigInterface $scopeConfig; |
| 24 | + |
| 25 | + /** @var AdminTokenServiceInterface */ |
| 26 | + private AdminTokenServiceInterface $adminTokenService; |
| 27 | + |
| 28 | + /** |
| 29 | + * BypassTwoFactorAuthForApiTokenGeneration constructor. |
| 30 | + * @param AdminTokenServiceInterface $adminTokenService |
| 31 | + * @param ScopeConfigInterface $scopeConfig |
| 32 | + */ |
| 33 | + public function __construct( |
| 34 | + AdminTokenServiceInterface $adminTokenService, |
| 35 | + ScopeConfigInterface $scopeConfig |
| 36 | + ) { |
| 37 | + $this->scopeConfig = $scopeConfig; |
| 38 | + $this->adminTokenService = $adminTokenService; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Enables the bypass of 2FA for API token generation. |
| 43 | + * This can be useful for third-party vendors during module development. |
| 44 | + * |
| 45 | + * NOTE: Always keep 2FA enabled within production environments for security purposes. |
| 46 | + * |
| 47 | + * @param AdminAccessTokenService $subject |
| 48 | + * @param Closure $proceed |
| 49 | + * @param $username |
| 50 | + * @param $password |
| 51 | + * @return string |
| 52 | + * @throws AuthenticationException |
| 53 | + * @throws InputException |
| 54 | + * @throws LocalizedException |
| 55 | + */ |
| 56 | + public function aroundCreateAdminAccessToken( |
| 57 | + AdminAccessTokenService $subject, |
| 58 | + Closure $proceed, |
| 59 | + $username, |
| 60 | + $password |
| 61 | + ): string { |
| 62 | + return $this->scopeConfig->isSetFlag(self::XML_PATH_CONFIG_ENABLE_FOR_API_TOKEN_GENERATION) |
| 63 | + ? $proceed($username, $password) |
| 64 | + : $this->adminTokenService->createAdminAccessToken($username, $password); |
| 65 | + } |
| 66 | +} |
0 commit comments