AccountManagement.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Model;
  7. use Magento\Customer\Api\AccountManagementInterface;
  8. use Magento\Customer\Api\AddressRepositoryInterface;
  9. use Magento\Customer\Api\CustomerMetadataInterface;
  10. use Magento\Customer\Api\CustomerRepositoryInterface;
  11. use Magento\Customer\Api\Data\AddressInterface;
  12. use Magento\Customer\Api\Data\CustomerInterface;
  13. use Magento\Customer\Api\Data\ValidationResultsInterfaceFactory;
  14. use Magento\Customer\Helper\View as CustomerViewHelper;
  15. use Magento\Customer\Model\Config\Share as ConfigShare;
  16. use Magento\Customer\Model\Customer as CustomerModel;
  17. use Magento\Customer\Model\Customer\CredentialsValidator;
  18. use Magento\Customer\Model\Metadata\Validator;
  19. use Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory;
  20. use Magento\Eav\Model\Validator\Attribute\Backend;
  21. use Magento\Framework\Api\ExtensibleDataObjectConverter;
  22. use Magento\Framework\Api\SearchCriteriaBuilder;
  23. use Magento\Framework\App\Area;
  24. use Magento\Framework\App\Config\ScopeConfigInterface;
  25. use Magento\Framework\App\ObjectManager;
  26. use Magento\Framework\DataObjectFactory as ObjectFactory;
  27. use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
  28. use Magento\Framework\Encryption\Helper\Security;
  29. use Magento\Framework\Event\ManagerInterface;
  30. use Magento\Framework\Exception\AlreadyExistsException;
  31. use Magento\Framework\Exception\EmailNotConfirmedException;
  32. use Magento\Framework\Exception\InputException;
  33. use Magento\Framework\Exception\InvalidEmailOrPasswordException;
  34. use Magento\Framework\Exception\LocalizedException;
  35. use Magento\Framework\Exception\MailException;
  36. use Magento\Framework\Exception\NoSuchEntityException;
  37. use Magento\Framework\Exception\State\ExpiredException;
  38. use Magento\Framework\Exception\State\InputMismatchException;
  39. use Magento\Framework\Exception\State\InvalidTransitionException;
  40. use Magento\Framework\Exception\State\UserLockedException;
  41. use Magento\Framework\Intl\DateTimeFactory;
  42. use Magento\Framework\Mail\Template\TransportBuilder;
  43. use Magento\Framework\Math\Random;
  44. use Magento\Framework\Phrase;
  45. use Magento\Framework\Reflection\DataObjectProcessor;
  46. use Magento\Framework\Registry;
  47. use Magento\Framework\Session\SaveHandlerInterface;
  48. use Magento\Framework\Session\SessionManagerInterface;
  49. use Magento\Framework\Stdlib\DateTime;
  50. use Magento\Framework\Stdlib\StringUtils as StringHelper;
  51. use Magento\Store\Model\ScopeInterface;
  52. use Magento\Store\Model\StoreManagerInterface;
  53. use Psr\Log\LoggerInterface as PsrLogger;
  54. /**
  55. * Handle various customer account actions
  56. *
  57. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  58. * @SuppressWarnings(PHPMD.TooManyFields)
  59. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  60. * @SuppressWarnings(PHPMD.CookieAndSessionMisuse)
  61. */
  62. class AccountManagement implements AccountManagementInterface
  63. {
  64. /**
  65. * Configuration paths for email templates and identities
  66. *
  67. * @deprecated
  68. */
  69. const XML_PATH_REGISTER_EMAIL_TEMPLATE = 'customer/create_account/email_template';
  70. /**
  71. * @deprecated
  72. */
  73. const XML_PATH_REGISTER_NO_PASSWORD_EMAIL_TEMPLATE = 'customer/create_account/email_no_password_template';
  74. /**
  75. * @deprecated
  76. */
  77. const XML_PATH_REGISTER_EMAIL_IDENTITY = 'customer/create_account/email_identity';
  78. /**
  79. * @deprecated
  80. */
  81. const XML_PATH_REMIND_EMAIL_TEMPLATE = 'customer/password/remind_email_template';
  82. /**
  83. * @deprecated
  84. */
  85. const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'customer/password/forgot_email_template';
  86. /**
  87. * @deprecated
  88. */
  89. const XML_PATH_FORGOT_EMAIL_IDENTITY = 'customer/password/forgot_email_identity';
  90. /**
  91. * @deprecated
  92. * @see AccountConfirmation::XML_PATH_IS_CONFIRM
  93. */
  94. const XML_PATH_IS_CONFIRM = 'customer/create_account/confirm';
  95. /**
  96. * @deprecated
  97. */
  98. const XML_PATH_CONFIRM_EMAIL_TEMPLATE = 'customer/create_account/email_confirmation_template';
  99. /**
  100. * @deprecated
  101. */
  102. const XML_PATH_CONFIRMED_EMAIL_TEMPLATE = 'customer/create_account/email_confirmed_template';
  103. /**
  104. * Constants for the type of new account email to be sent
  105. *
  106. * @deprecated
  107. */
  108. const NEW_ACCOUNT_EMAIL_REGISTERED = 'registered';
  109. /**
  110. * Welcome email, when password setting is required
  111. *
  112. * @deprecated
  113. */
  114. const NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD = 'registered_no_password';
  115. /**
  116. * Welcome email, when confirmation is enabled
  117. *
  118. * @deprecated
  119. */
  120. const NEW_ACCOUNT_EMAIL_CONFIRMATION = 'confirmation';
  121. /**
  122. * Confirmation email, when account is confirmed
  123. *
  124. * @deprecated
  125. */
  126. const NEW_ACCOUNT_EMAIL_CONFIRMED = 'confirmed';
  127. /**
  128. * Constants for types of emails to send out.
  129. * pdl:
  130. * forgot, remind, reset email templates
  131. */
  132. const EMAIL_REMINDER = 'email_reminder';
  133. const EMAIL_RESET = 'email_reset';
  134. /**
  135. * Configuration path to customer password minimum length
  136. */
  137. const XML_PATH_MINIMUM_PASSWORD_LENGTH = 'customer/password/minimum_password_length';
  138. /**
  139. * Configuration path to customer password required character classes number
  140. */
  141. const XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER = 'customer/password/required_character_classes_number';
  142. /**
  143. * @deprecated
  144. */
  145. const XML_PATH_RESET_PASSWORD_TEMPLATE = 'customer/password/reset_password_template';
  146. /**
  147. * @deprecated
  148. */
  149. const MIN_PASSWORD_LENGTH = 6;
  150. /**
  151. * @var CustomerFactory
  152. */
  153. private $customerFactory;
  154. /**
  155. * @var \Magento\Customer\Api\Data\ValidationResultsInterfaceFactory
  156. */
  157. private $validationResultsDataFactory;
  158. /**
  159. * @var ManagerInterface
  160. */
  161. private $eventManager;
  162. /**
  163. * @var \Magento\Store\Model\StoreManagerInterface
  164. */
  165. private $storeManager;
  166. /**
  167. * @var Random
  168. */
  169. private $mathRandom;
  170. /**
  171. * @var Validator
  172. */
  173. private $validator;
  174. /**
  175. * @var AddressRepositoryInterface
  176. */
  177. private $addressRepository;
  178. /**
  179. * @var CustomerMetadataInterface
  180. */
  181. private $customerMetadataService;
  182. /**
  183. * @var PsrLogger
  184. */
  185. protected $logger;
  186. /**
  187. * @var Encryptor
  188. */
  189. private $encryptor;
  190. /**
  191. * @var CustomerRegistry
  192. */
  193. private $customerRegistry;
  194. /**
  195. * @var ConfigShare
  196. */
  197. private $configShare;
  198. /**
  199. * @var StringHelper
  200. */
  201. protected $stringHelper;
  202. /**
  203. * @var CustomerRepositoryInterface
  204. */
  205. private $customerRepository;
  206. /**
  207. * @var ScopeConfigInterface
  208. */
  209. private $scopeConfig;
  210. /**
  211. * @var TransportBuilder
  212. */
  213. private $transportBuilder;
  214. /**
  215. * @var SessionManagerInterface
  216. */
  217. private $sessionManager;
  218. /**
  219. * @var SaveHandlerInterface
  220. */
  221. private $saveHandler;
  222. /**
  223. * @var CollectionFactory
  224. */
  225. private $visitorCollectionFactory;
  226. /**
  227. * @var DataObjectProcessor
  228. */
  229. protected $dataProcessor;
  230. /**
  231. * @var \Magento\Framework\Registry
  232. */
  233. protected $registry;
  234. /**
  235. * @var CustomerViewHelper
  236. */
  237. protected $customerViewHelper;
  238. /**
  239. * @var DateTime
  240. */
  241. protected $dateTime;
  242. /**
  243. * @var ObjectFactory
  244. */
  245. protected $objectFactory;
  246. /**
  247. * @var \Magento\Framework\Api\ExtensibleDataObjectConverter
  248. */
  249. protected $extensibleDataObjectConverter;
  250. /**
  251. * @var CustomerModel
  252. */
  253. protected $customerModel;
  254. /**
  255. * @var AuthenticationInterface
  256. */
  257. protected $authentication;
  258. /**
  259. * @var EmailNotificationInterface
  260. */
  261. private $emailNotification;
  262. /**
  263. * @var \Magento\Eav\Model\Validator\Attribute\Backend
  264. */
  265. private $eavValidator;
  266. /**
  267. * @var CredentialsValidator
  268. */
  269. private $credentialsValidator;
  270. /**
  271. * @var DateTimeFactory
  272. */
  273. private $dateTimeFactory;
  274. /**
  275. * @var AccountConfirmation
  276. */
  277. private $accountConfirmation;
  278. /**
  279. * @var SearchCriteriaBuilder
  280. */
  281. private $searchCriteriaBuilder;
  282. /**
  283. * @var AddressRegistry
  284. */
  285. private $addressRegistry;
  286. /**
  287. * @param CustomerFactory $customerFactory
  288. * @param ManagerInterface $eventManager
  289. * @param StoreManagerInterface $storeManager
  290. * @param Random $mathRandom
  291. * @param Validator $validator
  292. * @param ValidationResultsInterfaceFactory $validationResultsDataFactory
  293. * @param AddressRepositoryInterface $addressRepository
  294. * @param CustomerMetadataInterface $customerMetadataService
  295. * @param CustomerRegistry $customerRegistry
  296. * @param PsrLogger $logger
  297. * @param Encryptor $encryptor
  298. * @param ConfigShare $configShare
  299. * @param StringHelper $stringHelper
  300. * @param CustomerRepositoryInterface $customerRepository
  301. * @param ScopeConfigInterface $scopeConfig
  302. * @param TransportBuilder $transportBuilder
  303. * @param DataObjectProcessor $dataProcessor
  304. * @param Registry $registry
  305. * @param CustomerViewHelper $customerViewHelper
  306. * @param DateTime $dateTime
  307. * @param CustomerModel $customerModel
  308. * @param ObjectFactory $objectFactory
  309. * @param ExtensibleDataObjectConverter $extensibleDataObjectConverter
  310. * @param CredentialsValidator|null $credentialsValidator
  311. * @param DateTimeFactory|null $dateTimeFactory
  312. * @param AccountConfirmation|null $accountConfirmation
  313. * @param SessionManagerInterface|null $sessionManager
  314. * @param SaveHandlerInterface|null $saveHandler
  315. * @param CollectionFactory|null $visitorCollectionFactory
  316. * @param SearchCriteriaBuilder|null $searchCriteriaBuilder
  317. * @param AddressRegistry|null $addressRegistry
  318. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  319. * @SuppressWarnings(PHPMD.NPathComplexity)
  320. */
  321. public function __construct(
  322. CustomerFactory $customerFactory,
  323. ManagerInterface $eventManager,
  324. StoreManagerInterface $storeManager,
  325. Random $mathRandom,
  326. Validator $validator,
  327. ValidationResultsInterfaceFactory $validationResultsDataFactory,
  328. AddressRepositoryInterface $addressRepository,
  329. CustomerMetadataInterface $customerMetadataService,
  330. CustomerRegistry $customerRegistry,
  331. PsrLogger $logger,
  332. Encryptor $encryptor,
  333. ConfigShare $configShare,
  334. StringHelper $stringHelper,
  335. CustomerRepositoryInterface $customerRepository,
  336. ScopeConfigInterface $scopeConfig,
  337. TransportBuilder $transportBuilder,
  338. DataObjectProcessor $dataProcessor,
  339. Registry $registry,
  340. CustomerViewHelper $customerViewHelper,
  341. DateTime $dateTime,
  342. CustomerModel $customerModel,
  343. ObjectFactory $objectFactory,
  344. ExtensibleDataObjectConverter $extensibleDataObjectConverter,
  345. CredentialsValidator $credentialsValidator = null,
  346. DateTimeFactory $dateTimeFactory = null,
  347. AccountConfirmation $accountConfirmation = null,
  348. SessionManagerInterface $sessionManager = null,
  349. SaveHandlerInterface $saveHandler = null,
  350. CollectionFactory $visitorCollectionFactory = null,
  351. SearchCriteriaBuilder $searchCriteriaBuilder = null,
  352. AddressRegistry $addressRegistry = null
  353. ) {
  354. $this->customerFactory = $customerFactory;
  355. $this->eventManager = $eventManager;
  356. $this->storeManager = $storeManager;
  357. $this->mathRandom = $mathRandom;
  358. $this->validator = $validator;
  359. $this->validationResultsDataFactory = $validationResultsDataFactory;
  360. $this->addressRepository = $addressRepository;
  361. $this->customerMetadataService = $customerMetadataService;
  362. $this->customerRegistry = $customerRegistry;
  363. $this->logger = $logger;
  364. $this->encryptor = $encryptor;
  365. $this->configShare = $configShare;
  366. $this->stringHelper = $stringHelper;
  367. $this->customerRepository = $customerRepository;
  368. $this->scopeConfig = $scopeConfig;
  369. $this->transportBuilder = $transportBuilder;
  370. $this->dataProcessor = $dataProcessor;
  371. $this->registry = $registry;
  372. $this->customerViewHelper = $customerViewHelper;
  373. $this->dateTime = $dateTime;
  374. $this->customerModel = $customerModel;
  375. $this->objectFactory = $objectFactory;
  376. $this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
  377. $this->credentialsValidator =
  378. $credentialsValidator ?: ObjectManager::getInstance()->get(CredentialsValidator::class);
  379. $this->dateTimeFactory = $dateTimeFactory ?: ObjectManager::getInstance()->get(DateTimeFactory::class);
  380. $this->accountConfirmation = $accountConfirmation ?: ObjectManager::getInstance()
  381. ->get(AccountConfirmation::class);
  382. $this->sessionManager = $sessionManager
  383. ?: ObjectManager::getInstance()->get(SessionManagerInterface::class);
  384. $this->saveHandler = $saveHandler
  385. ?: ObjectManager::getInstance()->get(SaveHandlerInterface::class);
  386. $this->visitorCollectionFactory = $visitorCollectionFactory
  387. ?: ObjectManager::getInstance()->get(CollectionFactory::class);
  388. $this->searchCriteriaBuilder = $searchCriteriaBuilder
  389. ?: ObjectManager::getInstance()->get(SearchCriteriaBuilder::class);
  390. $this->addressRegistry = $addressRegistry
  391. ?: ObjectManager::getInstance()->get(AddressRegistry::class);
  392. }
  393. /**
  394. * Get authentication
  395. *
  396. * @return AuthenticationInterface
  397. */
  398. private function getAuthentication()
  399. {
  400. if (!($this->authentication instanceof AuthenticationInterface)) {
  401. return \Magento\Framework\App\ObjectManager::getInstance()->get(
  402. \Magento\Customer\Model\AuthenticationInterface::class
  403. );
  404. } else {
  405. return $this->authentication;
  406. }
  407. }
  408. /**
  409. * @inheritdoc
  410. */
  411. public function resendConfirmation($email, $websiteId = null, $redirectUrl = '')
  412. {
  413. $customer = $this->customerRepository->get($email, $websiteId);
  414. if (!$customer->getConfirmation()) {
  415. throw new InvalidTransitionException(__("Confirmation isn't needed."));
  416. }
  417. try {
  418. $this->getEmailNotification()->newAccount(
  419. $customer,
  420. self::NEW_ACCOUNT_EMAIL_CONFIRMATION,
  421. $redirectUrl,
  422. $this->storeManager->getStore()->getId()
  423. );
  424. } catch (MailException $e) {
  425. // If we are not able to send a new account email, this should be ignored
  426. $this->logger->critical($e);
  427. }
  428. }
  429. /**
  430. * @inheritdoc
  431. */
  432. public function activate($email, $confirmationKey)
  433. {
  434. $customer = $this->customerRepository->get($email);
  435. return $this->activateCustomer($customer, $confirmationKey);
  436. }
  437. /**
  438. * @inheritdoc
  439. */
  440. public function activateById($customerId, $confirmationKey)
  441. {
  442. $customer = $this->customerRepository->getById($customerId);
  443. return $this->activateCustomer($customer, $confirmationKey);
  444. }
  445. /**
  446. * Activate a customer account using a key that was sent in a confirmation email.
  447. *
  448. * @param \Magento\Customer\Api\Data\CustomerInterface $customer
  449. * @param string $confirmationKey
  450. * @return \Magento\Customer\Api\Data\CustomerInterface
  451. * @throws \Magento\Framework\Exception\State\InvalidTransitionException
  452. * @throws \Magento\Framework\Exception\State\InputMismatchException
  453. */
  454. private function activateCustomer($customer, $confirmationKey)
  455. {
  456. // check if customer is inactive
  457. if (!$customer->getConfirmation()) {
  458. throw new InvalidTransitionException(__('The account is already active.'));
  459. }
  460. if ($customer->getConfirmation() !== $confirmationKey) {
  461. throw new InputMismatchException(__('The confirmation token is invalid. Verify the token and try again.'));
  462. }
  463. $customer->setConfirmation(null);
  464. // No need to validate customer and customer address while activating customer
  465. $this->setIgnoreValidationFlag($customer);
  466. $this->customerRepository->save($customer);
  467. $this->getEmailNotification()->newAccount(
  468. $customer,
  469. 'confirmed',
  470. '',
  471. $this->storeManager->getStore()->getId()
  472. );
  473. return $customer;
  474. }
  475. /**
  476. * @inheritdoc
  477. */
  478. public function authenticate($username, $password)
  479. {
  480. try {
  481. $customer = $this->customerRepository->get($username);
  482. } catch (NoSuchEntityException $e) {
  483. throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
  484. }
  485. $customerId = $customer->getId();
  486. if ($this->getAuthentication()->isLocked($customerId)) {
  487. throw new UserLockedException(__('The account is locked.'));
  488. }
  489. try {
  490. $this->getAuthentication()->authenticate($customerId, $password);
  491. } catch (InvalidEmailOrPasswordException $e) {
  492. throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
  493. }
  494. if ($customer->getConfirmation() && $this->isConfirmationRequired($customer)) {
  495. throw new EmailNotConfirmedException(__("This account isn't confirmed. Verify and try again."));
  496. }
  497. $customerModel = $this->customerFactory->create()->updateData($customer);
  498. $this->eventManager->dispatch(
  499. 'customer_customer_authenticated',
  500. ['model' => $customerModel, 'password' => $password]
  501. );
  502. $this->eventManager->dispatch('customer_data_object_login', ['customer' => $customer]);
  503. return $customer;
  504. }
  505. /**
  506. * @inheritdoc
  507. */
  508. public function validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken)
  509. {
  510. $this->validateResetPasswordToken($customerId, $resetPasswordLinkToken);
  511. return true;
  512. }
  513. /**
  514. * @inheritdoc
  515. */
  516. public function initiatePasswordReset($email, $template, $websiteId = null)
  517. {
  518. if ($websiteId === null) {
  519. $websiteId = $this->storeManager->getStore()->getWebsiteId();
  520. }
  521. // load customer by email
  522. $customer = $this->customerRepository->get($email, $websiteId);
  523. // No need to validate customer address while saving customer reset password token
  524. $this->disableAddressValidation($customer);
  525. $newPasswordToken = $this->mathRandom->getUniqueHash();
  526. $this->changeResetPasswordLinkToken($customer, $newPasswordToken);
  527. try {
  528. switch ($template) {
  529. case AccountManagement::EMAIL_REMINDER:
  530. $this->getEmailNotification()->passwordReminder($customer);
  531. break;
  532. case AccountManagement::EMAIL_RESET:
  533. $this->getEmailNotification()->passwordResetConfirmation($customer);
  534. break;
  535. default:
  536. $this->handleUnknownTemplate($template);
  537. break;
  538. }
  539. return true;
  540. } catch (MailException $e) {
  541. // If we are not able to send a reset password email, this should be ignored
  542. $this->logger->critical($e);
  543. }
  544. return false;
  545. }
  546. /**
  547. * Match a customer by their RP token.
  548. *
  549. * @param string $rpToken
  550. * @throws ExpiredException
  551. * @throws NoSuchEntityException
  552. *
  553. * @return CustomerInterface
  554. * @throws LocalizedException
  555. */
  556. private function matchCustomerByRpToken(string $rpToken): CustomerInterface
  557. {
  558. $this->searchCriteriaBuilder->addFilter(
  559. 'rp_token',
  560. $rpToken
  561. );
  562. $this->searchCriteriaBuilder->setPageSize(1);
  563. $found = $this->customerRepository->getList(
  564. $this->searchCriteriaBuilder->create()
  565. );
  566. if ($found->getTotalCount() > 1) {
  567. //Failed to generated unique RP token
  568. throw new ExpiredException(
  569. new Phrase('Reset password token expired.')
  570. );
  571. }
  572. if ($found->getTotalCount() === 0) {
  573. //Customer with such token not found.
  574. throw NoSuchEntityException::singleField(
  575. 'rp_token',
  576. $rpToken
  577. );
  578. }
  579. //Unique customer found.
  580. return $found->getItems()[0];
  581. }
  582. /**
  583. * Handle not supported template
  584. *
  585. * @param string $template
  586. * @throws InputException
  587. */
  588. private function handleUnknownTemplate($template)
  589. {
  590. throw new InputException(__(
  591. 'Invalid value of "%value" provided for the %fieldName field. Possible values: %template1 or %template2.',
  592. [
  593. 'value' => $template,
  594. 'fieldName' => 'template',
  595. 'template1' => AccountManagement::EMAIL_REMINDER,
  596. 'template2' => AccountManagement::EMAIL_RESET
  597. ]
  598. ));
  599. }
  600. /**
  601. * @inheritdoc
  602. */
  603. public function resetPassword($email, $resetToken, $newPassword)
  604. {
  605. if (!$email) {
  606. $customer = $this->matchCustomerByRpToken($resetToken);
  607. $email = $customer->getEmail();
  608. } else {
  609. $customer = $this->customerRepository->get($email);
  610. }
  611. // No need to validate customer and customer address while saving customer reset password token
  612. $this->disableAddressValidation($customer);
  613. $this->setIgnoreValidationFlag($customer);
  614. //Validate Token and new password strength
  615. $this->validateResetPasswordToken($customer->getId(), $resetToken);
  616. $this->credentialsValidator->checkPasswordDifferentFromEmail(
  617. $email,
  618. $newPassword
  619. );
  620. $this->checkPasswordStrength($newPassword);
  621. //Update secure data
  622. $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
  623. $customerSecure->setRpToken(null);
  624. $customerSecure->setRpTokenCreatedAt(null);
  625. $customerSecure->setPasswordHash($this->createPasswordHash($newPassword));
  626. $this->destroyCustomerSessions($customer->getId());
  627. $this->sessionManager->destroy();
  628. $this->customerRepository->save($customer);
  629. return true;
  630. }
  631. /**
  632. * Make sure that password complies with minimum security requirements.
  633. *
  634. * @param string $password
  635. * @return void
  636. * @throws InputException
  637. */
  638. protected function checkPasswordStrength($password)
  639. {
  640. $length = $this->stringHelper->strlen($password);
  641. if ($length > self::MAX_PASSWORD_LENGTH) {
  642. throw new InputException(
  643. __(
  644. 'Please enter a password with at most %1 characters.',
  645. self::MAX_PASSWORD_LENGTH
  646. )
  647. );
  648. }
  649. $configMinPasswordLength = $this->getMinPasswordLength();
  650. if ($length < $configMinPasswordLength) {
  651. throw new InputException(
  652. __(
  653. 'The password needs at least %1 characters. Create a new password and try again.',
  654. $configMinPasswordLength
  655. )
  656. );
  657. }
  658. if ($this->stringHelper->strlen(trim($password)) != $length) {
  659. throw new InputException(
  660. __("The password can't begin or end with a space. Verify the password and try again.")
  661. );
  662. }
  663. $requiredCharactersCheck = $this->makeRequiredCharactersCheck($password);
  664. if ($requiredCharactersCheck !== 0) {
  665. throw new InputException(
  666. __(
  667. 'Minimum of different classes of characters in password is %1.' .
  668. ' Classes of characters: Lower Case, Upper Case, Digits, Special Characters.',
  669. $requiredCharactersCheck
  670. )
  671. );
  672. }
  673. }
  674. /**
  675. * Check password for presence of required character sets
  676. *
  677. * @param string $password
  678. * @return int
  679. */
  680. protected function makeRequiredCharactersCheck($password)
  681. {
  682. $counter = 0;
  683. $requiredNumber = $this->scopeConfig->getValue(self::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER);
  684. $return = 0;
  685. if (preg_match('/[0-9]+/', $password)) {
  686. $counter++;
  687. }
  688. if (preg_match('/[A-Z]+/', $password)) {
  689. $counter++;
  690. }
  691. if (preg_match('/[a-z]+/', $password)) {
  692. $counter++;
  693. }
  694. if (preg_match('/[^a-zA-Z0-9]+/', $password)) {
  695. $counter++;
  696. }
  697. if ($counter < $requiredNumber) {
  698. $return = $requiredNumber;
  699. }
  700. return $return;
  701. }
  702. /**
  703. * Retrieve minimum password length
  704. *
  705. * @return int
  706. */
  707. protected function getMinPasswordLength()
  708. {
  709. return $this->scopeConfig->getValue(self::XML_PATH_MINIMUM_PASSWORD_LENGTH);
  710. }
  711. /**
  712. * @inheritdoc
  713. */
  714. public function getConfirmationStatus($customerId)
  715. {
  716. // load customer by id
  717. $customer = $this->customerRepository->getById($customerId);
  718. if ($this->isConfirmationRequired($customer)) {
  719. if (!$customer->getConfirmation()) {
  720. return self::ACCOUNT_CONFIRMED;
  721. }
  722. return self::ACCOUNT_CONFIRMATION_REQUIRED;
  723. }
  724. return self::ACCOUNT_CONFIRMATION_NOT_REQUIRED;
  725. }
  726. /**
  727. * @inheritdoc
  728. */
  729. public function createAccount(CustomerInterface $customer, $password = null, $redirectUrl = '')
  730. {
  731. if ($password !== null) {
  732. $this->checkPasswordStrength($password);
  733. $customerEmail = $customer->getEmail();
  734. try {
  735. $this->credentialsValidator->checkPasswordDifferentFromEmail($customerEmail, $password);
  736. } catch (InputException $e) {
  737. throw new LocalizedException(
  738. __("The password can't be the same as the email address. Create a new password and try again.")
  739. );
  740. }
  741. $hash = $this->createPasswordHash($password);
  742. } else {
  743. $hash = null;
  744. }
  745. return $this->createAccountWithPasswordHash($customer, $hash, $redirectUrl);
  746. }
  747. /**
  748. * @inheritdoc
  749. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  750. * @SuppressWarnings(PHPMD.NPathComplexity)
  751. */
  752. public function createAccountWithPasswordHash(CustomerInterface $customer, $hash, $redirectUrl = '')
  753. {
  754. // This logic allows an existing customer to be added to a different store. No new account is created.
  755. // The plan is to move this logic into a new method called something like 'registerAccountWithStore'
  756. if ($customer->getId()) {
  757. $customer = $this->customerRepository->get($customer->getEmail());
  758. $websiteId = $customer->getWebsiteId();
  759. if ($this->isCustomerInStore($websiteId, $customer->getStoreId())) {
  760. throw new InputException(__('This customer already exists in this store.'));
  761. }
  762. // Existing password hash will be used from secured customer data registry when saving customer
  763. }
  764. // Make sure we have a storeId to associate this customer with.
  765. if (!$customer->getStoreId()) {
  766. if ($customer->getWebsiteId()) {
  767. $storeId = $this->storeManager->getWebsite($customer->getWebsiteId())->getDefaultStore()->getId();
  768. } else {
  769. $this->storeManager->setCurrentStore(null);
  770. $storeId = $this->storeManager->getStore()->getId();
  771. }
  772. $customer->setStoreId($storeId);
  773. }
  774. // Associate website_id with customer
  775. if (!$customer->getWebsiteId()) {
  776. $websiteId = $this->storeManager->getStore($customer->getStoreId())->getWebsiteId();
  777. $customer->setWebsiteId($websiteId);
  778. }
  779. // Update 'created_in' value with actual store name
  780. if ($customer->getId() === null) {
  781. $websiteId = $customer->getWebsiteId();
  782. if ($websiteId && !$this->isCustomerInStore($websiteId, $customer->getStoreId())) {
  783. throw new LocalizedException(__('The store view is not in the associated website.'));
  784. }
  785. $storeName = $this->storeManager->getStore($customer->getStoreId())->getName();
  786. $customer->setCreatedIn($storeName);
  787. }
  788. $customerAddresses = $customer->getAddresses() ?: [];
  789. $customer->setAddresses(null);
  790. try {
  791. // If customer exists existing hash will be used by Repository
  792. $customer = $this->customerRepository->save($customer, $hash);
  793. } catch (AlreadyExistsException $e) {
  794. throw new InputMismatchException(
  795. __('A customer with the same email address already exists in an associated website.')
  796. );
  797. } catch (LocalizedException $e) {
  798. throw $e;
  799. }
  800. try {
  801. foreach ($customerAddresses as $address) {
  802. if ($address->getId()) {
  803. $newAddress = clone $address;
  804. $newAddress->setId(null);
  805. $newAddress->setCustomerId($customer->getId());
  806. $this->addressRepository->save($newAddress);
  807. } else {
  808. $address->setCustomerId($customer->getId());
  809. $this->addressRepository->save($address);
  810. }
  811. }
  812. $this->customerRegistry->remove($customer->getId());
  813. } catch (InputException $e) {
  814. $this->customerRepository->delete($customer);
  815. throw $e;
  816. }
  817. $customer = $this->customerRepository->getById($customer->getId());
  818. $newLinkToken = $this->mathRandom->getUniqueHash();
  819. $this->changeResetPasswordLinkToken($customer, $newLinkToken);
  820. $this->sendEmailConfirmation($customer, $redirectUrl);
  821. return $customer;
  822. }
  823. /**
  824. * @inheritdoc
  825. */
  826. public function getDefaultBillingAddress($customerId)
  827. {
  828. $customer = $this->customerRepository->getById($customerId);
  829. return $this->getAddressById($customer, $customer->getDefaultBilling());
  830. }
  831. /**
  832. * @inheritdoc
  833. */
  834. public function getDefaultShippingAddress($customerId)
  835. {
  836. $customer = $this->customerRepository->getById($customerId);
  837. return $this->getAddressById($customer, $customer->getDefaultShipping());
  838. }
  839. /**
  840. * Send either confirmation or welcome email after an account creation
  841. *
  842. * @param CustomerInterface $customer
  843. * @param string $redirectUrl
  844. * @return void
  845. * @throws LocalizedException
  846. * @throws NoSuchEntityException
  847. */
  848. protected function sendEmailConfirmation(CustomerInterface $customer, $redirectUrl)
  849. {
  850. try {
  851. $hash = $this->customerRegistry->retrieveSecureData($customer->getId())->getPasswordHash();
  852. $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED;
  853. if ($this->isConfirmationRequired($customer) && $hash != '') {
  854. $templateType = self::NEW_ACCOUNT_EMAIL_CONFIRMATION;
  855. } elseif ($hash == '') {
  856. $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;
  857. }
  858. $this->getEmailNotification()->newAccount($customer, $templateType, $redirectUrl, $customer->getStoreId());
  859. } catch (MailException $e) {
  860. // If we are not able to send a new account email, this should be ignored
  861. $this->logger->critical($e);
  862. } catch (\UnexpectedValueException $e) {
  863. $this->logger->error($e);
  864. }
  865. }
  866. /**
  867. * @inheritdoc
  868. */
  869. public function changePassword($email, $currentPassword, $newPassword)
  870. {
  871. try {
  872. $customer = $this->customerRepository->get($email);
  873. } catch (NoSuchEntityException $e) {
  874. throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
  875. }
  876. return $this->changePasswordForCustomer($customer, $currentPassword, $newPassword);
  877. }
  878. /**
  879. * @inheritdoc
  880. */
  881. public function changePasswordById($customerId, $currentPassword, $newPassword)
  882. {
  883. try {
  884. $customer = $this->customerRepository->getById($customerId);
  885. } catch (NoSuchEntityException $e) {
  886. throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
  887. }
  888. return $this->changePasswordForCustomer($customer, $currentPassword, $newPassword);
  889. }
  890. /**
  891. * Change customer password
  892. *
  893. * @param CustomerInterface $customer
  894. * @param string $currentPassword
  895. * @param string $newPassword
  896. * @return bool true on success
  897. * @throws InputException
  898. * @throws InputMismatchException
  899. * @throws InvalidEmailOrPasswordException
  900. * @throws LocalizedException
  901. * @throws NoSuchEntityException
  902. * @throws UserLockedException
  903. */
  904. private function changePasswordForCustomer($customer, $currentPassword, $newPassword)
  905. {
  906. try {
  907. $this->getAuthentication()->authenticate($customer->getId(), $currentPassword);
  908. } catch (InvalidEmailOrPasswordException $e) {
  909. throw new InvalidEmailOrPasswordException(
  910. __("The password doesn't match this account. Verify the password and try again.")
  911. );
  912. }
  913. $customerEmail = $customer->getEmail();
  914. $this->credentialsValidator->checkPasswordDifferentFromEmail($customerEmail, $newPassword);
  915. $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
  916. $customerSecure->setRpToken(null);
  917. $customerSecure->setRpTokenCreatedAt(null);
  918. $this->checkPasswordStrength($newPassword);
  919. $customerSecure->setPasswordHash($this->createPasswordHash($newPassword));
  920. $this->destroyCustomerSessions($customer->getId());
  921. $this->disableAddressValidation($customer);
  922. $this->customerRepository->save($customer);
  923. return true;
  924. }
  925. /**
  926. * Create a hash for the given password
  927. *
  928. * @param string $password
  929. * @return string
  930. */
  931. protected function createPasswordHash($password)
  932. {
  933. return $this->encryptor->getHash($password, true);
  934. }
  935. /**
  936. * Get EAV validator
  937. *
  938. * @return Backend
  939. */
  940. private function getEavValidator()
  941. {
  942. if ($this->eavValidator === null) {
  943. $this->eavValidator = ObjectManager::getInstance()->get(Backend::class);
  944. }
  945. return $this->eavValidator;
  946. }
  947. /**
  948. * @inheritdoc
  949. */
  950. public function validate(CustomerInterface $customer)
  951. {
  952. $validationResults = $this->validationResultsDataFactory->create();
  953. $oldAddresses = $customer->getAddresses();
  954. $customerModel = $this->customerFactory->create()->updateData(
  955. $customer->setAddresses([])
  956. );
  957. $customer->setAddresses($oldAddresses);
  958. $result = $this->getEavValidator()->isValid($customerModel);
  959. if ($result === false && is_array($this->getEavValidator()->getMessages())) {
  960. return $validationResults->setIsValid(false)->setMessages(
  961. call_user_func_array(
  962. 'array_merge',
  963. $this->getEavValidator()->getMessages()
  964. )
  965. );
  966. }
  967. return $validationResults->setIsValid(true)->setMessages([]);
  968. }
  969. /**
  970. * @inheritdoc
  971. */
  972. public function isEmailAvailable($customerEmail, $websiteId = null)
  973. {
  974. try {
  975. if ($websiteId === null) {
  976. $websiteId = $this->storeManager->getStore()->getWebsiteId();
  977. }
  978. $this->customerRepository->get($customerEmail, $websiteId);
  979. return false;
  980. } catch (NoSuchEntityException $e) {
  981. return true;
  982. }
  983. }
  984. /**
  985. * @inheritDoc
  986. */
  987. public function isCustomerInStore($customerWebsiteId, $storeId)
  988. {
  989. $ids = [];
  990. if ((bool)$this->configShare->isWebsiteScope()) {
  991. $ids = $this->storeManager->getWebsite($customerWebsiteId)->getStoreIds();
  992. } else {
  993. foreach ($this->storeManager->getStores() as $store) {
  994. $ids[] = $store->getId();
  995. }
  996. }
  997. return in_array($storeId, $ids);
  998. }
  999. /**
  1000. * Validate the Reset Password Token for a customer.
  1001. *
  1002. * @param int $customerId
  1003. * @param string $resetPasswordLinkToken
  1004. * @return bool
  1005. * @throws \Magento\Framework\Exception\State\InputMismatchException If token is mismatched
  1006. * @throws \Magento\Framework\Exception\State\ExpiredException If token is expired
  1007. * @throws \Magento\Framework\Exception\InputException If token or customer id is invalid
  1008. * @throws \Magento\Framework\Exception\NoSuchEntityException If customer doesn't exist
  1009. * @throws LocalizedException
  1010. */
  1011. private function validateResetPasswordToken($customerId, $resetPasswordLinkToken)
  1012. {
  1013. if ($customerId !== null && $customerId <= 0) {
  1014. throw new InputException(
  1015. __(
  1016. 'Invalid value of "%value" provided for the %fieldName field.',
  1017. ['value' => $customerId, 'fieldName' => 'customerId']
  1018. )
  1019. );
  1020. }
  1021. if ($customerId === null) {
  1022. //Looking for the customer.
  1023. $customerId = $this->matchCustomerByRpToken($resetPasswordLinkToken)
  1024. ->getId();
  1025. }
  1026. if (!is_string($resetPasswordLinkToken) || empty($resetPasswordLinkToken)) {
  1027. $params = ['fieldName' => 'resetPasswordLinkToken'];
  1028. throw new InputException(__('"%fieldName" is required. Enter and try again.', $params));
  1029. }
  1030. $customerSecureData = $this->customerRegistry->retrieveSecureData($customerId);
  1031. $rpToken = $customerSecureData->getRpToken();
  1032. $rpTokenCreatedAt = $customerSecureData->getRpTokenCreatedAt();
  1033. if (!Security::compareStrings($rpToken, $resetPasswordLinkToken)) {
  1034. throw new InputMismatchException(__('The password token is mismatched. Reset and try again.'));
  1035. } elseif ($this->isResetPasswordLinkTokenExpired($rpToken, $rpTokenCreatedAt)) {
  1036. throw new ExpiredException(__('The password token is expired. Reset and try again.'));
  1037. }
  1038. return true;
  1039. }
  1040. /**
  1041. * Check if customer can be deleted.
  1042. *
  1043. * @param int $customerId
  1044. * @return bool
  1045. * @throws \Magento\Framework\Exception\NoSuchEntityException If group is not found
  1046. * @throws LocalizedException
  1047. */
  1048. public function isReadonly($customerId)
  1049. {
  1050. $customer = $this->customerRegistry->retrieveSecureData($customerId);
  1051. return !$customer->getDeleteable();
  1052. }
  1053. /**
  1054. * Send email with new account related information
  1055. *
  1056. * @param CustomerInterface $customer
  1057. * @param string $type
  1058. * @param string $backUrl
  1059. * @param string $storeId
  1060. * @param string $sendemailStoreId
  1061. * @return $this
  1062. * @throws LocalizedException
  1063. * @deprecated 100.1.0
  1064. */
  1065. protected function sendNewAccountEmail(
  1066. $customer,
  1067. $type = self::NEW_ACCOUNT_EMAIL_REGISTERED,
  1068. $backUrl = '',
  1069. $storeId = '0',
  1070. $sendemailStoreId = null
  1071. ) {
  1072. $types = $this->getTemplateTypes();
  1073. if (!isset($types[$type])) {
  1074. throw new LocalizedException(
  1075. __('The transactional account email type is incorrect. Verify and try again.')
  1076. );
  1077. }
  1078. if (!$storeId) {
  1079. $storeId = $this->getWebsiteStoreId($customer, $sendemailStoreId);
  1080. }
  1081. $store = $this->storeManager->getStore($customer->getStoreId());
  1082. $customerEmailData = $this->getFullCustomerObject($customer);
  1083. $this->sendEmailTemplate(
  1084. $customer,
  1085. $types[$type],
  1086. self::XML_PATH_REGISTER_EMAIL_IDENTITY,
  1087. ['customer' => $customerEmailData, 'back_url' => $backUrl, 'store' => $store],
  1088. $storeId
  1089. );
  1090. return $this;
  1091. }
  1092. /**
  1093. * Send email to customer when his password is reset
  1094. *
  1095. * @param CustomerInterface $customer
  1096. * @return $this
  1097. * @throws LocalizedException
  1098. * @throws NoSuchEntityException
  1099. * @deprecated 100.1.0
  1100. */
  1101. protected function sendPasswordResetNotificationEmail($customer)
  1102. {
  1103. return $this->sendPasswordResetConfirmationEmail($customer);
  1104. }
  1105. /**
  1106. * Get either first store ID from a set website or the provided as default
  1107. *
  1108. * @param CustomerInterface $customer
  1109. * @param int|string|null $defaultStoreId
  1110. * @return int
  1111. * @deprecated 100.1.0
  1112. * @throws LocalizedException
  1113. */
  1114. protected function getWebsiteStoreId($customer, $defaultStoreId = null)
  1115. {
  1116. if ($customer->getWebsiteId() != 0 && empty($defaultStoreId)) {
  1117. $storeIds = $this->storeManager->getWebsite($customer->getWebsiteId())->getStoreIds();
  1118. reset($storeIds);
  1119. $defaultStoreId = current($storeIds);
  1120. }
  1121. return $defaultStoreId;
  1122. }
  1123. /**
  1124. * Get template types
  1125. *
  1126. * @return array
  1127. * @deprecated 100.1.0
  1128. */
  1129. protected function getTemplateTypes()
  1130. {
  1131. /**
  1132. * self::NEW_ACCOUNT_EMAIL_REGISTERED welcome email, when confirmation is disabled
  1133. * and password is set
  1134. * self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD welcome email, when confirmation is disabled
  1135. * and password is not set
  1136. * self::NEW_ACCOUNT_EMAIL_CONFIRMED welcome email, when confirmation is enabled
  1137. * and password is set
  1138. * self::NEW_ACCOUNT_EMAIL_CONFIRMATION email with confirmation link
  1139. */
  1140. $types = [
  1141. self::NEW_ACCOUNT_EMAIL_REGISTERED => self::XML_PATH_REGISTER_EMAIL_TEMPLATE,
  1142. self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD => self::XML_PATH_REGISTER_NO_PASSWORD_EMAIL_TEMPLATE,
  1143. self::NEW_ACCOUNT_EMAIL_CONFIRMED => self::XML_PATH_CONFIRMED_EMAIL_TEMPLATE,
  1144. self::NEW_ACCOUNT_EMAIL_CONFIRMATION => self::XML_PATH_CONFIRM_EMAIL_TEMPLATE,
  1145. ];
  1146. return $types;
  1147. }
  1148. /**
  1149. * Send corresponding email template
  1150. *
  1151. * @param CustomerInterface $customer
  1152. * @param string $template configuration path of email template
  1153. * @param string $sender configuration path of email identity
  1154. * @param array $templateParams
  1155. * @param int|null $storeId
  1156. * @param string $email
  1157. * @return $this
  1158. * @throws MailException
  1159. * @deprecated 100.1.0
  1160. */
  1161. protected function sendEmailTemplate(
  1162. $customer,
  1163. $template,
  1164. $sender,
  1165. $templateParams = [],
  1166. $storeId = null,
  1167. $email = null
  1168. ) {
  1169. $templateId = $this->scopeConfig->getValue(
  1170. $template,
  1171. ScopeInterface::SCOPE_STORE,
  1172. $storeId
  1173. );
  1174. if ($email === null) {
  1175. $email = $customer->getEmail();
  1176. }
  1177. $transport = $this->transportBuilder->setTemplateIdentifier($templateId)
  1178. ->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $storeId])
  1179. ->setTemplateVars($templateParams)
  1180. ->setFrom($this->scopeConfig->getValue(
  1181. $sender,
  1182. ScopeInterface::SCOPE_STORE,
  1183. $storeId
  1184. ))
  1185. ->addTo($email, $this->customerViewHelper->getCustomerName($customer))
  1186. ->getTransport();
  1187. $transport->sendMessage();
  1188. return $this;
  1189. }
  1190. /**
  1191. * Check if accounts confirmation is required in config
  1192. *
  1193. * @param CustomerInterface $customer
  1194. * @return bool
  1195. * @deprecated 101.0.4
  1196. * @see AccountConfirmation::isConfirmationRequired
  1197. */
  1198. protected function isConfirmationRequired($customer)
  1199. {
  1200. return $this->accountConfirmation->isConfirmationRequired(
  1201. $customer->getWebsiteId(),
  1202. $customer->getId(),
  1203. $customer->getEmail()
  1204. );
  1205. }
  1206. /**
  1207. * Check whether confirmation may be skipped when registering using certain email address
  1208. *
  1209. * @param CustomerInterface $customer
  1210. * @return bool
  1211. * @deprecated 101.0.4
  1212. * @see AccountConfirmation::isConfirmationRequired
  1213. */
  1214. protected function canSkipConfirmation($customer)
  1215. {
  1216. if (!$customer->getId()) {
  1217. return false;
  1218. }
  1219. /* If an email was used to start the registration process and it is the same email as the one
  1220. used to register, then this can skip confirmation.
  1221. */
  1222. $skipConfirmationIfEmail = $this->registry->registry("skip_confirmation_if_email");
  1223. if (!$skipConfirmationIfEmail) {
  1224. return false;
  1225. }
  1226. return strtolower($skipConfirmationIfEmail) === strtolower($customer->getEmail());
  1227. }
  1228. /**
  1229. * Check if rpToken is expired
  1230. *
  1231. * @param string $rpToken
  1232. * @param string $rpTokenCreatedAt
  1233. * @return bool
  1234. */
  1235. public function isResetPasswordLinkTokenExpired($rpToken, $rpTokenCreatedAt)
  1236. {
  1237. if (empty($rpToken) || empty($rpTokenCreatedAt)) {
  1238. return true;
  1239. }
  1240. $expirationPeriod = $this->customerModel->getResetPasswordLinkExpirationPeriod();
  1241. $currentTimestamp = $this->dateTimeFactory->create()->getTimestamp();
  1242. $tokenTimestamp = $this->dateTimeFactory->create($rpTokenCreatedAt)->getTimestamp();
  1243. if ($tokenTimestamp > $currentTimestamp) {
  1244. return true;
  1245. }
  1246. $hourDifference = floor(($currentTimestamp - $tokenTimestamp) / (60 * 60));
  1247. if ($hourDifference >= $expirationPeriod) {
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. /**
  1253. * Change reset password link token
  1254. *
  1255. * Stores new reset password link token
  1256. *
  1257. * @param CustomerInterface $customer
  1258. * @param string $passwordLinkToken
  1259. * @return bool
  1260. * @throws InputException
  1261. * @throws InputMismatchException
  1262. * @throws LocalizedException
  1263. * @throws NoSuchEntityException
  1264. */
  1265. public function changeResetPasswordLinkToken($customer, $passwordLinkToken)
  1266. {
  1267. if (!is_string($passwordLinkToken) || empty($passwordLinkToken)) {
  1268. throw new InputException(
  1269. __(
  1270. 'Invalid value of "%value" provided for the %fieldName field.',
  1271. ['value' => $passwordLinkToken, 'fieldName' => 'password reset token']
  1272. )
  1273. );
  1274. }
  1275. if (is_string($passwordLinkToken) && !empty($passwordLinkToken)) {
  1276. $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
  1277. $customerSecure->setRpToken($passwordLinkToken);
  1278. $customerSecure->setRpTokenCreatedAt(
  1279. $this->dateTimeFactory->create()->format(DateTime::DATETIME_PHP_FORMAT)
  1280. );
  1281. $this->setIgnoreValidationFlag($customer);
  1282. $this->customerRepository->save($customer);
  1283. }
  1284. return true;
  1285. }
  1286. /**
  1287. * Send email with new customer password
  1288. *
  1289. * @param CustomerInterface $customer
  1290. * @return $this
  1291. * @throws LocalizedException
  1292. * @throws NoSuchEntityException
  1293. * @deprecated 100.1.0
  1294. */
  1295. public function sendPasswordReminderEmail($customer)
  1296. {
  1297. $storeId = $this->storeManager->getStore()->getId();
  1298. if (!$storeId) {
  1299. $storeId = $this->getWebsiteStoreId($customer);
  1300. }
  1301. $customerEmailData = $this->getFullCustomerObject($customer);
  1302. $this->sendEmailTemplate(
  1303. $customer,
  1304. self::XML_PATH_REMIND_EMAIL_TEMPLATE,
  1305. self::XML_PATH_FORGOT_EMAIL_IDENTITY,
  1306. ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
  1307. $storeId
  1308. );
  1309. return $this;
  1310. }
  1311. /**
  1312. * Send email with reset password confirmation link
  1313. *
  1314. * @param CustomerInterface $customer
  1315. * @return $this
  1316. * @throws LocalizedException
  1317. * @throws NoSuchEntityException
  1318. * @deprecated 100.1.0
  1319. */
  1320. public function sendPasswordResetConfirmationEmail($customer)
  1321. {
  1322. $storeId = $this->storeManager->getStore()->getId();
  1323. if (!$storeId) {
  1324. $storeId = $this->getWebsiteStoreId($customer);
  1325. }
  1326. $customerEmailData = $this->getFullCustomerObject($customer);
  1327. $this->sendEmailTemplate(
  1328. $customer,
  1329. self::XML_PATH_FORGOT_EMAIL_TEMPLATE,
  1330. self::XML_PATH_FORGOT_EMAIL_IDENTITY,
  1331. ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
  1332. $storeId
  1333. );
  1334. return $this;
  1335. }
  1336. /**
  1337. * Get address by id
  1338. *
  1339. * @param CustomerInterface $customer
  1340. * @param int $addressId
  1341. * @return AddressInterface|null
  1342. */
  1343. protected function getAddressById(CustomerInterface $customer, $addressId)
  1344. {
  1345. foreach ($customer->getAddresses() as $address) {
  1346. if ($address->getId() == $addressId) {
  1347. return $address;
  1348. }
  1349. }
  1350. return null;
  1351. }
  1352. /**
  1353. * Create an object with data merged from Customer and CustomerSecure
  1354. *
  1355. * @param CustomerInterface $customer
  1356. * @return Data\CustomerSecure
  1357. * @throws NoSuchEntityException
  1358. * @deprecated 100.1.0
  1359. */
  1360. protected function getFullCustomerObject($customer)
  1361. {
  1362. // No need to flatten the custom attributes or nested objects since the only usage is for email templates and
  1363. // object passed for events
  1364. $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId());
  1365. $customerData = $this->dataProcessor->buildOutputDataArray(
  1366. $customer,
  1367. \Magento\Customer\Api\Data\CustomerInterface::class
  1368. );
  1369. $mergedCustomerData->addData($customerData);
  1370. $mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer));
  1371. return $mergedCustomerData;
  1372. }
  1373. /**
  1374. * Return hashed password, which can be directly saved to database.
  1375. *
  1376. * @param string $password
  1377. * @return string
  1378. */
  1379. public function getPasswordHash($password)
  1380. {
  1381. return $this->encryptor->getHash($password);
  1382. }
  1383. /**
  1384. * Disable Customer Address Validation
  1385. *
  1386. * @param CustomerInterface $customer
  1387. * @throws NoSuchEntityException
  1388. */
  1389. private function disableAddressValidation($customer)
  1390. {
  1391. foreach ($customer->getAddresses() as $address) {
  1392. $addressModel = $this->addressRegistry->retrieve($address->getId());
  1393. $addressModel->setShouldIgnoreValidation(true);
  1394. }
  1395. }
  1396. /**
  1397. * Get email notification
  1398. *
  1399. * @return EmailNotificationInterface
  1400. * @deprecated 100.1.0
  1401. */
  1402. private function getEmailNotification()
  1403. {
  1404. if (!($this->emailNotification instanceof EmailNotificationInterface)) {
  1405. return \Magento\Framework\App\ObjectManager::getInstance()->get(
  1406. EmailNotificationInterface::class
  1407. );
  1408. } else {
  1409. return $this->emailNotification;
  1410. }
  1411. }
  1412. /**
  1413. * Destroy all active customer sessions by customer id (current session will not be destroyed).
  1414. * Customer sessions which should be deleted are collecting from the "customer_visitor" table considering
  1415. * configured session lifetime.
  1416. *
  1417. * @param string|int $customerId
  1418. * @return void
  1419. */
  1420. private function destroyCustomerSessions($customerId)
  1421. {
  1422. $sessionLifetime = $this->scopeConfig->getValue(
  1423. \Magento\Framework\Session\Config::XML_PATH_COOKIE_LIFETIME,
  1424. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  1425. );
  1426. $dateTime = $this->dateTimeFactory->create();
  1427. $activeSessionsTime = $dateTime->setTimestamp($dateTime->getTimestamp() - $sessionLifetime)
  1428. ->format(DateTime::DATETIME_PHP_FORMAT);
  1429. /** @var \Magento\Customer\Model\ResourceModel\Visitor\Collection $visitorCollection */
  1430. $visitorCollection = $this->visitorCollectionFactory->create();
  1431. $visitorCollection->addFieldToFilter('customer_id', $customerId);
  1432. $visitorCollection->addFieldToFilter('last_visit_at', ['from' => $activeSessionsTime]);
  1433. $visitorCollection->addFieldToFilter('session_id', ['neq' => $this->sessionManager->getSessionId()]);
  1434. /** @var \Magento\Customer\Model\Visitor $visitor */
  1435. foreach ($visitorCollection->getItems() as $visitor) {
  1436. $sessionId = $visitor->getSessionId();
  1437. $this->saveHandler->destroy($sessionId);
  1438. }
  1439. }
  1440. /**
  1441. * Set ignore_validation_flag for reset password flow to skip unnecessary address and customer validation
  1442. *
  1443. * @param Customer $customer
  1444. * @return void
  1445. */
  1446. private function setIgnoreValidationFlag($customer)
  1447. {
  1448. $customer->setData('ignore_validation_flag', true);
  1449. }
  1450. }