-
Notifications
You must be signed in to change notification settings - Fork 614
/
UserPasswordValidator.php
110 lines (92 loc) · 2.44 KB
/
UserPasswordValidator.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\validators;
use Craft;
use yii\base\Model;
use yii\validators\StringValidator;
/**
* Class UserPasswordValidator.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class UserPasswordValidator extends StringValidator
{
/**
* @since 3.5.18
*/
const MIN_PASSWORD_LENGTH = 6;
/**
* @since 3.5.18
*/
const MAX_PASSWORD_LENGTH = 160;
/**
* @var bool Whether the password must be different from the existing password.
*/
public $forceDifferent = false;
/**
* @var string|null The user's current (hashed) password.
*/
public $currentPassword;
/**
* @var string|null User-defined error message used when the new password is the same as [[currentPassword]].
*/
public $sameAsCurrent;
/**
* @inheritdoc
*/
public function __construct(array $config = [])
{
// Default min
if (!isset($config['min'])) {
$config['min'] = self::MIN_PASSWORD_LENGTH;
}
// Default max
if (!isset($config['max'])) {
$config['max'] = self::MAX_PASSWORD_LENGTH;
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->forceDifferent && $this->sameAsCurrent === null) {
$this->sameAsCurrent = Craft::t('app', '{attribute} must be set to a new password.');
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
/** @var Model $model */
parent::validateAttribute($model, $attribute);
if ($model->hasErrors($attribute)) {
return;
}
if ($this->forceDifferent && $this->currentPassword) {
$newPassword = $model->$attribute;
if (Craft::$app->getSecurity()->validatePassword($newPassword, $this->currentPassword)) {
$this->addError($model, $attribute, $this->sameAsCurrent);
}
}
}
/**
* @inheritdoc
*/
public function isEmpty($value)
{
if ($this->isEmpty !== null) {
return call_user_func($this->isEmpty, $value);
}
// Don't let an empty string count as empty
return $value === null;
}
}