1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Model\ResourceModel;
use Magento\Authorization\Model\Acl\Role\Group as RoleGroup;
use Magento\Authorization\Model\Acl\Role\User as RoleUser;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\Acl\Data\CacheInterface;
use Magento\Framework\App\ObjectManager;
use Magento\User\Model\Backend\Config\ObserverConfig;
use Magento\User\Model\User as ModelUser;
/**
* ACL user resource
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @api
* @since 100.0.2
*/
class User extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Role model
*
* @var \Magento\Authorization\Model\RoleFactory
*/
protected $_roleFactory;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
/**
* @var CacheInterface
*/
private $aclDataCache;
/**
* @var ObserverConfig|null
*/
private $observerConfig;
/**
* Construct
*
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
* @param \Magento\Authorization\Model\RoleFactory $roleFactory
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param string $connectionName
* @param CacheInterface $aclDataCache
* @param ObserverConfig|null $observerConfig
*/
public function __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
) {
parent::__construct($context, $connectionName);
$this->_roleFactory = $roleFactory;
$this->dateTime = $dateTime;
$this->aclDataCache = $aclDataCache ?: ObjectManager::getInstance()->get(CacheInterface::class);
$this->observerConfig = $observerConfig ?: ObjectManager::getInstance()->get(ObserverConfig::class);
}
/**
* Define main table
*
* @return void
*/
protected function _construct()
{
$this->_init('admin_user', 'user_id');
}
/**
* Initialize unique fields
*
* @return $this
*/
protected function _initUniqueFields()
{
$this->_uniqueFields = [
['field' => 'email', 'title' => __('Email')],
['field' => 'username', 'title' => __('User Name')],
];
return $this;
}
/**
* Authenticate user by $username and $password
*
* @param ModelUser $user
* @return $this
*/
public function recordLogin(ModelUser $user)
{
$connection = $this->getConnection();
$data = [
'logdate' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
'lognum' => $user->getLognum() + 1,
];
$condition = ['user_id = ?' => (int)$user->getUserId()];
$connection->update($this->getMainTable(), $data, $condition);
return $this;
}
/**
* Load data by specified username
*
* @param string $username
* @return array
*/
public function loadByUsername($username)
{
$connection = $this->getConnection();
$select = $connection->select()->from($this->getMainTable())->where('username=:username');
$binds = ['username' => $username];
return $connection->fetchRow($select, $binds);
}
/**
* Check if user is assigned to any role
*
* @param int|ModelUser $user
* @return null|array
*/
public function hasAssigned2Role($user)
{
if (is_numeric($user)) {
$userId = $user;
} elseif ($user instanceof \Magento\Framework\Model\AbstractModel) {
$userId = $user->getUserId();
} else {
return null;
}
if ($userId > 0) {
$connection = $this->getConnection();
$select = $connection->select();
$select->from($this->getTable('authorization_role'))
->where('parent_id > :parent_id')
->where('user_id = :user_id')
->where('user_type = :user_type');
$binds = ['parent_id' => 0, 'user_id' => $userId,
'user_type' => UserContextInterface::USER_TYPE_ADMIN
];
return $connection->fetchAll($select, $binds);
} else {
return null;
}
}
/**
* Unserialize user extra data after user save
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return $this
*/
protected function _afterSave(\Magento\Framework\Model\AbstractModel $user)
{
$user->setExtra($this->getSerializer()->unserialize($user->getExtra()));
if ($user->hasRoleId()) {
$this->_clearUserRoles($user);
$this->_createUserRole($user->getRoleId(), $user);
}
return $this;
}
/**
* Clear all user-specific roles of provided user
*
* @param ModelUser $user
* @return void
*/
public function _clearUserRoles(ModelUser $user)
{
$conditions = ['user_id = ?' => (int)$user->getId(), 'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN];
$this->getConnection()->delete($this->getTable('authorization_role'), $conditions);
}
/**
* Create role for provided user of provided type
*
* @param int $parentId
* @param ModelUser $user
* @return void
*/
protected function _createUserRole($parentId, ModelUser $user)
{
if ($parentId > 0) {
/** @var \Magento\Authorization\Model\Role $parentRole */
$parentRole = $this->_roleFactory->create()->load($parentId);
} else {
$role = new \Magento\Framework\DataObject();
$role->setTreeLevel(0);
}
if ($parentRole->getId()) {
$data = new \Magento\Framework\DataObject(
[
'parent_id' => $parentRole->getId(),
'tree_level' => $parentRole->getTreeLevel() + 1,
'sort_order' => 0,
'role_type' => RoleUser::ROLE_TYPE,
'user_id' => $user->getId(),
'user_type' => UserContextInterface::USER_TYPE_ADMIN,
'role_name' => $user->getFirstName(),
]
);
$insertData = $this->_prepareDataForTable($data, $this->getTable('authorization_role'));
$this->getConnection()->insert($this->getTable('authorization_role'), $insertData);
$this->aclDataCache->clean();
}
}
/**
* Unserialize user extra data after user load
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return $this
*/
protected function _afterLoad(\Magento\Framework\Model\AbstractModel $user)
{
if (is_string($user->getExtra())) {
$user->setExtra($this->getSerializer()->unserialize($user->getExtra()));
}
return parent::_afterLoad($user);
}
/**
* Delete user role record with user
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function delete(\Magento\Framework\Model\AbstractModel $user)
{
$this->_beforeDelete($user);
$connection = $this->getConnection();
$uid = $user->getId();
$connection->beginTransaction();
try {
$connection->delete($this->getMainTable(), ['user_id = ?' => $uid]);
$connection->delete(
$this->getTable('authorization_role'),
['user_id = ?' => $uid, 'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN]
);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
throw $e;
} catch (\Exception $e) {
$connection->rollBack();
return false;
}
$connection->commit();
$this->_afterDelete($user);
return true;
}
/**
* Get user roles
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return array
*/
public function getRoles(\Magento\Framework\Model\AbstractModel $user)
{
if (!$user->getId()) {
return [];
}
$table = $this->getTable('authorization_role');
$connection = $this->getConnection();
$select = $connection->select()->from(
$table,
[]
)->joinLeft(
['ar' => $table],
"(ar.role_id = {$table}.parent_id and ar.role_type = '" . RoleGroup::ROLE_TYPE . "')",
['role_id']
)->where(
"{$table}.user_id = :user_id"
)->where(
"{$table}.user_type = :user_type"
);
$binds = ['user_id' => (int)$user->getId(),
'user_type' => UserContextInterface::USER_TYPE_ADMIN
];
$roles = $connection->fetchCol($select, $binds);
if ($roles) {
return $roles;
}
return [];
}
/**
* Delete user role
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return $this
*/
public function deleteFromRole(\Magento\Framework\Model\AbstractModel $user)
{
if ($user->getUserId() <= 0) {
return $this;
}
if ($user->getRoleId() <= 0) {
return $this;
}
$dbh = $this->getConnection();
$condition = [
'user_id = ?' => (int)$user->getId(),
'parent_id = ?' => (int)$user->getRoleId(),
'user_type = ?' => UserContextInterface::USER_TYPE_ADMIN
];
$dbh->delete($this->getTable('authorization_role'), $condition);
return $this;
}
/**
* Check if role user exists
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return array
*/
public function roleUserExists(\Magento\Framework\Model\AbstractModel $user)
{
if ($user->getUserId() > 0) {
$roleTable = $this->getTable('authorization_role');
$dbh = $this->getConnection();
$binds = [
'parent_id' => $user->getRoleId(),
'user_id' => $user->getUserId(),
'user_type' => UserContextInterface::USER_TYPE_ADMIN
];
$select = $dbh->select()->from($roleTable)
->where('parent_id = :parent_id')
->where('user_type = :user_type')
->where('user_id = :user_id');
return $dbh->fetchCol($select, $binds);
} else {
return [];
}
}
/**
* Check if user exists
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return array
*/
public function userExists(\Magento\Framework\Model\AbstractModel $user)
{
$connection = $this->getConnection();
$select = $connection->select();
$binds = [
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'user_id' => (int)$user->getId(),
];
$select->from(
$this->getMainTable()
)->where(
'(username = :username OR email = :email)'
)->where(
'user_id <> :user_id'
);
return $connection->fetchRow($select, $binds);
}
/**
* Whether a user's identity is confirmed
*
* @param \Magento\Framework\Model\AbstractModel $user
* @return bool
*/
public function isUserUnique(\Magento\Framework\Model\AbstractModel $user)
{
return !$this->userExists($user);
}
/**
* Save user extra data
*
* @param \Magento\Framework\Model\AbstractModel $object
* @param string $data
* @return $this
*/
public function saveExtra($object, $data)
{
if ($object->getId()) {
$this->getConnection()->update(
$this->getMainTable(),
['extra' => $data],
['user_id = ?' => (int)$object->getId()]
);
}
return $this;
}
/**
* Retrieve the total user count bypassing any filters applied to collections
*
* @return int
*/
public function countAll()
{
$connection = $this->getConnection();
$select = $connection->select();
$select->from($this->getMainTable(), 'COUNT(*)');
$result = (int)$connection->fetchOne($select);
return $result;
}
/**
* Add validation rules to be applied before saving an entity
*
* @return \Zend_Validate_Interface $validator
*/
public function getValidationRulesBeforeSave()
{
$userIdentity = new \Zend_Validate_Callback([$this, 'isUserUnique']);
$userIdentity->setMessage(
__('A user with the same user name or email already exists.'),
\Zend_Validate_Callback::INVALID_VALUE
);
return $userIdentity;
}
/**
* Update role users ACL
*
* @param \Magento\Authorization\Model\Role $role
* @return bool
*/
public function updateRoleUsersAcl(\Magento\Authorization\Model\Role $role)
{
$connection = $this->getConnection();
$users = $role->getRoleUsers();
$rowsCount = 0;
if (sizeof($users) > 0) {
$bind = ['reload_acl_flag' => 1];
$where = ['user_id IN(?)' => $users];
$rowsCount = $connection->update($this->getTable('admin_user'), $bind, $where);
}
return $rowsCount > 0;
}
/**
* Unlock specified user record(s)
*
* @param int|int[] $userIds
* @return int number of affected rows
*/
public function unlock($userIds)
{
if (!is_array($userIds)) {
$userIds = [$userIds];
}
return $this->getConnection()->update(
$this->getMainTable(),
['failures_num' => 0, 'first_failure' => null, 'lock_expires' => null],
$this->getIdFieldName() . ' IN (' . $this->getConnection()->quote($userIds) . ')'
);
}
/**
* Lock specified user record(s)
*
* @param int|int[] $userIds
* @param int $exceptId
* @param int $lifetime
* @return int number of affected rows
*/
public function lock($userIds, $exceptId, $lifetime)
{
if (!is_array($userIds)) {
$userIds = [$userIds];
}
$exceptId = (int)$exceptId;
return $this->getConnection()->update(
$this->getMainTable(),
['lock_expires' => $this->dateTime->formatDate(time() + $lifetime)],
"{$this->getIdFieldName()} IN (" . $this->getConnection()->quote(
$userIds
) . ")\n AND {$this->getIdFieldName()} <> {$exceptId}"
);
}
/**
* Increment failures count along with updating lock expire and first failure dates
*
* @param ModelUser $user
* @param int|bool $setLockExpires
* @param int|bool $setFirstFailure
* @return void
*/
public function updateFailure($user, $setLockExpires = false, $setFirstFailure = false)
{
$update = ['failures_num' => new \Zend_Db_Expr('failures_num + 1')];
if (false !== $setFirstFailure) {
$update['first_failure'] = $this->dateTime->formatDate($setFirstFailure);
$update['failures_num'] = 1;
}
if (false !== $setLockExpires) {
$update['lock_expires'] = $this->dateTime->formatDate($setLockExpires);
}
$this->getConnection()->update(
$this->getMainTable(),
$update,
$this->getConnection()->quoteInto("{$this->getIdFieldName()} = ?", $user->getId())
);
}
/**
* Purge and get remaining old password hashes
*
* @param ModelUser $user
* @param int $retainLimit
* @return array
*/
public function getOldPasswords($user, $retainLimit = 4)
{
$userId = (int)$user->getId();
$table = $this->getTable('admin_passwords');
// purge expired passwords, except those which should be retained
$retainPasswordIds = $this->getConnection()->fetchCol(
$this->getConnection()
->select()
->from($table, 'password_id')
->where('user_id = :user_id')
->order('password_id ' . \Magento\Framework\DB\Select::SQL_DESC)
->limit($retainLimit),
[':user_id' => $userId]
);
$where = [
'user_id = ?' => $userId,
'last_updated <= ?' => time() - $this->observerConfig->getAdminPasswordLifetime()
];
if ($retainPasswordIds) {
$where['password_id NOT IN (?)'] = $retainPasswordIds;
}
$this->getConnection()->delete($table, $where);
// get all remaining passwords
return $this->getConnection()->fetchCol(
$this->getConnection()
->select()
->from($table, 'password_hash')
->where('user_id = :user_id'),
[':user_id' => $userId]
);
}
/**
* Remember a password hash for further usage
*
* @param ModelUser $user
* @param string $passwordHash
* @param int $lifetime deprecated, password expiration date doesn't save anymore,
* it is calculated in runtime based on password created date and lifetime config value
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @see \Magento\User\Model\Backend\Config\ObserverConfig::_isLatestPasswordExpired()
*/
public function trackPassword($user, $passwordHash, $lifetime = 0)
{
$this->getConnection()->insert(
$this->getTable('admin_passwords'),
[
'user_id' => $user->getId(),
'password_hash' => $passwordHash,
'last_updated' => time()
]
);
}
/**
* Get latest password for specified user id
* Possible false positive when password was changed several times with different lifetime configuration
*
* @param int $userId
* @return array
*/
public function getLatestPassword($userId)
{
return $this->getConnection()->fetchRow(
$this->getConnection()
->select()
->from($this->getTable('admin_passwords'))
->where('user_id = :user_id')
->order('password_id ' . \Magento\Framework\DB\Select::SQL_DESC)
->limit(1),
[':user_id' => $userId]
);
}
}