PasswordTrait::setPasswordResetToken()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 3.1406
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\base\models\traits;
14
15
use Yii;
16
use yii\base\ModelEvent;
17
18
/**
19
 * User features concerning password.
20
 *
21
 * Notice! Please DO NOT change password throughout modifying `pass_hash` property,
22
 * use `setPassword()` magic property instead!
23
 *
24
 * Set or directly reset password:
25
 * ```php
26
 * $this->password = '<new password>'; // 'afterSetPassword' event will be triggered.
27
 * $this->save();
28
 * ```
29
 *
30
 * @property-write string $password New password to be set.
31
 * @property array $passwordHashRules
32
 * @property array $passwordResetTokenRules
33
 * @property array $rules
34
 * @version 1.0
35
 * @author vistart <[email protected]>
36
 */
37
trait PasswordTrait
38
{
39
40
    public static $eventAfterSetPassword = "afterSetPassword";
41
    public static $eventBeforeValidatePassword = "beforeValidatePassword";
42
    public static $eventValidatePasswordSucceeded = "validatePasswordSucceeded";
43
    public static $eventValidatePasswordFailed = "validatePasswordFailed";
44
    public static $eventBeforeResetPassword = "beforeResetPassword";
45
    public static $eventAfterResetPassword = "afterResetPassword";
46
    public static $eventResetPasswordFailed = "resetPasswordFailed";
47
    public static $eventNewPasswordAppliedFor = "newPasswordAppliedFor";
48
    public static $eventPasswordResetTokenGenerated = "passwordResetTokenGenerated";
49
50
    /**
51
     * @var string The name of attribute used for storing password hash.
52
     * We strongly recommend you not to change `pass_hash` property directly,
53
     * please use setPassword() magic property instead.
54
     */
55
    public $passwordHashAttribute = 'pass_hash';
56
57
    /**
58
     * @var string The name of attribute used for storing password reset token.
59
     * If you do not want to provide password reset feature, please set `false`.
60
     */
61
    public $passwordResetTokenAttribute = 'password_reset_token';
62
63
    /**
64
     * @var integer Cost parameter used by the Blowfish hash algorithm.
65
     */
66
    public $passwordCost = 13;
67
68
    /**
69
     * @var integer if $passwordHashStrategy equals 'crypt', this value statically
70
     * equals 60.
71
     */
72
    public $passwordHashAttributeLength = 60;
73
    private $passwordHashRules = [];
74
    private $passwordResetTokenRules = [];
75
    
76
    /**
77
     * Return the empty password specialty.
78
     * NOTE: PLEASE OVERRIDE THIS METHOD TO SPECIFY YOUR OWN EMPTY PASSWORD SPECIALTY.
79
     * - The length of specialty should be greater than 18.
80
     * - Uppercase and lowercase letters, punctuation marks, numbers, and underscores are required.
81
     * @return string The string regarded as empty password.
82
     */
83 7
    protected function getEmptyPasswordSpecialty()
84
    {
85 7
        return 'Rrvl-7}cXt_<iAx[5s';
86
    }
87
    
88
    protected $_password;
89
90
    /**
91
     * Get rules of password hash.
92
     * @return array password hash rules.
93
     */
94 292
    public function getPasswordHashRules()
95
    {
96 292
        if (!is_string($this->passwordHashAttribute) || empty($this->passwordHashAttribute)) {
97
            return [];
98
        }
99 292
        if (empty($this->passwordHashRules) || !is_array($this->passwordHashRules)) {
100 290
            $this->passwordHashRules = [
101 290
                [[$this->passwordHashAttribute], 'string', 'max' => $this->passwordHashAttributeLength],
102
            ];
103
        }
104 292
        return $this->passwordHashRules;
105
    }
106
107
    /**
108
     * Set rules of password hash.
109
     * @param array $rules password hash rules.
110
     */
111 2
    public function setPasswordHashRules($rules)
112
    {
113 2
        if (!empty($rules) && is_array($rules)) {
114 2
            $this->passwordHashRules = $rules;
115
        }
116 2
    }
117
118
    /**
119
     * Get the rules associated with password reset token attribute.
120
     * If password reset feature is not enabled, the empty array will be given.
121
     * @return mixed
122
     */
123 292
    public function getPasswordResetTokenRules()
124
    {
125 292
        if (!is_string($this->passwordResetTokenAttribute) || empty($this->passwordResetTokenAttribute)) {
126
            return [];
127
        }
128 292
        if (empty($this->passwordResetTokenRules) || !is_array($this->passwordResetTokenRules)) {
129 290
            $this->passwordResetTokenRules = [
130 290
                [[$this->passwordResetTokenAttribute], 'string', 'length' => 40],
131 290
                [[$this->passwordResetTokenAttribute], 'unique'],
132
            ];
133
        }
134 292
        return $this->passwordResetTokenRules;
135
    }
136
137
    /**
138
     * Set the rules associated with password reset token attribute.
139
     * @param mixed $rules
140
     */
141 3
    public function setPasswordResetTokenRules($rules)
142
    {
143 3
        if (!empty($rules) && is_array($rules)) {
144 2
            $this->passwordResetTokenRules = $rules;
145
        }
146 3
    }
147
148
    /**
149
     * Generates a secure hash from a password and a random salt.
150
     *
151
     * The generated hash can be stored in database.
152
     * Later when a password needs to be validated, the hash can be fetched and passed
153
     * to [[validatePassword()]]. For example,
154
     *
155
     * ~~~
156
     * // generates the hash (usually done during user registration or when the password is changed)
157
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
158
     * // ...save $hash in database...
159
     *
160
     * // during login, validate if the password entered is correct using $hash fetched from database
161
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
162
     *     // password is good
163
     * } else {
164
     *     // password is bad
165
     * }
166
     * ~~~
167
     *
168
     * @param string $password The password to be hashed.
169
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
170
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
171
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
172
     */
173 191
    public function generatePasswordHash($password)
174
    {
175 191
        return Yii::$app->security->generatePasswordHash((string)$password, $this->passwordCost);
176
    }
177
178
    /**
179
     * Verifies a password against a hash.
180
     * @param string $password The password to verify.
181
     * @return boolean whether the password is correct.
182
     */
183 9
    public function validatePassword($password)
184
    {
185 9
        $phAttribute = $this->passwordHashAttribute;
186 9
        $result = Yii::$app->security->validatePassword($password, $this->$phAttribute);
187 9
        if ($result) {
188 8
            $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...
189 8
            return $result;
190
        }
191 2
        $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...
192 2
        return $result;
193
    }
194
195
    /**
196
     * Set new password.
197
     * If $password is empty, the specilty which represents the empty will be taken.
198
     * Finally, it will trigger `static::$eventAfterSetPassword` event.
199
     * @param string $password the new password to be set.
200
     */
201 191
    public function setPassword($password = null)
202
    {
203 191
        if (empty($password)) {
204 2
            $password = $this->getEmptyPasswordSpecialty();
205
        }
206 191
        $phAttribute = $this->passwordHashAttribute;
207 191
        if (empty($phAttribute) || !is_string($phAttribute)) {
208
            return;
209
        }
210 191
        $this->$phAttribute = $this->generatePasswordHash($password);
211 191
        $this->_password = $password;
212 191
        $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...
213 191
    }
214
    
215
    /**
216
     * Set empty password.
217
     */
218 4
    public function setEmptyPassword()
219
    {
220 4
        $this->password = $this->getEmptyPasswordSpecialty();
221 4
    }
222
    
223
    /**
224
     * Check whether password is empty.
225
     * @return boolean
226
     */
227 4
    public function getIsEmptyPassword()
228
    {
229
        return 
230 4
        (!is_string($this->passwordHashAttribute) || empty($this->passwordHashAttribute)) ? 
231 4
        true : $this->validatePassword($this->getEmptyPasswordSpecialty());
232
    }
233
234
    /**
235
     * Apply for new password.
236
     * If this model is new one, false will be given, and no events will be triggered.
237
     * If password reset feature is not enabled, `$eventNewPasswordAppliedFor`
238
     * will be triggered and return true directly.
239
     * Otherwise, the new password reset token will be regenerated and saved. Then
240
     * trigger the `$eventNewPasswordAppliedFor` and
241
     * `$eventPasswordResetTokenGenerated` events and return true.
242
     * @return boolean
243
     */
244 1
    public function applyForNewPassword()
245
    {
246 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...
247 1
            return false;
248
        }
249 1
        if (!is_string($this->passwordResetTokenAttribute)) {
250
            $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...
251
            return true;
252
        }
253 1
        $this->setPasswordResetToken(static::generatePasswordResetToken());
254 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...
255
            $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...
256
            return false;
257
        }
