Example #1
0
 /**
  * {@inheritdoc}
  */
 public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
     /** @var State[] $stateIndexers */
     $stateIndexers = [];
     $states = $this->statesFactory->create();
     foreach ($states->getItems() as $state) {
         /** @var State $state */
         $stateIndexers[$state->getIndexerId()] = $state;
     }
     foreach ($this->config->getIndexers() as $indexerId => $indexerConfig) {
         $expectedHashConfig = $this->encryptor->hash($this->encoder->encode($indexerConfig), Encryptor::HASH_VERSION_MD5);
         if (isset($stateIndexers[$indexerId])) {
             if ($stateIndexers[$indexerId]->getHashConfig() != $expectedHashConfig) {
                 $stateIndexers[$indexerId]->setStatus(StateInterface::STATUS_INVALID);
                 $stateIndexers[$indexerId]->setHashConfig($expectedHashConfig);
                 $stateIndexers[$indexerId]->save();
             }
         } else {
             /** @var State $state */
             $state = $this->stateFactory->create();
             $state->loadByIndexer($indexerId);
             $state->setHashConfig($expectedHashConfig);
             $state->setStatus(StateInterface::STATUS_INVALID);
             $state->save();
         }
     }
 }
 public function __construct(ClientInterface $client, OpenpayExceptionMapper $exceptionMapper, OpenpayFeeValidator $validator, OpenpayTransactionMapper $transactionMapper, EncryptorInterface $encryptor, ScopeConfigInterface $config)
 {
     $paymentOpenpayConfig = $config->getValue('payment/openpay');
     $paymentOpenpayConfig['merchantId'] = $encryptor->decrypt($paymentOpenpayConfig['merchantId']);
     $paymentOpenpayConfig['apiKey'] = $encryptor->decrypt($paymentOpenpayConfig['apiKey']);
     $paymentOpenpayConfig['publicKey'] = $encryptor->decrypt($paymentOpenpayConfig['publicKey']);
     parent::__construct($client, $exceptionMapper, $validator, $transactionMapper, $paymentOpenpayConfig);
 }
 /**
  * Generate vault payment public hash
  *
  * @param PaymentTokenInterface $paymentToken
  * @return string
  */
 protected function generatePublicHash(PaymentTokenInterface $paymentToken)
 {
     $hashKey = $paymentToken->getGatewayToken();
     if ($paymentToken->getCustomerId()) {
         $hashKey = $paymentToken->getCustomerId();
     }
     $hashKey .= $paymentToken->getPaymentMethodCode() . $paymentToken->getType() . $paymentToken->getTokenDetails();
     return $this->encryptor->getHash($hashKey);
 }
 /**
  * {@inheritdoc}
  */
 public function get($storeId = null)
 {
     /** @var CredentialsInterface $credentials */
     $credentials = $this->credentialsFactory->create();
     $configValues = $this->scopeConfig->getValue(self::PAYMENT_OPENPAY_PATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
     $merchantId = $this->encryptor->decrypt($configValues['merchantId']);
     $publicKey = $this->encryptor->decrypt($configValues['publicKey']);
     $credentials->setMerchantId($merchantId)->setPublicKey($publicKey)->setIsSandboxMode($configValues['sandbox']);
     return $credentials;
 }
 /**
  * Upgrade customer password hash when customer has logged in
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return void
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $password = $observer->getEvent()->getData('password');
     /** @var \Magento\Customer\Model\Customer $model */
     $model = $observer->getEvent()->getData('model');
     $customer = $this->customerRepository->getById($model->getId());
     $customerSecure = $this->customerRegistry->retrieveSecureData($model->getId());
     if (!$this->encryptor->validateHashVersion($customerSecure->getPasswordHash(), true)) {
         $customerSecure->setPasswordHash($this->encryptor->getHash($password, true));
         $this->customerRepository->save($customer);
     }
 }
