55
66use Closure ;
77use Magento \Framework \App \Config \ScopeConfigInterface ;
8+ use Magento \Framework \App \State ;
89use Magento \Framework \Exception \AuthenticationException ;
910use Magento \Framework \Exception \InputException ;
1011use Magento \Framework \Exception \LocalizedException ;
1718 */
1819class BypassTwoFactorAuthForApiTokenGeneration
1920{
20- const XML_PATH_CONFIG_ENABLE_FOR_API_TOKEN_GENERATION = 'twofactorauth/general/enable_for_api_token_generation ' ;
21+ /** @var AdminTokenServiceInterface */
22+ private $ adminTokenService ;
2123
2224 /** @var ScopeConfigInterface */
2325 private $ scopeConfig ;
2426
25- /** @var AdminTokenServiceInterface */
26- private $ adminTokenService ;
27+ /** @var State */
28+ private $ appState ;
2729
2830 /**
2931 * BypassTwoFactorAuthForApiTokenGeneration constructor.
3032 * @param AdminTokenServiceInterface $adminTokenService
3133 * @param ScopeConfigInterface $scopeConfig
34+ * @param State $appState
3235 */
3336 public function __construct (
3437 AdminTokenServiceInterface $ adminTokenService ,
35- ScopeConfigInterface $ scopeConfig
38+ ScopeConfigInterface $ scopeConfig ,
39+ State $ appState
3640 ) {
3741 $ this ->scopeConfig = $ scopeConfig ;
3842 $ this ->adminTokenService = $ adminTokenService ;
43+ $ this ->appState = $ appState ;
3944 }
4045
4146 /**
4247 * Enables the bypass of 2FA for API token generation.
43- * This can be useful for third-party vendors during module development.
48+ * This can be useful for within development & integration environments.
49+ *
50+ * If 2FA is enabled, return the original result.
51+ * If developer mode is enabled, 2FA is disabled unless "Disable 2FA in developer mode" is set to No.
52+ *
53+ * Calling createAdminAccessToken within this function bypasses 2FA.
4454 *
4555 * NOTE: Always keep 2FA enabled within production environments for security purposes.
4656 *
@@ -59,7 +69,19 @@ public function aroundCreateAdminAccessToken(
5969 $ username ,
6070 $ password
6171 ): string {
62- return $ this ->scopeConfig ->isSetFlag (self ::XML_PATH_CONFIG_ENABLE_FOR_API_TOKEN_GENERATION )
72+ $ is2faEnabled = $ this ->scopeConfig ->isSetFlag (
73+ BypassTwoFactorAuth::XML_PATH_CONFIG_ENABLE_FOR_API_TOKEN_GENERATION
74+ );
75+ $ isDeveloperMode = $ this ->appState ->getMode () == State::MODE_DEVELOPER ;
76+ $ alwaysDisableInDeveloperMode = $ this ->scopeConfig ->isSetFlag (
77+ BypassTwoFactorAuth::XML_PATH_CONFIG_DISABLE_IN_DEVELOPER_MODE
78+ );
79+
80+ if ($ isDeveloperMode && $ alwaysDisableInDeveloperMode ) {
81+ $ is2faEnabled = false ;
82+ }
83+
84+ return $ is2faEnabled
6385 ? $ proceed ($ username , $ password )
6486 : $ this ->adminTokenService ->createAdminAccessToken ($ username , $ password );
6587 }
0 commit comments