forked from magento/magento2
/
User.php
733 lines (664 loc) · 21.8 KB
/
User.php
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Magento\User\Model;
/**
* Admin user model
*
* @method \Magento\User\Model\Resource\User _getResource()
* @method \Magento\User\Model\Resource\User getResource()
* @method string getFirstname()
* @method \Magento\User\Model\User setFirstname(string $value)
* @method string getLastname()
* @method \Magento\User\Model\User setLastname(string $value)
* @method string getEmail()
* @method string getUsername()
* @method \Magento\User\Model\User setUsername(string $value)
* @method string getPassword()
* @method \Magento\User\Model\User setPassword(string $value)
* @method string getCreated()
* @method \Magento\User\Model\User setCreated(string $value)
* @method string getModified()
* @method \Magento\User\Model\User setModified(string $value)
* @method string getLogdate()
* @method \Magento\User\Model\User setLogdate(string $value)
* @method int getLognum()
* @method \Magento\User\Model\User setLognum(int $value)
* @method int getReloadAclFlag()
* @method \Magento\User\Model\User setReloadAclFlag(int $value)
* @method int getIsActive()
* @method \Magento\User\Model\User setIsActive(int $value)
* @method string getExtra()
* @method \Magento\User\Model\User setExtra(string $value)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.LongVariable)
*/
class User extends \Magento\Framework\Model\AbstractModel implements \Magento\Backend\Model\Auth\Credential\StorageInterface
{
/**
* Configuration paths for email templates and identities
*/
const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'admin/emails/forgot_email_template';
const XML_PATH_FORGOT_EMAIL_IDENTITY = 'admin/emails/forgot_email_identity';
const XML_PATH_RESET_PASSWORD_TEMPLATE = 'admin/emails/reset_password_template';
/**
* Minimum length of admin password
*/
const MIN_PASSWORD_LENGTH = 7;
/**
* Model event prefix
*
* @var string
*/
protected $_eventPrefix = 'admin_user';
/**
* Admin role
*
* @var \Magento\User\Model\Role
*/
protected $_role;
/**
* Available resources flag
*
* @var bool
*/
protected $_hasResources = true;
/**
* User data
*
* @var \Magento\User\Helper\Data
*/
protected $_userData = null;
/**
* Core store config
*
* @var \Magento\Backend\App\ConfigInterface
*/
protected $_config;
/**
* Factory for validator composite object
*
* @var \Magento\Framework\Validator\ObjectFactory
*/
protected $_validatorObject;
/**
* Role model factory
*
* @var \Magento\User\Model\RoleFactory
*/
protected $_roleFactory;
/**
* @var \Magento\Framework\Encryption\EncryptorInterface
*/
protected $_encryptor;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
/**
* @var \Magento\Framework\Mail\Template\TransportBuilder
*/
protected $_transportBuilder;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\User\Helper\Data $userData
* @param \Magento\Backend\App\ConfigInterface $config
* @param \Magento\Framework\Validator\ObjectFactory $validatorObjectFactory
* @param \Magento\User\Model\RoleFactory $roleFactory
* @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param \Magento\Framework\Model\Resource\AbstractResource $resource
* @param \Magento\Framework\Data\Collection\Db $resourceCollection
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\User\Helper\Data $userData,
\Magento\Backend\App\ConfigInterface $config,
\Magento\Framework\Validator\ObjectFactory $validatorObjectFactory,
\Magento\User\Model\RoleFactory $roleFactory,
\Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
\Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Magento\Framework\Stdlib\DateTime $dateTime,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Model\Resource\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\Db $resourceCollection = null,
array $data = array()
) {
$this->_encryptor = $encryptor;
$this->dateTime = $dateTime;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
$this->_userData = $userData;
$this->_config = $config;
$this->_validatorObject = $validatorObjectFactory;
$this->_roleFactory = $roleFactory;
$this->_transportBuilder = $transportBuilder;
$this->_storeManager = $storeManager;
}
/**
* Initialize user model
*
* @return void
*/
protected function _construct()
{
$this->_init('Magento\User\Model\Resource\User');
}
/**
* @return string[]
*/
public function __sleep()
{
$properties = parent::__sleep();
return array_diff(
$properties,
array(
'_eventManager',
'_userData',
'_config',
'_validatorObject',
'_roleFactory',
'_encryptor',
'_transportBuilder',
'_storeManager'
)
);
}
/**
* @return void
*/
public function __wakeup()
{
parent::__wakeup();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$this->_eventManager = $objectManager->get('Magento\Framework\Event\ManagerInterface');
$this->_userData = $objectManager->get('Magento\User\Helper\Data');
$this->_config = $objectManager->get('Magento\Backend\App\ConfigInterface');
$this->_registry = $objectManager->get('Magento\Framework\Registry');
$this->_validatorObject = $objectManager->get('Magento\Framework\Validator\ObjectFactory');
$this->_roleFactory = $objectManager->get('Magento\User\Model\RoleFactory');
$this->_encryptor = $objectManager->get('Magento\Framework\Encryption\EncryptorInterface');
$this->_transportBuilder = $objectManager->get('Magento\Framework\Mail\Template\TransportBuilder');
$this->_storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
}
/**
* Processing data before model save
*
* @return $this
*/
protected function _beforeSave()
{
$data = array(
'firstname' => $this->getFirstname(),
'lastname' => $this->getLastname(),
'email' => $this->getEmail(),
'modified' => $this->dateTime->now(),
'extra' => serialize($this->getExtra())
);
if ($this->getId() > 0) {
$data['user_id'] = $this->getId();
}
if ($this->getUsername()) {
$data['username'] = $this->getUsername();
}
if ($this->_willSavePassword()) {
$data['password'] = $this->_getEncodedPassword($this->getPassword());
}
if (!is_null($this->getIsActive())) {
$data['is_active'] = intval($this->getIsActive());
}
$this->addData($data);
return parent::_beforeSave();
}
/**
* Whether the password saving is going to occur
*
* @return bool
*/
protected function _willSavePassword()
{
return $this->isObjectNew() || $this->hasData('password') && $this->dataHasChangedFor('password');
}
/**
* Add validation rules for particular fields
*
* @return \Zend_Validate_Interface
*/
protected function _getValidationRulesBeforeSave()
{
$userNameNotEmpty = new \Zend_Validate_NotEmpty();
$userNameNotEmpty->setMessage(__('User Name is a required field.'), \Zend_Validate_NotEmpty::IS_EMPTY);
$firstNameNotEmpty = new \Zend_Validate_NotEmpty();
$firstNameNotEmpty->setMessage(__('First Name is a required field.'), \Zend_Validate_NotEmpty::IS_EMPTY);
$lastNameNotEmpty = new \Zend_Validate_NotEmpty();
$lastNameNotEmpty->setMessage(__('Last Name is a required field.'), \Zend_Validate_NotEmpty::IS_EMPTY);
$emailValidity = new \Zend_Validate_EmailAddress();
$emailValidity->setMessage(__('Please enter a valid email.'), \Zend_Validate_EmailAddress::INVALID);
/** @var $validator \Magento\Framework\Validator\Object */
$validator = $this->_validatorObject->create();
$validator->addRule(
$userNameNotEmpty,
'username'
)->addRule(
$firstNameNotEmpty,
'firstname'
)->addRule(
$lastNameNotEmpty,
'lastname'
)->addRule(
$emailValidity,
'email'
);
if ($this->_willSavePassword()) {
$this->_addPasswordValidation($validator);
}
return $validator;
}
/**
* Validate customer attribute values.
* For existing customer password + confirmation will be validated only when password is set
* (i.e. its change is requested)
*
* @return bool|string[]
*/
public function validate()
{
$errors = array();
if (!\Zend_Validate::is(trim($this->getUsername()), 'NotEmpty')) {
$errors[] = __('The user name cannot be empty.');
}
if (!\Zend_Validate::is(trim($this->getFirstname()), 'NotEmpty')) {
$errors[] = __('The first name cannot be empty.');
}
if (!\Zend_Validate::is(trim($this->getLastname()), 'NotEmpty')) {
$errors[] = __('The last name cannot be empty.');
}
if (!\Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
$errors[] = __('Please correct this email address: "%1".', $this->getEmail());
}
if (empty($errors)) {
return true;
}
return $errors;
}
/**
* Add validation rules for the password management fields
*
* @param \Magento\Framework\Validator\Object $validator
* @return void
*/
protected function _addPasswordValidation(\Magento\Framework\Validator\Object $validator)
{
$passwordNotEmpty = new \Zend_Validate_NotEmpty();
$passwordNotEmpty->setMessage(__('Password is required field.'), \Zend_Validate_NotEmpty::IS_EMPTY);
$minPassLength = self::MIN_PASSWORD_LENGTH;
$passwordLength = new \Zend_Validate_StringLength(array('min' => $minPassLength, 'encoding' => 'UTF-8'));
$passwordLength->setMessage(
__('Your password must be at least %1 characters.', $minPassLength),
\Zend_Validate_StringLength::TOO_SHORT
);
$passwordChars = new \Zend_Validate_Regex('/[a-z].*\d|\d.*[a-z]/iu');
$passwordChars->setMessage(
__('Your password must include both numeric and alphabetic characters.'),
\Zend_Validate_Regex::NOT_MATCH
);
$validator->addRule(
$passwordNotEmpty,
'password'
)->addRule(
$passwordLength,
'password'
)->addRule(
$passwordChars,
'password'
);
if ($this->hasPasswordConfirmation()) {
$passwordConfirmation = new \Zend_Validate_Identical($this->getPasswordConfirmation());
$passwordConfirmation->setMessage(
__('Your password confirmation must match your password.'),
\Zend_Validate_Identical::NOT_SAME
);
$validator->addRule($passwordConfirmation, 'password');
}
}
/**
* Process data after model is saved
*
* @return $this
*/
protected function _afterSave()
{
$this->_role = null;
return parent::_afterSave();
}
/**
* Save admin user extra data (like configuration sections state)
*
* @param array $data
* @return $this
*/
public function saveExtra($data)
{
if (is_array($data)) {
$data = serialize($data);
}
$this->_getResource()->saveExtra($this, $data);
return $this;
}
/**
* Retrieve user roles
*
* @return array
*/
public function getRoles()
{
return $this->_getResource()->getRoles($this);
}
/**
* Get admin role model
*
* @return \Magento\User\Model\Role
*/
public function getRole()
{
if (null === $this->_role) {
$this->_role = $this->_roleFactory->create();
$roles = $this->getRoles();
if ($roles && isset($roles[0]) && $roles[0]) {
$this->_role->load($roles[0]);
}
}
return $this->_role;
}
/**
* Unassign user from his current role
*
* @return $this
*/
public function deleteFromRole()
{
$this->_getResource()->deleteFromRole($this);
return $this;
}
/**
* Check if such combination role/user exists
*
* @return bool
*/
public function roleUserExists()
{
$result = $this->_getResource()->roleUserExists($this);
return is_array($result) && count($result) > 0 ? true : false;
}
/**
* Send email with reset password confirmation link
*
* @return $this
*/
public function sendPasswordResetConfirmationEmail()
{
// Set all required params and send emails
/** @var \Magento\Framework\Mail\TransportInterface $transport */
$transport = $this->_transportBuilder->setTemplateIdentifier(
$this->_config->getValue(self::XML_PATH_FORGOT_EMAIL_TEMPLATE)
)->setTemplateOptions(
array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => 0)
)->setTemplateVars(
array('user' => $this, 'store' => $this->_storeManager->getStore(0))
)->setFrom(
$this->_config->getValue(self::XML_PATH_FORGOT_EMAIL_IDENTITY)
)->addTo(
$this->getEmail(),
$this->getName()
)->getTransport();
$transport->sendMessage();
return $this;
}
/**
* Send email to when password is resetting
*
* @return $this
*/
public function sendPasswordResetNotificationEmail()
{
// Set all required params and send emails
/** @var \Magento\Framework\Mail\TransportInterface $transport */
$transport = $this->_transportBuilder->setTemplateIdentifier(
$this->_config->getValue(self::XML_PATH_RESET_PASSWORD_TEMPLATE)
)->setTemplateOptions(
array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => 0)
)->setTemplateVars(
array('user' => $this, 'store' => $this->_storeManager->getStore(0))
)->setFrom(
$this->_config->getValue(self::XML_PATH_FORGOT_EMAIL_IDENTITY)
)->addTo(
$this->getEmail(),
$this->getName()
)->getTransport();
$transport->sendMessage();
return $this;
}
/**
* Retrieve user name
*
* @param string $separator
* @return string
*/
public function getName($separator = ' ')
{
return $this->getFirstname() . $separator . $this->getLastname();
}
/**
* Retrieve user identifier
*
* @return mixed
*/
public function getId()
{
return $this->getUserId();
}
/**
* Get user ACL role
*
* @return string
*/
public function getAclRole()
{
return $this->getRole()->getId();
}
/**
* Authenticate user name and password and save loaded record
*
* @param string $username
* @param string $password
* @return bool
* @throws \Magento\Framework\Model\Exception
* @throws \Magento\Backend\Model\Auth\Exception
* @throws \Magento\Backend\Model\Auth\Plugin\Exception
*/
public function authenticate($username, $password)
{
$config = $this->_config->isSetFlag('admin/security/use_case_sensitive_login');
$result = false;
try {
$this->_eventManager->dispatch(
'admin_user_authenticate_before',
array('username' => $username, 'user' => $this)
);
$this->loadByUsername($username);
$sensitive = $config ? $username == $this->getUsername() : true;
if ($sensitive && $this->getId() && $this->_encryptor->validateHash($password, $this->getPassword())) {
if ($this->getIsActive() != '1') {
throw new \Magento\Backend\Model\Auth\Exception(__('This account is inactive.'));
}
if (!$this->hasAssigned2Role($this->getId())) {
throw new \Magento\Backend\Model\Auth\Exception(__('Access denied.'));
}
$result = true;
}
$this->_eventManager->dispatch(
'admin_user_authenticate_after',
array('username' => $username, 'password' => $password, 'user' => $this, 'result' => $result)
);
} catch (\Magento\Framework\Model\Exception $e) {
$this->unsetData();
throw $e;
}
if (!$result) {
$this->unsetData();
}
return $result;
}
/**
* Login user
*
* @param string $username
* @param string $password
* @return $this
*/
public function login($username, $password)
{
if ($this->authenticate($username, $password)) {
$this->getResource()->recordLogin($this);
}
return $this;
}
/**
* Reload current user
*
* @return $this
*/
public function reload()
{
$userId = $this->getId();
$this->setId(null);
$this->load($userId);
return $this;
}
/**
* Load user by its username
*
* @param string $username
* @return $this
*/
public function loadByUsername($username)
{
$data = $this->getResource()->loadByUsername($username);
if ($data !== false) {
$this->setData($data);
}
return $this;
}
/**
* Check if user is assigned to any role
*
* @param int|\Magento\User\Model\User $user
* @return null|array
*/
public function hasAssigned2Role($user)
{
return $this->getResource()->hasAssigned2Role($user);
}
/**
* Retrieve encoded password
*
* @param string $password
* @return string
*/
protected function _getEncodedPassword($password)
{
return $this->_encryptor->getHash($password, true);
}
/**
* Change reset password link token
*
* Stores new reset password link token and its creation time
*
* @param string $newToken
* @return $this
* @throws \Magento\Framework\Model\Exception
*/
public function changeResetPasswordLinkToken($newToken)
{
if (!is_string($newToken) || empty($newToken)) {
throw new \Magento\Framework\Model\Exception(__('Please correct the password reset token.'));
}
$this->setRpToken($newToken);
$this->setRpTokenCreatedAt($this->dateTime->now());
return $this;
}
/**
* Check if current reset password link token is expired
*
* @return bool
*/
public function isResetPasswordLinkTokenExpired()
{
$linkToken = $this->getRpToken();
$linkTokenCreatedAt = $this->getRpTokenCreatedAt();
if (empty($linkToken) || empty($linkTokenCreatedAt)) {
return true;
}
$expirationPeriod = $this->_userData->getResetPasswordLinkExpirationPeriod();
$currentTimestamp = $this->dateTime->toTimestamp($this->dateTime->now());
$tokenTimestamp = $this->dateTime->toTimestamp($linkTokenCreatedAt);
if ($tokenTimestamp > $currentTimestamp) {
return true;
}
$dayDifference = floor(($currentTimestamp - $tokenTimestamp) / (24 * 60 * 60));
if ($dayDifference >= $expirationPeriod) {
return true;
}
return false;
}
/**
* Check if user has available resources
*
* @return bool
*/
public function hasAvailableResources()
{
return $this->_hasResources;
}
/**
* Set user has available resources
*
* @param bool $hasResources
* @return $this
*/
public function setHasAvailableResources($hasResources)
{
$this->_hasResources = $hasResources;
return $this;
}
}