Example #6
0
 public function testExecuteNonRandomAndWithCryptKey()
 {
     $expectedMessage = 'The encryption key has been changed.';
     $key = 1;
     $newKey = 'RSASHA9000VERYSECURESUPERMANKEY';
     $this->requestMock->expects($this->at(0))->method('getPost')->with($this->equalTo('generate_random'))->willReturn(0);
     $this->requestMock->expects($this->at(1))->method('getPost')->with($this->equalTo('crypt_key'))->willReturn($key);
     $this->encryptMock->expects($this->once())->method('validateKey');
     $this->changeMock->expects($this->once())->method('changeEncryptionKey')->willReturn($newKey);
     $this->managerMock->expects($this->once())->method('addSuccessMessage')->with($expectedMessage);
     $this->cacheMock->expects($this->once())->method('clean');
     $this->responseMock->expects($this->once())->method('setRedirect');
     $this->model->execute();
 }
 /**
  * Save current admin password to prevent its usage when changed in the future.
  *
  * @param EventObserver $observer
  * @return void
  */
 public function execute(EventObserver $observer)
 {
     /* @var $user \Magento\User\Model\User */
     $user = $observer->getEvent()->getObject();
     if ($user->getId()) {
         $password = $user->getCurrentPassword();
         $passwordLifetime = $this->observerConfig->getAdminPasswordLifetime();
         if ($passwordLifetime && $password && !$user->getForceNewPassword()) {
             $passwordHash = $this->encryptor->getHash($password, false);
             $this->userResource->trackPassword($user, $passwordHash, $passwordLifetime);
             $this->messageManager->getMessages()->deleteMessageByIdentifier('magento_user_password_expired');
             $this->authSession->unsPciAdminUserIsPasswordExpired();
         }
     }
 }
 /**
  * Admin locking and password hashing upgrade logic implementation
  *
  * @param EventObserver $observer
  * @return void
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function execute(EventObserver $observer)
 {
     $password = $observer->getEvent()->getPassword();
     /** @var User $user */
     $user = $observer->getEvent()->getUser();
     $authResult = $observer->getEvent()->getResult();
     if (!$authResult && $user->getId()) {
         // update locking information regardless whether user locked or not
         $this->_updateLockingInformation($user);
     }
     // check whether user is locked
     $lockExpires = $user->getLockExpires();
     if ($lockExpires) {
         $lockExpires = new \DateTime($lockExpires);
         if ($lockExpires > new \DateTime()) {
             throw new UserLockedException(__('You did not sign in correctly or your account is temporarily disabled.'));
         }
     }
     if (!$authResult) {
         return;
     }
     $this->userResource->unlock($user->getId());
     $latestPassword = $this->userResource->getLatestPassword($user->getId());
     $this->_checkExpiredPassword($latestPassword);
     if (!$this->encryptor->validateHashVersion($user->getPassword(), true)) {
         $user->setPassword($password)->setData('force_new_password', true)->save();
     }
 }
 public function testAdminAuthenticate()
 {
     $password = "******";
     $uid = 123;
     $authResult = true;
     $lockExpires = false;
     $userPassword = ['expires' => 1];
     /** @var Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */
     $eventObserverMock = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var Event|\PHPUnit_Framework_MockObject_MockObject */
     $eventMock = $this->getMockBuilder('Magento\\Framework\\Event')->disableOriginalConstructor()->setMethods(['getPassword', 'getUser', 'getResult'])->getMock();
     /** @var ModelUser|\PHPUnit_Framework_MockObject_MockObject $userMock */
     $userMock = $this->getMockBuilder('Magento\\User\\Model\\User')->disableOriginalConstructor()->setMethods(['getId', 'getLockExpires', 'getPassword', 'save'])->getMock();
     $eventObserverMock->expects($this->atLeastOnce())->method('getEvent')->willReturn($eventMock);
     $eventMock->expects($this->once())->method('getPassword')->willReturn($password);
     $eventMock->expects($this->once())->method('getUser')->willReturn($userMock);
     $eventMock->expects($this->once())->method('getResult')->willReturn($authResult);
     $userMock->expects($this->atLeastOnce())->method('getId')->willReturn($uid);
     $userMock->expects($this->once())->method('getLockExpires')->willReturn($lockExpires);
     $this->userMock->expects($this->once())->method('unlock');
     $this->userMock->expects($this->once())->method('getLatestPassword')->willReturn($userPassword);
     $this->configInterfaceMock->expects($this->atLeastOnce())->method('getValue')->willReturn(1);
     /** @var Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */
     $collectionMock = $this->getMockBuilder('Magento\\Framework\\Message\\Collection')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->managerInterfaceMock->expects($this->once())->method('getMessages')->willReturn($collectionMock);
     $collectionMock->expects($this->once())->method('getLastAddedMessage')->willReturn($this->messageInterfaceMock);
     $this->messageInterfaceMock->expects($this->once())->method('setIdentifier')->willReturnSelf();
     $this->authSessionMock->expects($this->once())->method('setPciAdminUserIsPasswordExpired');
     $this->encryptorMock->expects($this->once())->method('validateHashVersion')->willReturn(false);
     $this->model->execute($eventObserverMock);
 }
 /**
  * {@inheritdoc}
  */
 public function authenticate($username, $password)
 {
     try {
         switch ($this->advancedLoginConfigProvider->getLoginMode()) {
             case LoginMode::LOGIN_TYPE_ONLY_ATTRIBUTE:
                 $customer = $this->loginViaCustomerAttributeOnly($username);
                 break;
             case LoginMode::LOGIN_TYPE_BOTH:
                 $customer = $this->loginViaCustomerAttributeOrEmail($username);
                 break;
             default:
                 $customer = $this->loginViaEmailOnly($username);
                 break;
         }
     } catch (NoSuchEntityException $e) {
         throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
     }
     $this->checkPasswordStrength($password);
     $hash = $this->customerRegistry->retrieveSecureData($customer->getId())->getPasswordHash();
     if (!$this->encryptor->validateHash($password, $hash)) {
         throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
     }
     if ($customer->getConfirmation() && $this->isConfirmationRequired($customer)) {
         throw new EmailNotConfirmedException(__('This account is not confirmed.'));
     }
     $customerModel = $this->customerFactory->create()->updateData($customer);
     $this->eventManager->dispatch('customer_customer_authenticated', ['model' => $customerModel, 'password' => $password]);
     $this->eventManager->dispatch('customer_data_object_login', ['customer' => $customer]);
     return $customer;
 }
