Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
User.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\User\Model;
8 
18 
39 {
44  const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'admin/emails/forgot_email_template';
45 
50  const XML_PATH_FORGOT_EMAIL_IDENTITY = 'admin/emails/forgot_email_identity';
51 
56  const XML_PATH_USER_NOTIFICATION_TEMPLATE = 'admin/emails/user_notification_template';
57 
59  const XML_PATH_RESET_PASSWORD_TEMPLATE = 'admin/emails/reset_password_template';
60 
61  const MESSAGE_ID_PASSWORD_EXPIRED = 'magento_user_password_expired';
62 
68  protected $_eventPrefix = 'admin_user';
69 
75  protected $_role;
76 
82  protected $_hasResources = true;
83 
89  protected $_userData = null;
90 
96  protected $_config;
97 
103  protected $_validatorObject;
104 
110  protected $_roleFactory;
111 
115  protected $_encryptor;
116 
121 
125  protected $_storeManager;
126 
130  protected $validationRules;
131 
135  private $serializer;
136 
140  private $notificator;
141 
145  private $deploymentConfig;
146 
166  public function __construct(
167  \Magento\Framework\Model\Context $context,
168  \Magento\Framework\Registry $registry,
169  \Magento\User\Helper\Data $userData,
171  \Magento\Framework\Validator\DataObjectFactory $validatorObjectFactory,
172  \Magento\Authorization\Model\RoleFactory $roleFactory,
173  \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
174  \Magento\Framework\Encryption\EncryptorInterface $encryptor,
177  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
178  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
179  array $data = [],
180  Json $serializer = null,
181  DeploymentConfig $deploymentConfig = null,
182  ?NotificatorInterface $notificator = null
183  ) {
184  $this->_encryptor = $encryptor;
185  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
186  $this->_userData = $userData;
187  $this->_config = $config;
188  $this->_validatorObject = $validatorObjectFactory;
189  $this->_roleFactory = $roleFactory;
190  $this->_transportBuilder = $transportBuilder;
191  $this->_storeManager = $storeManager;
192  $this->validationRules = $validationRules;
193  $this->serializer = $serializer
194  ?: ObjectManager::getInstance()->get(Json::class);
195  $this->deploymentConfig = $deploymentConfig
196  ?: ObjectManager::getInstance()->get(DeploymentConfig::class);
197  $this->notificator = $notificator
198  ?: ObjectManager::getInstance()->get(NotificatorInterface::class);
199  }
200 
206  protected function _construct()
207  {
208  $this->_init(\Magento\User\Model\ResourceModel\User::class);
209  }
210 
216  public function __sleep()
217  {
219  return array_diff(
220  $properties,
221  [
222  '_eventManager',
223  '_userData',
224  '_config',
225  '_validatorObject',
226  '_roleFactory',
227  '_encryptor',
228  '_transportBuilder',
229  '_storeManager',
230  '_validatorBeforeSave',
231  'validationRules',
232  'serializer',
233  'deploymentConfig',
234  'notificator'
235  ]
236  );
237  }
238 
244  public function __wakeup()
245  {
248  $this->serializer = $objectManager->get(Json::class);
249  $this->_eventManager = $objectManager->get(\Magento\Framework\Event\ManagerInterface::class);
250  $this->_userData = $objectManager->get(\Magento\User\Helper\Data::class);
251  $this->_config = $objectManager->get(\Magento\Backend\App\ConfigInterface::class);
252  $this->_registry = $objectManager->get(\Magento\Framework\Registry::class);
253  $this->_validatorObject = $objectManager->get(\Magento\Framework\Validator\DataObjectFactory::class);
254  $this->_roleFactory = $objectManager->get(\Magento\Authorization\Model\RoleFactory::class);
255  $this->_encryptor = $objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
256  $this->_transportBuilder = $objectManager->get(\Magento\Framework\Mail\Template\TransportBuilder::class);
257  $this->_storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);
258  $this->validationRules = $objectManager->get(UserValidationRules::class);
259  $this->deploymentConfig = $objectManager->get(DeploymentConfig::class);
260  $this->notificator = $objectManager->get(NotificatorInterface::class);
261  }
262 
268  public function beforeSave()
269  {
270  $data = [
271  'extra' => $this->serializer->serialize($this->getExtra()),
272  ];
273 
274  if ($this->_willSavePassword()) {
275  $data['password'] = $this->_getEncodedPassword($this->getPassword());
276  }
277 
278  if ($this->getIsActive() !== null) {
279  $data['is_active'] = intval($this->getIsActive());
280  }
281 
282  $this->addData($data);
283 
284  return parent::beforeSave();
285  }
286 
292  protected function _willSavePassword()
293  {
294  return $this->isObjectNew() || $this->hasData('password') && $this->dataHasChangedFor('password');
295  }
296 
302  protected function _getValidationRulesBeforeSave()
303  {
305  $validator = $this->_validatorObject->create();
306  $this->validationRules->addUserInfoRules($validator);
307 
308  // Add validation rules for the password management fields
309  if ($this->_willSavePassword()) {
310  $this->validationRules->addPasswordRules($validator);
311  if ($this->hasPasswordConfirmation()) {
312  $this->validationRules->addPasswordConfirmationRule($validator, $this->getPasswordConfirmation());
313  }
314  }
315  return $validator;
316  }
317 
325  public function validate()
326  {
328  $validator = $this->_validatorObject->create();
329  $this->validationRules->addUserInfoRules($validator);
330 
331  if (!$validator->isValid($this)) {
332  return $validator->getMessages();
333  }
334 
335  return $this->validatePasswordChange();
336  }
337 
346  protected function validatePasswordChange()
347  {
348  $password = $this->getPassword();
349  if ($password && !$this->getForceNewPassword() && $this->getId()) {
350  $errorMessage = __('Sorry, but this password has already been used. Please create another.');
351  // Check if password is equal to the current one
352  if ($this->_encryptor->isValidHash($password, $this->getOrigData('password'))) {
353  return [$errorMessage];
354  }
355 
356  // Check whether password was used before
357  foreach ($this->getResource()->getOldPasswords($this) as $oldPasswordHash) {
358  if ($this->_encryptor->isValidHash($password, $oldPasswordHash)) {
359  return [$errorMessage];
360  }
361  }
362  }
363  return true;
364  }
365 
371  public function afterSave()
372  {
373  $this->_role = null;
374  return parent::afterSave();
375  }
376 
383  public function saveExtra($data)
384  {
385  if (is_array($data)) {
386  $data = $this->serializer->serialize($data);
387  }
388  $this->_getResource()->saveExtra($this, $data);
389  return $this;
390  }
391 
397  public function getRoles()
398  {
399  return $this->_getResource()->getRoles($this);
400  }
401 
407  public function getRole()
408  {
409  if (null === $this->_role) {
410  $this->_role = $this->_roleFactory->create();
411  $roles = $this->getRoles();
412  if ($roles && isset($roles[0]) && $roles[0]) {
413  $this->_role->load($roles[0]);
414  }
415  }
416  return $this->_role;
417  }
418 
424  public function deleteFromRole()
425  {
426  $this->_getResource()->deleteFromRole($this);
427  return $this;
428  }
429 
435  public function roleUserExists()
436  {
437  $result = $this->_getResource()->roleUserExists($this);
438  return is_array($result) && count($result) > 0 ? true : false;
439  }
440 
450  {
451  $this->notificator->sendForgotPassword($this);
452 
453  return $this;
454  }
455 
464  {
466  return $this;
467  }
468 
477  {
478  if ($this->isObjectNew()) {
479  //Notification about a new user.
480  $this->notificator->sendCreated($this);
482  //User changed.
483  $this->notificator->sendUpdated($this, explode(', ', $changes));
484  }
485 
486  return $this;
487  }
488 
495  protected function createChangesDescriptionString()
496  {
497  $changes = [];
498 
499  if ($this->getEmail() != $this->getOrigData('email') && $this->getOrigData('email')) {
500  $changes[] = __('email');
501  }
502 
503  if ($this->getPassword()
504  && $this->getOrigData('password')
505  && $this->getPassword() != $this->getOrigData('password')) {
506  $changes[] = __('password');
507  }
508 
509  if ($this->getUserName() != $this->getOrigData('username') && $this->getOrigData('username')) {
510  $changes[] = __('username');
511  }
512 
513  return implode(', ', $changes);
514  }
515 
528  protected function sendUserNotificationEmail($changes, $email = null)
529  {
530  $this->notificator->sendUpdated($this, explode(', ', $changes));
531 
532  return $this;
533  }
534 
541  public function getName($separator = ' ')
542  {
543  return $this->getFirstName() . $separator . $this->getLastName();
544  }
545 
551  public function getAclRole()
552  {
553  return $this->getRole()->getId();
554  }
555 
564  public function authenticate($username, $password)
565  {
566  $config = $this->_config->isSetFlag('admin/security/use_case_sensitive_login');
567  $result = false;
568 
569  try {
570  $this->_eventManager->dispatch(
571  'admin_user_authenticate_before',
572  ['username' => $username, 'user' => $this]
573  );
574  $this->loadByUsername($username);
575  $sensitive = $config ? $username == $this->getUserName() : true;
576  if ($sensitive && $this->getId()) {
577  $result = $this->verifyIdentity($password);
578  }
579 
580  $this->_eventManager->dispatch(
581  'admin_user_authenticate_after',
582  ['username' => $username, 'password' => $password, 'user' => $this, 'result' => $result]
583  );
584  } catch (\Magento\Framework\Exception\LocalizedException $e) {
585  $this->unsetData();
586  throw $e;
587  }
588 
589  if (!$result) {
590  $this->unsetData();
591  }
592  return $result;
593  }
594 
602  public function verifyIdentity($password)
603  {
604  $result = false;
605  if ($this->_encryptor->validateHash($password, $this->getPassword())) {
606  if ($this->getIsActive() != '1') {
607  throw new AuthenticationException(
608  __(
609  'The account sign-in was incorrect or your account is disabled temporarily. '
610  . 'Please wait and try again later.'
611  )
612  );
613  }
614  if (!$this->hasAssigned2Role($this->getId())) {
615  throw new AuthenticationException(__('More permissions are needed to access this.'));
616  }
617  $result = true;
618  }
619  return $result;
620  }
621 
629  public function login($username, $password)
630  {
631  if ($this->authenticate($username, $password)) {
632  $this->getResource()->recordLogin($this);
633  }
634  return $this;
635  }
636 
642  public function reload()
643  {
644  $userId = $this->getId();
645  $this->setId(null);
646  $this->load($userId);
647  return $this;
648  }
649 
656  public function loadByUsername($username)
657  {
658  $data = $this->getResource()->loadByUsername($username);
659  if ($data !== false) {
660  $this->setData($data);
661  $this->setOrigData();
662  }
663  return $this;
664  }
665 
672  public function hasAssigned2Role($user)
673  {
674  return $this->getResource()->hasAssigned2Role($user);
675  }
676 
683  protected function _getEncodedPassword($password)
684  {
685  return $this->_encryptor->getHash($password, true);
686  }
687 
697  public function changeResetPasswordLinkToken($newToken)
698  {
699  if (!is_string($newToken) || empty($newToken)) {
700  throw new \Magento\Framework\Exception\LocalizedException(
701  __('The password reset token is incorrect. Verify the token and try again.')
702  );
703  }
704  $this->setRpToken($newToken);
705  $this->setRpTokenCreatedAt((new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT));
706 
707  return $this;
708  }
709 
716  {
717  $linkToken = $this->getRpToken();
718  $linkTokenCreatedAt = $this->getRpTokenCreatedAt();
719 
720  if (empty($linkToken) || empty($linkTokenCreatedAt)) {
721  return true;
722  }
723 
724  $expirationPeriod = $this->_userData->getResetPasswordLinkExpirationPeriod();
725 
726  $currentTimestamp = (new \DateTime())->getTimestamp();
727  $tokenTimestamp = (new \DateTime($linkTokenCreatedAt))->getTimestamp();
728  if ($tokenTimestamp > $currentTimestamp) {
729  return true;
730  }
731 
732  $hourDifference = floor(($currentTimestamp - $tokenTimestamp) / (60 * 60));
733  if ($hourDifference >= $expirationPeriod) {
734  return true;
735  }
736 
737  return false;
738  }
739 
745  public function hasAvailableResources()
746  {
747  return $this->_hasResources;
748  }
749 
756  public function setHasAvailableResources($hasResources)
757  {
758  $this->_hasResources = $hasResources;
759  return $this;
760  }
761 
765  public function getFirstName()
766  {
767  return $this->_getData('firstname');
768  }
769 
773  public function setFirstName($firstName)
774  {
775  return $this->setData('firstname', $firstName);
776  }
777 
781  public function getLastName()
782  {
783  return $this->_getData('lastname');
784  }
785 
789  public function setLastName($lastName)
790  {
791  return $this->setData('lastname', $lastName);
792  }
793 
797  public function getEmail()
798  {
799  return $this->_getData('email');
800  }
801 
805  public function setEmail($email)
806  {
807  return $this->setData('email', $email);
808  }
809 
813  public function getUserName()
814  {
815  return $this->_getData('username');
816  }
817 
821  public function setUserName($userName)
822  {
823  return $this->setData('username', $userName);
824  }
825 
829  public function getPassword()
830  {
831  return $this->_getData('password');
832  }
833 
837  public function setPassword($password)
838  {
839  return $this->setData('password', $password);
840  }
841 
845  public function getCreated()
846  {
847  return $this->_getData('created');
848  }
849 
853  public function setCreated($created)
854  {
855  return $this->setData('created', $created);
856  }
857 
861  public function getModified()
862  {
863  return $this->_getData('modified');
864  }
865 
869  public function setModified($modified)
870  {
871  return $this->setData('modified', $modified);
872  }
873 
877  public function getIsActive()
878  {
879  return $this->_getData('is_active');
880  }
881 
885  public function setIsActive($isActive)
886  {
887  return $this->setData('is_active', $isActive);
888  }
889 
893  public function getInterfaceLocale()
894  {
895  return $this->_getData('interface_locale');
896  }
897 
901  public function setInterfaceLocale($interfaceLocale)
902  {
903  return $this->setData('interface_locale', $interfaceLocale);
904  }
905 
915  public function performIdentityCheck($passwordString)
916  {
917  try {
918  $isCheckSuccessful = $this->verifyIdentity($passwordString);
919  } catch (\Magento\Framework\Exception\AuthenticationException $e) {
920  $isCheckSuccessful = false;
921  }
922  $this->_eventManager->dispatch(
923  'admin_user_authenticate_after',
924  [
925  'username' => $this->getUserName(),
926  'password' => $passwordString,
927  'user' => $this,
928  'result' => $isCheckSuccessful
929  ]
930  );
931  // Check if lock information has been updated in observers
932  $clonedUser = clone($this);
933  $clonedUser->reload();
934  if ($clonedUser->getLockExpires()) {
935  throw new \Magento\Framework\Exception\State\UserLockedException(
936  __('Your account is temporarily disabled. Please try again later.')
937  );
938  }
939 
940  if (!$isCheckSuccessful) {
941  throw new \Magento\Framework\Exception\AuthenticationException(
942  __('The password entered for the current user is invalid. Verify the password and try again.')
943  );
944  }
945 
946  return $this;
947  }
948 }
setInterfaceLocale($interfaceLocale)
Definition: User.php:901
setCreated($created)
Definition: User.php:853
isResetPasswordLinkTokenExpired()
Definition: User.php:715
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
setUserName($userName)
Definition: User.php:821
$objectManager
Definition: bootstrap.php:17
$email
Definition: details.phtml:13
$config
Definition: fraud_order.php:17
setModified($modified)
Definition: User.php:869
sendPasswordResetNotificationEmail()
Definition: User.php:463
sendUserNotificationEmail($changes, $email=null)
Definition: User.php:528
$storeManager
verifyIdentity($password)
Definition: User.php:602
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
loadByUsername($username)
Definition: User.php:656
performIdentityCheck($passwordString)
Definition: User.php:915
authenticate($username, $password)
Definition: User.php:564
login($username, $password)
Definition: User.php:629
getName($separator=' ')
Definition: User.php:541
setHasAvailableResources($hasResources)
Definition: User.php:756
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\User\Helper\Data $userData, \Magento\Backend\App\ConfigInterface $config, \Magento\Framework\Validator\DataObjectFactory $validatorObjectFactory, \Magento\Authorization\Model\RoleFactory $roleFactory, \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder, \Magento\Framework\Encryption\EncryptorInterface $encryptor, \Magento\Store\Model\StoreManagerInterface $storeManager, UserValidationRules $validationRules, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[], Json $serializer=null, DeploymentConfig $deploymentConfig=null, ?NotificatorInterface $notificator=null)
Definition: User.php:166
const XML_PATH_FORGOT_EMAIL_TEMPLATE
Definition: User.php:44
$user
Definition: dummy_user.php:13
_getEncodedPassword($password)
Definition: User.php:683
const MESSAGE_ID_PASSWORD_EXPIRED
Definition: User.php:61
const XML_PATH_USER_NOTIFICATION_TEMPLATE
Definition: User.php:56
sendPasswordResetConfirmationEmail()
Definition: User.php:449
hasAssigned2Role($user)
Definition: User.php:672
setLastName($lastName)
Definition: User.php:789
sendNotificationEmailsIfRequired()
Definition: User.php:476
$properties
Definition: categories.php:26
createChangesDescriptionString()
Definition: User.php:495
setFirstName($firstName)
Definition: User.php:773
const XML_PATH_RESET_PASSWORD_TEMPLATE
Definition: User.php:59
const XML_PATH_FORGOT_EMAIL_IDENTITY
Definition: User.php:50
changeResetPasswordLinkToken($newToken)
Definition: User.php:697
setPassword($password)
Definition: User.php:837
setIsActive($isActive)
Definition: User.php:885