258 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...
259 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...
260 1
        return true;
261
    }
262
263
    /**
264
     * Reset password with password reset token.
265
     * It will validate password reset token, before reseting password.
266
     * @param string $password New password to be reset.
267
     * @param string $token Password reset token.
268
     * @return boolean whether reset password successfully or not.
269
     */
270 1
    public function resetPassword($password, $token)
271
    {
272 1
        if (!$this->validatePasswordResetToken($token)) {
273 1
            return false;
274
        }
275 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...
276 1
        $this->password = $password;
277 1
        $this->setPasswordResetToken();
278 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...
279
            $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...
280
            return false;
281
        }
282 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...
283 1
        return true;
284
    }
285
286
    /**
287
     * Generate password reset token.
288
     * @return string
289
     */
290 1
    public static function generatePasswordResetToken()
291
    {
292 1
        return sha1(Yii::$app->security->generateRandomString());
293
    }
294
295
    /**
296
     * The event triggered after new password set.
297
     * The auth key and access token should be regenerated if new password has applied.
298
     * @param ModelEvent $event
299
     */
300 9
    public function onAfterSetNewPassword($event)
301
    {
302 9
        $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...
303 9
        $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...
304 9
    }
305
306
    /**
307
     * Validate whether the $token is the valid password reset token.
308
     * If password reset feature is not enabled, true will be given.
309
     * @param string $token
310
     * @return boolean whether the token is correct.
311
     */