Example #11
0
 /**
  * Create physical certificate file based on DB data
  *
  * @param string $file
  * @return void
  */
 protected function _createCertFile($file)
 {
     if ($this->varDirectory->isDirectory(self::BASEPATH_PAYPAL_CERT)) {
         $this->_removeOutdatedCertFile();
     }
     $this->varDirectory->writeFile($file, $this->encryptor->decrypt($this->getContent()));
 }
Example #12
0
 /**
  * Generate secret key for controller and action based on form key
  *
  * @param string $routeName
  * @param string $controller Controller name
  * @param string $action Action name
  * @return string
  */
 public function getSecretKey($routeName = null, $controller = null, $action = null)
 {
     $salt = $this->formKey->getFormKey();
     $request = $this->_getRequest();
     if (!$routeName) {
         if ($request->getBeforeForwardInfo('route_name') !== null) {
             $routeName = $request->getBeforeForwardInfo('route_name');
         } else {
             $routeName = $request->getRouteName();
         }
     }
     if (!$controller) {
         if ($request->getBeforeForwardInfo('controller_name') !== null) {
             $controller = $request->getBeforeForwardInfo('controller_name');
         } else {
             $controller = $request->getControllerName();
         }
     }
     if (!$action) {
         if ($request->getBeforeForwardInfo('action_name') !== null) {
             $action = $request->getBeforeForwardInfo('action_name');
         } else {
             $action = $request->getActionName();
         }
     }
     $secret = $routeName . $controller . $action . $salt;
     return $this->_encryptor->getHash($secret);
 }
