Completed
Push — master ( e765e7...0b5840 )
by vistart
05:28
created

PasswordTrait::applyNewPassword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.243

Importance

Changes 7
Bugs 1 Features 0
Metric Value
c 7
b 1
f 0
dl 0
loc 14
ccs 7
cts 10
cp 0.7
rs 9.4285
cc 3
eloc 10
nc 3
nop 0
crap 3.243
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license https://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use Yii;
16
17
/**
18
 * User features concerning password.
19
 * @property-write string $password New password to be set.
20
 * @property array $passwordHashRules
21
 * @property array $passwordResetTokenRules
22
 * @property array $rules
23
 * @version 2.0
24
 * @author vistart <[email protected]>
25
 */
26
trait PasswordTrait
27
{
28
29
    public static $eventAfterSetPassword = "afterSetPassword";
30
    public static $eventBeforeValidatePassword = "beforeValidatePassword";
31
    public static $eventValidatePasswordSucceeded = "validatePasswordSucceeded";
32
    public static $eventValidatePasswordFailed = "validatePasswordFailed";
33
    public static $eventBeforeResetPassword = "beforeResetPassword";
34
    public static $eventAfterResetPassword = "afterResetPassword";
35
    public static $eventResetPasswordFailed = "resetPasswordFailed";
36
    public static $eventNewPasswordAppliedFor = "newPasswordAppliedFor";
37
    public static $eventPasswordResetTokenGenerated = "passwordResetTokenGenerated";
38
39
    /**
40
     * @var string The name of attribute used for storing password hash.
41
     */
42
    public $passwordHashAttribute = 'pass_hash';
43
44
    /**
45
     * @var string The name of attribute used for storing password reset token.
46
     * If you do not want to provide password reset feature, please set `false`. 
47
     */
48
    public $passwordResetTokenAttribute = 'password_reset_token';
49
50
    /**
51
     * @var integer Cost parameter used by the Blowfish hash algorithm.
52
     */
53
    public $passwordCost = 13;
54
55
    /**
56
     * @var string strategy, which should be used to generate password hash.
57
     * Available strategies:
58
     * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
59
     *   This option is recommended, but it requires PHP version >= 5.5.0
60
     * - 'crypt' - use PHP `crypt()` function.
61
     */
62
    public $passwordHashStrategy = 'crypt';
63
64
    /**
65
     * @var integer if $passwordHashStrategy equals 'crypt', this value statically
66
     * equals 60.
67
     */
68
    public $passwordHashAttributeLength = 60;
69
    private $passwordHashRules = [];
70
    private $passwordResetTokenRules = [];
71
72
    /**
73
     * Get rules of password hash.
74
     * @return array password hash rules.
75
     */
76 1
    public function getPasswordHashRules()
77
    {
78 1
        if ($this->passwordHashStrategy == 'crypt') {
79 1
            $this->passwordHashAttributeLength = 60;
80 1
        }
81 1
        if (empty($this->passwordHashRules) || !is_array($this->passwordHashRules)) {
82 1
            $this->passwordHashRules = [
83 1
                [[$this->passwordHashAttribute], 'string', 'max' => $this->passwordHashAttributeLength],
84
            ];
85 1
        }
86 1
        return $this->passwordHashRules;
87
    }
88
89
    /**
90
     * Set rules of password hash.
91
     * @param array $rules password hash rules.
92
     */
93
    public function setPasswordHashRules($rules)
94
    {
95
        if (!empty($rules) && is_array($rules)) {
96
            $this->passwordHashRules = $rules;
97
        }
98
    }
99
100
    /**
101
     * Get the rules associated with password reset token attribute.
102
     * If password reset feature is not enabled, the empty array will be given.
103
     * @return mixed
104
     */
105
    public function getPasswordResetTokenRules()
106
    {
107
        if (!is_string($this->passwordResetTokenAttribute)) {
108
            return [];
109
        }
110
        if (empty($this->passwordResetTokenRules) || !is_array($this->passwordResetTokenRules)) {
111
            $this->passwordResetTokenRules = [
112
                [[$this->passwordResetTokenAttribute], 'string', 'length' => 40],
113
                [[$this->passwordResetTokenAttribute], 'unique'],
114
            ];
115
        }
116
        return $this->passwordResetTokenRules;
117
    }
118
119
    /**
120
     * Set the rules associated with password reset token attribute.
121
     * @param mixed $rules
122
     */
123
    public function setPasswordResetTokenRules($rules)
124
    {
125
        if (!empty($rules) && is_array($rules)) {
126
            $this->passwordResetTokenRules = $rules;
127
        }
128
    }
129
130
    /**
131
     * Generates a secure hash from a password and a random salt.
132
     *
133
     * The generated hash can be stored in database.
134
     * Later when a password needs to be validated, the hash can be fetched and passed
135
     * to [[validatePassword()]]. For example,
136
     *
137
     * ~~~
138
     * // generates the hash (usually done during user registration or when the password is changed)
139
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
140
     * // ...save $hash in database...
141
     *
142
     * // during login, validate if the password entered is correct using $hash fetched from database
143
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
144
     *     // password is good
145
     * } else {
146
     *     // password is bad
147
     * }
148
     * ~~~
149
     *
150
     * @param string $password The password to be hashed.
151
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
152
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
153
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
154
     */
155
    public function generatePasswordHash($password)
156
    {
157
        Yii::$app->security->passwordHashStrategy = $this->passwordHashStrategy;
158
        return Yii::$app->security->generatePasswordHash($password, $this->passwordCost);
159
    }
160
161
    /**
162
     * Verifies a password against a hash.
163
     * @param string $password The password to verify.
164
     * @return boolean whether the password is correct.
165
     */
166 1
    public function validatePassword($password)
167
    {
168 1
        $phAttribute = $this->passwordHashAttribute;
169 1
        $result = Yii::$app->security->validatePassword($password, $this->$phAttribute);
170 1
        if ($result) {
171 1
            $this->trigger(static::$eventValidatePasswordSucceeded);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
172 1
            return $result;
173
        }
174
        $this->trigger(static::$eventValidatePasswordFailed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
175
        return $result;
176
    }
177
178
    /**
179
     * Set new password.
180
     * @param string $password the new password to be set.
181
     */
182 28
    public function setPassword($password)
183
    {
184 28
        $phAttribute = $this->passwordHashAttribute;
185 28
        $this->$phAttribute = Yii::$app->security->generatePasswordHash($password);
186 28
        $this->trigger(static::$eventAfterSetPassword);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
187 28
    }
188
189
    /**
190
     * Apply for new password.
191
     * If this model is new one, false will be given, and no events will be triggered.
192
     * If password reset feature is not enabled, `$eventNewPasswordAppliedFor`
193
     * will be triggered and return true directly.
194
     * Otherwise, the new password reset token will be regenerated and saved. Then
195
     * trigger the `$eventNewPasswordAppliedFor` and
196
     * `$eventPasswordResetTokenGenerated` events and return true.
197
     * @return boolean
198
     */
199 1
    public function applyForNewPassword()
200
    {
201 1
        if ($this->isNewRecord) {
0 ignored issues
show
Bug introduced by
The property isNewRecord does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
202
            return false;
203
        }
204 1
        if (!is_string($this->passwordResetTokenAttribute)) {
205
            $this->trigger(static::$eventNewPasswordAppliedFor);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
206
            return true;
207
        }
208 1
        $prtAttribute = $this->passwordResetTokenAttribute;
209 1
        $this->$prtAttribute = static::generatePasswordResetToken();
210 1
        if (!$this->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
211
            $this->trigger(static::$eventResetPasswordFailed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
212
            return false;
213
        }
214 1
        $this->trigger(static::$eventNewPasswordAppliedFor);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
215 1
        $this->trigger(static::$eventPasswordResetTokenGenerated);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
216 1
        return true;
217
    }
218
219
    /**
220
     * Reset password with password reset token.
221
     * It will validate password reset token, before reseting password.
222
     * @param string $password
223
     * @param string $token
224
     * @return boolean whether reset password successfully or not.
225
     */
226 1
    public function resetPassword($password, $token)
227
    {
228 1
        if (!$this->validatePasswordResetToken($token)) {
229
            return false;
230
        }
231 1
        $this->trigger(static::$eventBeforeResetPassword);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
232 1
        $this->password = $password;
233 1
        if (is_string($this->passwordResetTokenAttribute)) {
234 1
            $prtAttribute = $this->passwordResetTokenAttribute;
235 1
            $this->$prtAttribute = '';
236 1
        }
237 1
        if (!$this->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
238
            $this->trigger(static::$eventResetPasswordFailed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
239
            return false;
240
        }
241 1
        $this->trigger(static::$eventAfterResetPassword);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
242 1
        return true;
243
    }
244
245
    /**
246
     * Generate password reset token.
247
     * @return string
248
     */
249 1
    public static function generatePasswordResetToken()
250
    {
251 1
        return sha1(Yii::$app->security->generateRandomString());
252
    }
253
254
    /**
255
     * The event triggered after new password set.
256
     * The auth key and access token should be regenerated if new password has applied.
257
     * @param \yii\base\Event $event
258
     */
259 3
    public function onAfterSetNewPassword($event)
260
    {
261 3
        $this->onInitAuthKey($event);
0 ignored issues
show
Bug introduced by
It seems like onInitAuthKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
262 3
        $this->onInitAccessToken($event);
0 ignored issues
show
Bug introduced by
It seems like onInitAccessToken() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
263 3
    }
264
265
    /**
266
     * Validate whether the $token is the valid password reset token.
267
     * If password reset feature is not enabled, true will be given.
268
     * @param string $token
269
     * @return boolean whether the token is correct.
270
     */
271 1
    protected function validatePasswordResetToken($token)
272
    {
273 1
        if (!is_string($this->passwordResetTokenAttribute)) {
274
            return true;
275
        }
276 1
        $prtAttribute = $this->passwordResetTokenAttribute;
277 1
        return $this->$prtAttribute === $token;
278
    }
279
280
    /**
281
     * Initialize password reset token attribute.
282
     * @param \yii\base\ModelEvent $event
283
     */
284 38
    public function onInitPasswordResetToken($event)
285
    {
286 38
        $sender = $event->sender;
287 38
        if (!is_string($sender->passwordResetTokenAttribute)) {
288
            return;
289
        }
290 38
        $prtAttribute = $sender->passwordResetTokenAttribute;
291 38
        $sender->$prtAttribute = '';
292 38
    }
293
}
294