312 1
    protected function validatePasswordResetToken($token)
313
    {
314 1
        if (!is_string($this->passwordResetTokenAttribute) || empty($this->passwordResetTokenAttribute)) {
315
            return true;
316
        }
317 1
        return $this->getPasswordResetToken() === $token;
318
    }
319
320
    /**
321
     * Initialize password reset token attribute.
322
     * @param ModelEvent $event
323
     */
324 306
    public function onInitPasswordResetToken($event)
325
    {
326 306
        $sender = $event->sender;
327
        /* @var $sender static */
328 306
        return $sender->setPasswordResetToken();
329
    }
330
    
331
    /**
332
     * Set password reset token.
333
     * @param string $token
334
     * @return string
335
     */
336 306
    public function setPasswordResetToken($token = '')
337
    {
338 306
        if (empty($this->passwordResetTokenAttribute) || !is_string($this->passwordResetTokenAttribute)) {
339
            return null;
340
        }
341 306
        return $this->{$this->passwordResetTokenAttribute} = $token;
342
    }
343
    
344
    /**
345
     * Get password reset token.
346
     * @return string
347
     */
348 1
    public function getPasswordResetToken()
349
    {
350 1
        if (empty($this->passwordResetTokenAttribute) || !is_string($this->passwordResetTokenAttribute)) {
351
            return null;
352
        }
353 1
        return $this->{$this->passwordResetTokenAttribute};
354
    }
355
}
356