Example #13
0
 public function testDecrypt()
 {
     $data = 'data';
     $encryptedData = 'd1a2t3a4';
     $this->encryptorInterfaceMock->expects($this->once())->method('decrypt')->with($encryptedData)->will($this->returnValue($data));
     $this->assertEquals($data, $this->info->decrypt($encryptedData));
 }
 /**
  * Run test for saveTokenWithPaymentLink method
  */
 public function testSaveTokenWithPaymentLinkWithDuplicateTokenNotVisible()
 {
     /** @var OrderPaymentInterface|\PHPUnit_Framework_MockObject_MockObject $paymentMock */
     $paymentMock = $this->getMock(OrderPaymentInterface::class);
     /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $tokenMock */
     $tokenMock = $this->getMock(PaymentTokenInterface::class);
     /** @var PaymentTokenInterface|\PHPUnit_Framework_MockObject_MockObject $duplicateToken */
     $duplicateToken = $this->getMock(PaymentTokenInterface::class);
     $entityId = 1;
     $newEntityId = 1;
     $paymentId = 1;
     $customerId = 1;
     $gatewayToken = 'xs4vf3';
     $publicHash = 'existing-token';
     $duplicateTokenData = ['entity_id' => $entityId];
     $newHash = 'new-token2';
     $tokenMock->expects(static::atLeastOnce())->method('getPublicHash')->willReturn($publicHash);
     $tokenMock->expects(static::atLeastOnce())->method('getCustomerId')->willReturn($customerId);
     $this->paymentTokenResourceModelMock->expects(self::once())->method('getByPublicHash')->with($publicHash, $customerId)->willReturn($duplicateTokenData);
     $this->paymentTokenFactoryMock->expects(self::once())->method('create')->with(['data' => $duplicateTokenData])->willReturn($duplicateToken);
     $tokenMock->expects(static::atLeastOnce())->method('getIsVisible')->willReturn(false);
     $tokenMock->expects(static::atLeastOnce())->method('getCustomerId')->willReturn($customerId);
     $tokenMock->expects(static::atLeastOnce())->method('getGatewayToken')->willReturn($gatewayToken);
     $this->encryptorMock->expects(static::once())->method('getHash')->with($publicHash . $gatewayToken)->willReturn($newHash);
     $tokenMock->expects(static::once())->method('setPublicHash')->with($newHash);
     $this->paymentTokenRepositoryMock->expects(self::once())->method('save')->with($tokenMock);
     $tokenMock->expects(static::atLeastOnce())->method('getEntityId')->willReturn($newEntityId);
     $paymentMock->expects(self::atLeastOnce())->method('getEntityId')->willReturn($paymentId);
     $this->paymentTokenResourceModelMock->expects(static::once())->method('addLinkToOrderPayment')->with($newEntityId, $paymentId);
     $this->paymentTokenManagement->saveTokenWithPaymentLink($tokenMock, $paymentMock);
 }
Example #15
0
 public function testVerifyIdentityNoAssignedRoles()
 {
     $password = '******';
     $this->_encryptorMock->expects($this->once())->method('validateHash')->with($password, $this->_model->getPassword())->will($this->returnValue(true));
     $this->_model->setIsActive(true);
     $this->_resourceMock->expects($this->once())->method('hasAssigned2Role')->will($this->returnValue(false));
     $this->setExpectedException('Magento\\Framework\\Exception\\AuthenticationException', 'Access denied.');
     $this->_model->verifyIdentity($password);
 }
