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
8 
15 use Magento\User\Model\User as ModelUser;
16 
25 {
31  protected $_roleFactory;
32 
36  protected $dateTime;
37 
41  private $aclDataCache;
42 
46  private $observerConfig;
47 
58  public function __construct(
59  \Magento\Framework\Model\ResourceModel\Db\Context $context,
60  \Magento\Authorization\Model\RoleFactory $roleFactory,
61  \Magento\Framework\Stdlib\DateTime $dateTime,
62  $connectionName = null,
63  CacheInterface $aclDataCache = null,
64  ObserverConfig $observerConfig = null
65  ) {
66  parent::__construct($context, $connectionName);
67  $this->_roleFactory = $roleFactory;
68  $this->dateTime = $dateTime;
69  $this->aclDataCache = $aclDataCache ?: ObjectManager::getInstance()->get(CacheInterface::class);
70  $this->observerConfig = $observerConfig ?: ObjectManager::getInstance()->get(ObserverConfig::class);
71  }
72 
78  protected function _construct()
79  {
80  $this->_init('admin_user', 'user_id');
81  }
82 
88  protected function _initUniqueFields()
89  {
90  $this->_uniqueFields = [
91  ['field' => 'email', 'title' => __('Email')],
92  ['field' => 'username', 'title' => __('User Name')],
93  ];
94  return $this;
95  }
96 
103  public function recordLogin(ModelUser $user)
104  {
105  $connection = $this->getConnection();
106 
107  $data = [
108  'logdate' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
109  'lognum' => $user->getLognum() + 1,
110  ];
111 
112  $condition = ['user_id = ?' => (int)$user->getUserId()];
113 
114  $connection->update($this->getMainTable(), $data, $condition);
115 
116  return $this;
117  }
118 
125  public function loadByUsername($username)
126  {
127  $connection = $this->getConnection();
128 
129  $select = $connection->select()->from($this->getMainTable())->where('username=:username');
130 
131  $binds = ['username' => $username];
132 
133  return $connection->fetchRow($select, $binds);
134  }
135 
142  public function hasAssigned2Role($user)
143  {
144  if (is_numeric($user)) {
145  $userId = $user;
146  } elseif ($user instanceof \Magento\Framework\Model\AbstractModel) {
147  $userId = $user->getUserId();
148  } else {
149  return null;
150  }
151 
152  if ($userId > 0) {
153  $connection = $this->getConnection();
154 
155  $select = $connection->select();
156  $select->from($this->getTable('authorization_role'))
157  ->where('parent_id > :parent_id')
158  ->where('user_id = :user_id')
159  ->where('user_type = :user_type');
160 
161  $binds = ['parent_id' => 0, 'user_id' => $userId,
163  ];
164 
165  return $connection->fetchAll($select, $binds);
166  } else {
167  return null;
168  }
169  }
170 
177  protected function _afterSave(\Magento\Framework\Model\AbstractModel $user)
178  {
179  $user->setExtra($this->getSerializer()->unserialize($user->getExtra()));
180  if ($user->hasRoleId()) {
181  $this->_clearUserRoles($user);
182  $this->_createUserRole($user->getRoleId(), $user);
183  }
184  return $this;
185  }
186 
193  public function _clearUserRoles(ModelUser $user)
194  {
195  $conditions = ['user_id = ?' => (int)$user->getId(), 'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN];
196  $this->getConnection()->delete($this->getTable('authorization_role'), $conditions);
197  }
198 
206  protected function _createUserRole($parentId, ModelUser $user)
207  {
208  if ($parentId > 0) {
210  $parentRole = $this->_roleFactory->create()->load($parentId);
211  } else {
212  $role = new \Magento\Framework\DataObject();
213  $role->setTreeLevel(0);
214  }
215 
216  if ($parentRole->getId()) {
217  $data = new \Magento\Framework\DataObject(
218  [
219  'parent_id' => $parentRole->getId(),
220  'tree_level' => $parentRole->getTreeLevel() + 1,
221  'sort_order' => 0,
222  'role_type' => RoleUser::ROLE_TYPE,
223  'user_id' => $user->getId(),
225  'role_name' => $user->getFirstName(),
226  ]
227  );
228 
229  $insertData = $this->_prepareDataForTable($data, $this->getTable('authorization_role'));
230  $this->getConnection()->insert($this->getTable('authorization_role'), $insertData);
231  $this->aclDataCache->clean();
232  }
233  }
234 
241  protected function _afterLoad(\Magento\Framework\Model\AbstractModel $user)
242  {
243  if (is_string($user->getExtra())) {
244  $user->setExtra($this->getSerializer()->unserialize($user->getExtra()));
245  }
246  return parent::_afterLoad($user);
247  }
248 
257  {
258  $this->_beforeDelete($user);
259  $connection = $this->getConnection();
260 
261  $uid = $user->getId();
262  $connection->beginTransaction();
263  try {
264  $connection->delete($this->getMainTable(), ['user_id = ?' => $uid]);
265  $connection->delete(
266  $this->getTable('authorization_role'),
267  ['user_id = ?' => $uid, 'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN]
268  );
269  } catch (\Magento\Framework\Exception\LocalizedException $e) {
270  throw $e;
271  } catch (\Exception $e) {
272  $connection->rollBack();
273  return false;
274  }
275  $connection->commit();
276  $this->_afterDelete($user);
277  return true;
278  }
279 
286  public function getRoles(\Magento\Framework\Model\AbstractModel $user)
287  {
288  if (!$user->getId()) {
289  return [];
290  }
291 
292  $table = $this->getTable('authorization_role');
293  $connection = $this->getConnection();
294 
295  $select = $connection->select()->from(
296  $table,
297  []
298  )->joinLeft(
299  ['ar' => $table],
300  "(ar.role_id = {$table}.parent_id and ar.role_type = '" . RoleGroup::ROLE_TYPE . "')",
301  ['role_id']
302  )->where(
303  "{$table}.user_id = :user_id"
304  )->where(
305  "{$table}.user_type = :user_type"
306  );
307 
308  $binds = ['user_id' => (int)$user->getId(),
310  ];
311 
312  $roles = $connection->fetchCol($select, $binds);
313 
314  if ($roles) {
315  return $roles;
316  }
317 
318  return [];
319  }
320 
327  public function deleteFromRole(\Magento\Framework\Model\AbstractModel $user)
328  {
329  if ($user->getUserId() <= 0) {
330  return $this;
331  }
332  if ($user->getRoleId() <= 0) {
333  return $this;
334  }
335 
336  $dbh = $this->getConnection();
337 
338  $condition = [
339  'user_id = ?' => (int)$user->getId(),
340  'parent_id = ?' => (int)$user->getRoleId(),
341  'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN
342  ];
343 
344  $dbh->delete($this->getTable('authorization_role'), $condition);
345  return $this;
346  }
347 
354  public function roleUserExists(\Magento\Framework\Model\AbstractModel $user)
355  {
356  if ($user->getUserId() > 0) {
357  $roleTable = $this->getTable('authorization_role');
358 
359  $dbh = $this->getConnection();
360 
361  $binds = [
362  'parent_id' => $user->getRoleId(),
363  'user_id' => $user->getUserId(),
365  ];
366 
367  $select = $dbh->select()->from($roleTable)
368  ->where('parent_id = :parent_id')
369  ->where('user_type = :user_type')
370  ->where('user_id = :user_id');
371 
372  return $dbh->fetchCol($select, $binds);
373  } else {
374  return [];
375  }
376  }
377 
384  public function userExists(\Magento\Framework\Model\AbstractModel $user)
385  {
386  $connection = $this->getConnection();
387  $select = $connection->select();
388 
389  $binds = [
390  'username' => $user->getUsername(),
391  'email' => $user->getEmail(),
392  'user_id' => (int)$user->getId(),
393  ];
394 
395  $select->from(
396  $this->getMainTable()
397  )->where(
398  '(username = :username OR email = :email)'
399  )->where(
400  'user_id <> :user_id'
401  );
402 
403  return $connection->fetchRow($select, $binds);
404  }
405 
412  public function isUserUnique(\Magento\Framework\Model\AbstractModel $user)
413  {
414  return !$this->userExists($user);
415  }
416 
424  public function saveExtra($object, $data)
425  {
426  if ($object->getId()) {
427  $this->getConnection()->update(
428  $this->getMainTable(),
429  ['extra' => $data],
430  ['user_id = ?' => (int)$object->getId()]
431  );
432  }
433 
434  return $this;
435  }
436 
442  public function countAll()
443  {
444  $connection = $this->getConnection();
445  $select = $connection->select();
446  $select->from($this->getMainTable(), 'COUNT(*)');
447  $result = (int)$connection->fetchOne($select);
448  return $result;
449  }
450 
457  {
458  $userIdentity = new \Zend_Validate_Callback([$this, 'isUserUnique']);
459  $userIdentity->setMessage(
460  __('A user with the same user name or email already exists.'),
462  );
463 
464  return $userIdentity;
465  }
466 
473  public function updateRoleUsersAcl(\Magento\Authorization\Model\Role $role)
474  {
475  $connection = $this->getConnection();
476  $users = $role->getRoleUsers();
477  $rowsCount = 0;
478 
479  if (sizeof($users) > 0) {
480  $bind = ['reload_acl_flag' => 1];
481  $where = ['user_id IN(?)' => $users];
482  $rowsCount = $connection->update($this->getTable('admin_user'), $bind, $where);
483  }
484 
485  return $rowsCount > 0;
486  }
487 
494  public function unlock($userIds)
495  {
496  if (!is_array($userIds)) {
497  $userIds = [$userIds];
498  }
499  return $this->getConnection()->update(
500  $this->getMainTable(),
501  ['failures_num' => 0, 'first_failure' => null, 'lock_expires' => null],
502  $this->getIdFieldName() . ' IN (' . $this->getConnection()->quote($userIds) . ')'
503  );
504  }
505 
514  public function lock($userIds, $exceptId, $lifetime)
515  {
516  if (!is_array($userIds)) {
517  $userIds = [$userIds];
518  }
519  $exceptId = (int)$exceptId;
520  return $this->getConnection()->update(
521  $this->getMainTable(),
522  ['lock_expires' => $this->dateTime->formatDate(time() + $lifetime)],
523  "{$this->getIdFieldName()} IN (" . $this->getConnection()->quote(
524  $userIds
525  ) . ")\n AND {$this->getIdFieldName()} <> {$exceptId}"
526  );
527  }
528 
537  public function updateFailure($user, $setLockExpires = false, $setFirstFailure = false)
538  {
539  $update = ['failures_num' => new \Zend_Db_Expr('failures_num + 1')];
540  if (false !== $setFirstFailure) {
541  $update['first_failure'] = $this->dateTime->formatDate($setFirstFailure);
542  $update['failures_num'] = 1;
543  }
544  if (false !== $setLockExpires) {
545  $update['lock_expires'] = $this->dateTime->formatDate($setLockExpires);
546  }
547  $this->getConnection()->update(
548  $this->getMainTable(),
549  $update,
550  $this->getConnection()->quoteInto("{$this->getIdFieldName()} = ?", $user->getId())
551  );
552  }
553 
561  public function getOldPasswords($user, $retainLimit = 4)
562  {
563  $userId = (int)$user->getId();
564  $table = $this->getTable('admin_passwords');
565 
566  // purge expired passwords, except those which should be retained
567  $retainPasswordIds = $this->getConnection()->fetchCol(
568  $this->getConnection()
569  ->select()
570  ->from($table, 'password_id')
571  ->where('user_id = :user_id')
572  ->order('password_id ' . \Magento\Framework\DB\Select::SQL_DESC)
573  ->limit($retainLimit),
574  [':user_id' => $userId]
575  );
576  $where = [
577  'user_id = ?' => $userId,
578  'last_updated <= ?' => time() - $this->observerConfig->getAdminPasswordLifetime()
579  ];
580  if ($retainPasswordIds) {
581  $where['password_id NOT IN (?)'] = $retainPasswordIds;
582  }
583  $this->getConnection()->delete($table, $where);
584 
585  // get all remaining passwords
586  return $this->getConnection()->fetchCol(
587  $this->getConnection()
588  ->select()
589  ->from($table, 'password_hash')
590  ->where('user_id = :user_id'),
591  [':user_id' => $userId]
592  );
593  }
594 
607  public function trackPassword($user, $passwordHash, $lifetime = 0)
608  {
609  $this->getConnection()->insert(
610  $this->getTable('admin_passwords'),
611  [
612  'user_id' => $user->getId(),
613  'password_hash' => $passwordHash,
614  'last_updated' => time()
615  ]
616  );
617  }
618 
626  public function getLatestPassword($userId)
627  {
628  return $this->getConnection()->fetchRow(
629  $this->getConnection()
630  ->select()
631  ->from($this->getTable('admin_passwords'))
632  ->where('user_id = :user_id')
633  ->order('password_id ' . \Magento\Framework\DB\Select::SQL_DESC)
634  ->limit(1),
635  [':user_id' => $userId]
636  );
637  }
638 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
userExists(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:384
lock($userIds, $exceptId, $lifetime)
Definition: User.php:514
_beforeDelete(\Magento\Framework\Model\AbstractModel $object)
Definition: AbstractDb.php:677
trackPassword($user, $passwordHash, $lifetime=0)
Definition: User.php:607
__()
Definition: __.php:13
$userIds
deleteFromRole(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:327
$user
Definition: dummy_user.php:13
_afterSave(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:177
isUserUnique(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:412
_afterDelete(\Magento\Framework\Model\AbstractModel $object)
Definition: AbstractDb.php:689
__construct(\Magento\Framework\Model\ResourceModel\Db\Context $context, \Magento\Authorization\Model\RoleFactory $roleFactory, \Magento\Framework\Stdlib\DateTime $dateTime, $connectionName=null, CacheInterface $aclDataCache=null, ObserverConfig $observerConfig=null)
Definition: User.php:58
updateFailure($user, $setLockExpires=false, $setFirstFailure=false)
Definition: User.php:537
roleUserExists(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:354
_clearUserRoles(ModelUser $user)
Definition: User.php:193
$connection
Definition: bulk.php:13
$table
Definition: trigger.php:14
getOldPasswords($user, $retainLimit=4)
Definition: User.php:561
getRoles(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:286
updateRoleUsersAcl(\Magento\Authorization\Model\Role $role)
Definition: User.php:473
_afterLoad(\Magento\Framework\Model\AbstractModel $user)
Definition: User.php:241