Example #16
0
 /**
  * @desc Retrieve the webserver password
  * @return string
  */
 public function getWsPassword()
 {
     if ($this->isDemoMode()) {
         $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test')));
     } else {
         $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live')));
     }
     return $wsPassword;
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testCreateAccountWithPassword()
 {
     $websiteId = 1;
     $storeId = null;
     $defaultStoreId = 1;
     $customerId = 1;
     $customerEmail = '*****@*****.**';
     $password = '******';
     $hash = '4nj54lkj5jfi03j49f8bgujfgsd';
     $newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu';
     $templateIdentifier = 'Template Identifier';
     $sender = 'Sender';
     $this->string->expects($this->any())->method('strlen')->willReturnCallback(function ($string) {
         return strlen($string);
     });
     $this->encryptor->expects($this->once())->method('getHash')->with($password, true)->willReturn($hash);
     $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     $address->expects($this->once())->method('setCustomerId')->with($customerId);
     $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $store->expects($this->once())->method('getId')->willReturn($defaultStoreId);
     $website = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->getMock();
     $website->expects($this->atLeastOnce())->method('getStoreIds')->willReturn([1, 2, 3]);
     $website->expects($this->once())->method('getDefaultStore')->willReturn($store);
     $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $customer->expects($this->atLeastOnce())->method('getEmail')->willReturn($customerEmail);
     $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId);
     $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId);
     $customer->expects($this->once())->method('setStoreId')->with($defaultStoreId);
     $customer->expects($this->once())->method('getAddresses')->willReturn([$address]);
     $customer->expects($this->once())->method('setAddresses')->with(null);
     $this->customerRepository->expects($this->once())->method('get')->with($customerEmail)->willReturn($customer);
     $this->share->expects($this->once())->method('isWebsiteScope')->willReturn(true);
     $this->storeManager->expects($this->atLeastOnce())->method('getWebsite')->with($websiteId)->willReturn($website);
     $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer);
     $this->addressRepository->expects($this->atLeastOnce())->method('save')->with($address);
     $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer);
     $this->random->expects($this->once())->method('getUniqueHash')->willReturn($newLinkToken);
     $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock();
     $customerSecure->expects($this->any())->method('setRpToken')->with($newLinkToken);
     $customerSecure->expects($this->any())->method('setRpTokenCreatedAt');
     $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash);
     $this->customerRegistry->expects($this->atLeastOnce())->method('retrieveSecureData')->willReturn($customerSecure);
     $this->dataObjectProcessor->expects($this->once())->method('buildOutputDataArray')->willReturn([]);
     $this->scopeConfig->expects($this->at(1))->method('getValue')->with(AccountManagement::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId)->willReturn($templateIdentifier);
     $this->scopeConfig->expects($this->at(2))->method('getValue')->willReturn($sender);
     $transport = $this->getMockBuilder('Magento\\Framework\\Mail\\TransportInterface')->getMock();
     $this->transportBuilder->expects($this->once())->method('setTemplateIdentifier')->with($templateIdentifier)->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setTemplateOptions')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setTemplateVars')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setFrom')->with($sender)->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('addTo')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('getTransport')->willReturn($transport);
     $transport->expects($this->once())->method('sendMessage');
     $this->accountManagement->createAccount($customer, $password);
 }
Example #18
0
 /**
  * Gather saved credit card numbers from sales order payments and re-encrypt them
  *
  * @return void
  */
 protected function _reEncryptCreditCardNumbers()
 {
     $table = $this->getTable('sales_order_payment');
     $select = $this->getConnection()->select()->from($table, ['entity_id', 'cc_number_enc']);
     $attributeValues = $this->getConnection()->fetchPairs($select);
     // save new values
     foreach ($attributeValues as $valueId => $value) {
         $this->getConnection()->update($table, ['cc_number_enc' => $this->encryptor->encrypt($this->encryptor->decrypt($value))], ['entity_id = ?' => (int) $valueId]);
     }
 }
Example #19
0
 public function getBackendCfg()
 {
     $cfg = [];
     $cfg['key'] = $this->_encryptor->decrypt($this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/main_options/backend_accesstoken', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)));
     $cfg['enabled'] = $this->scopeConfig->isSetFlag('cc_uk/main_options/backend_enabled', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     $cfg['auto_search'] = $this->scopeConfig->isSetFlag('cc_uk/gfx_options/searchbar_auto_search', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     $cfg['clean_postsearch'] = $this->scopeConfig->isSetFlag('cc_uk/gfx_options/searchbar_clean_postsearch', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     $cfg['searchbar_type'] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/gfx_options/searchbar_type', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['error_msg'] = [];
     $cfg['error_msg']["0001"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['error_msg']["0002"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_2', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['error_msg']["0003"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_3', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['error_msg']["0004"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_4', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['txt'] = [];
     $cfg['txt']["search_label"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_label', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['txt']["search_placeholder"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_placeholder', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $cfg['txt']["search_buttontext"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_buttontext', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     return json_encode($cfg);
 }
 /**
  * Validate that password is correct and customer is not locked
  *
  * @param \Magento\Customer\Api\Data\CustomerInterface $customer
  * @param string $password
  * @return $this
  * @throws InvalidEmailOrPasswordException
  */
 public function validatePasswordAndLockStatus(\Magento\Customer\Api\Data\CustomerInterface $customer, $password)
 {
     $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
     $hash = $customerSecure->getPasswordHash();
     if (!$this->encryptor->validateHash($password, $hash)) {
         $this->_eventManager->dispatch('customer_password_invalid', ['username' => $customer->getEmail(), 'password' => $password]);
         $this->checkIfLocked($customer);
         throw new InvalidEmailOrPasswordException(__('The password doesn\'t match this account.'));
     }
     return $this;
 }
Example #21
0
 /**
  * Process additional data before save config
  *
  * @return $this
  * @throws \Magento\Framework\Model\Exception
  */
 protected function _beforeSave()
 {
     $value = $this->getValue();
     if (is_array($value) && !empty($value['delete'])) {
         $this->setValue('');
         $this->_certFactory->create()->loadByWebsite($this->getScopeId())->delete();
     }
     if (!isset($_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value'])) {
         return $this;
     }
     $tmpPath = $this->_tmpDirectory->getRelativePath($_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value']);
     if ($tmpPath && $this->_tmpDirectory->isExist($tmpPath)) {
         if (!$this->_tmpDirectory->stat($tmpPath)['size']) {
             throw new \Magento\Framework\Model\Exception(__('The PayPal certificate file is empty.'));
         }
         $this->setValue($_FILES['groups']['name'][$this->getGroupId()]['fields'][$this->getField()]['value']);
         $content = $this->_encryptor->encrypt($this->_tmpDirectory->readFile($tmpPath));
         $this->_certFactory->create()->loadByWebsite($this->getScopeId())->setContent($content)->save();
     }
     return $this;
 }
 /**
  * Harden admin password change.
  *
  * New password must be minimum 7 chars length and include alphanumeric characters
  * The password is compared to at least last 4 previous passwords to prevent setting them again
  *
  * @param EventObserver $observer
  * @return void
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function execute(EventObserver $observer)
 {
     /* @var $user \Magento\User\Model\User */
     $user = $observer->getEvent()->getObject();
     if ($user->getNewPassword()) {
         $password = $user->getNewPassword();
     } else {
         $password = $user->getPassword();
     }
     if ($password && !$user->getForceNewPassword() && $user->getId()) {
         if ($this->encryptor->isValidHash($password, $user->getOrigData('password'))) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Sorry, but this password has already been used. Please create another.'));
         }
         // check whether password was used before
         $passwordHash = $this->encryptor->getHash($password, false);
         foreach ($this->userResource->getOldPasswords($user) as $oldPasswordHash) {
             if ($passwordHash === $oldPasswordHash) {
                 throw new \Magento\Framework\Exception\LocalizedException(__('Sorry, but this password has already been used. Please create another.'));
             }
         }
     }
 }
Example #23
0
 /**
  * @dataProvider authenticateDataProvider
  * @param string $usernameIn
  * @param string $usernameOut
  * @param bool $expectedResult
  * @return void
  */
 public function testAuthenticate($usernameIn, $usernameOut, $expectedResult)
 {
     $password = '******';
     $config = 'config';
     $data = ['id' => 1, 'is_active' => 1, 'username' => $usernameOut];
     $this->configMock->expects($this->once())->method('isSetFlag')->with('admin/security/use_case_sensitive_login')->willReturn($config);
     $this->eventManagerMock->expects($this->any())->method('dispatch');
     $this->resourceMock->expects($this->any())->method('loadByUsername')->willReturn($data);
     $this->model->setIdFieldName('id');
     $this->encryptorMock->expects($this->any())->method('validateHash')->willReturn(true);
     $this->resourceMock->expects($this->any())->method('hasAssigned2Role')->willReturn(true);
     $this->assertEquals($expectedResult, $this->model->authenticate($usernameIn, $password));
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function authenticate($customerId, $password)
 {
     $customerSecure = $this->customerRegistry->retrieveSecureData($customerId);
     $hash = $customerSecure->getPasswordHash();
     if (!$this->encryptor->validateHash($password, $hash)) {
         $this->processAuthenticationFailure($customerId);
         if ($this->isLocked($customerId)) {
             throw new UserLockedException(__('The account is locked.'));
         }
         throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
     }
     return true;
 }
Example #25
0
 /**
  * @param PaymentTokenInterface $token
  * @param OrderPaymentInterface $payment
  * @return bool
  */
 public function saveTokenWithPaymentLink(PaymentTokenInterface $token, OrderPaymentInterface $payment)
 {
     $tokenDuplicate = $this->getByPublicHash($token->getPublicHash(), $token->getCustomerId());
     if (!empty($tokenDuplicate)) {
         if ($token->getIsVisible()) {
             $token->setEntityId($tokenDuplicate->getEntityId());
         } else {
             $token->setPublicHash($this->encryptor->getHash($token->getPublicHash() . $token->getCreatedAt()));
         }
     }
     $this->paymentTokenRepository->save($token);
     $result = $this->addLinkToOrderPayment($token->getEntityId(), $payment->getEntityId());
     return $result;
 }
Example #26
0
 /**
  * Process saving new encryption key
  *
  * @return void
  */
 public function executeInternal()
 {
     try {
         $key = null;
         if (0 == $this->getRequest()->getPost('generate_random')) {
             $key = $this->getRequest()->getPost('crypt_key');
             if (empty($key)) {
                 throw new \Exception(__('Please enter an encryption key.'));
             }
             $this->encryptor->validateKey($key);
         }
         $newKey = $this->change->changeEncryptionKey($key);
         $this->messageManager->addSuccessMessage(__('The encryption key has been changed.'));
         if (!$key) {
             $this->messageManager->addNoticeMessage(__('This is your new encryption key: <span style="font-family:monospace;">%1</span>. ' . 'Be sure to write it down and take good care of it!', $newKey));
         }
         $this->cache->clean();
     } catch (\Exception $e) {
         $this->messageManager->addErrorMessage($e->getMessage());
         $this->_session->setFormData(['crypt_key' => $key]);
     }
     $this->_redirect('adminhtml/*/');
 }
 public function testCheckAdminPasswordChangeThrowsLocalizedExp()
 {
     $newPW = "mYn3wpassw0rd";
     $uid = 123;
     /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */
     $eventObserverMock = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */
     $eventMock = $this->getMockBuilder('Magento\\Framework\\Event')->disableOriginalConstructor()->setMethods(['getObject'])->getMock();
     /** @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject $userMock */
     $userMock = $this->getMockBuilder('Magento\\User\\Model\\User')->disableOriginalConstructor()->setMethods(['getId', 'getNewPassword', 'getForceNewPassword'])->getMock();
     $eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock);
     $eventMock->expects($this->once())->method('getObject')->willReturn($userMock);
     $userMock->expects($this->atLeastOnce())->method('getNewPassword')->willReturn($newPW);
     $userMock->expects($this->once())->method('getForceNewPassword')->willReturn(false);
     $userMock->expects($this->once())->method('getId')->willReturn($uid);
     $this->encryptorMock->expects($this->once())->method('isValidHash')->willReturn(true);
     $this->userMock->method('getOldPasswords')->willReturn([md5('pw1'), md5('pw2')]);
     try {
         $this->model->execute($eventObserverMock);
     } catch (\Magento\Framework\Exception\LocalizedException $expected) {
         return;
     }
     $this->fail('An expected exception has not been raised.');
 }
 public function testTrackAdminPassword()
 {
     $newPW = "mYn3wpassw0rd";
     $oldPW = "notsecure";
     $uid = 123;
     /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserverMock */
     $eventObserverMock = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Magento\Framework\Event|\PHPUnit_Framework_MockObject_MockObject */
     $eventMock = $this->getMockBuilder('Magento\\Framework\\Event')->disableOriginalConstructor()->setMethods(['getObject'])->getMock();
     /** @var \Magento\User\Model\User|\PHPUnit_Framework_MockObject_MockObject $userMock */
     $userMock = $this->getMockBuilder('Magento\\User\\Model\\User')->disableOriginalConstructor()->setMethods(['getId', 'getCurrentPassword', 'getForceNewPassword'])->getMock();
     $eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock);
     $eventMock->expects($this->once())->method('getObject')->willReturn($userMock);
     $userMock->expects($this->once())->method('getId')->willReturn($uid);
     $userMock->expects($this->once())->method('getCurrentPassword')->willReturn($newPW);
     $this->configInterfaceMock->expects($this->atLeastOnce())->method('getValue')->willReturn(1);
     $userMock->expects($this->once())->method('getForceNewPassword')->willReturn(false);
     $this->encryptorMock->expects($this->once())->method('getHash')->willReturn(md5($oldPW));
     /** @var \Magento\Framework\Message\Collection|\PHPUnit_Framework_MockObject_MockObject $collectionMock */
     $collectionMock = $this->getMockBuilder('Magento\\Framework\\Message\\Collection')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->managerInterfaceMock->expects($this->once())->method('getMessages')->willReturn($collectionMock);
     $this->authSessionMock->expects($this->once())->method('unsPciAdminUserIsPasswordExpired')->willReturn(null);
     $this->model->execute($eventObserverMock);
 }
 /**
  * Save the configuration value in both core and module db tables.
  *
  * @param $path
  * @param $scopeId
  * @param $value
  * @param string $type
  */
 protected function _saveConfig($path, $scopeId, $value, $type = self::TYPE_NORMAL)
 {
     // do not save config if path validation fails.
     if (!($fullPathParts = $this->_validateFullPath($path))) {
         return;
     }
     if ($type === self::TYPE_ENCRYPTED) {
         $value = $this->_encryptor->encrypt($value);
     }
     // get the path from the parts of path
     $path = implode('/', array_slice($fullPathParts, 1, 3));
     $this->_coreConfigResource->saveConfig($path, $value, $fullPathParts[0], $scopeId);
     $this->_configModel->setData(['scope_type' => $fullPathParts[0], 'scope_id' => $scopeId, 'path' => $path, 'value' => $value]);
     $this->_configModel->save();
     $this->_configModel->clearInstance();
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testCreateAccountWithPassword()
 {
     $websiteId = 1;
     $storeId = null;
     $defaultStoreId = 1;
     $customerId = 1;
     $customerEmail = '*****@*****.**';
     $hash = '4nj54lkj5jfi03j49f8bgujfgsd';
     $newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu';
     $templateIdentifier = 'Template Identifier';
     $sender = 'Sender';
     $password = '******';
     $minPasswordLength = 5;
     $minCharacterSetsNum = 2;
     $this->scopeConfig->expects($this->any())->method('getValue')->willReturnMap([[AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH, 'default', null, $minPasswordLength], [AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER, 'default', null, $minCharacterSetsNum], [AccountManagement::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId, $templateIdentifier], [AccountManagement::XML_PATH_REGISTER_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, 1, $sender]]);
     $this->string->expects($this->any())->method('strlen')->with($password)->willReturn(iconv_strlen($password, 'UTF-8'));
     $this->encryptor->expects($this->once())->method('getHash')->with($password, true)->willReturn($hash);
     $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     $address->expects($this->once())->method('setCustomerId')->with($customerId);
     $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $store->expects($this->once())->method('getId')->willReturn($defaultStoreId);
     $website = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->getMock();
     $website->expects($this->atLeastOnce())->method('getStoreIds')->willReturn([1, 2, 3]);
     $website->expects($this->once())->method('getDefaultStore')->willReturn($store);
     $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $customer->expects($this->atLeastOnce())->method('getEmail')->willReturn($customerEmail);
     $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId);
     $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId);
     $customer->expects($this->once())->method('setStoreId')->with($defaultStoreId);
     $customer->expects($this->once())->method('getAddresses')->willReturn([$address]);
     $customer->expects($this->once())->method('setAddresses')->with(null);
     $this->customerRepository->expects($this->once())->method('get')->with($customerEmail)->willReturn($customer);
     $this->share->expects($this->once())->method('isWebsiteScope')->willReturn(true);
     $this->storeManager->expects($this->atLeastOnce())->method('getWebsite')->with($websiteId)->willReturn($website);
     $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer);
     $this->addressRepository->expects($this->atLeastOnce())->method('save')->with($address);
     $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer);
     $this->random->expects($this->once())->method('getUniqueHash')->willReturn($newLinkToken);
     $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock();
     $customerSecure->expects($this->any())->method('setRpToken')->with($newLinkToken);
     $customerSecure->expects($this->any())->method('setRpTokenCreatedAt');
     $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash);
     $this->customerRegistry->expects($this->atLeastOnce())->method('retrieveSecureData')->willReturn($customerSecure);
     $this->emailNotificationMock->expects($this->once())->method('newAccount')->willReturnSelf();
     $this->accountManagement->createAccount($customer, $password);
 }