Completed
Push — master ( 1d1fd8...eec31e )
by vistart
05:27
created

PasswordTrait::setPasswordResetToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 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 5
    protected function getEmptyPasswordSpecialty()
84
    {
85 5
        return 'Rrvl-7}cXt_<iAx[5s';
86
    }
87
88
    /**
89
     * Get rules of password hash.
90
     * @return array password hash rules.
91
     */
92 87
    public function getPasswordHashRules()
93
    {
94 87
        if (empty($this->passwordHashRules) || !is_array($this->passwordHashRules)) {
95 85
            $this->passwordHashRules = [
96 85
                [[$this->passwordHashAttribute], 'string', 'max' => $this->passwordHashAttributeLength],
97
            ];
98 85
        }
99 87
        return $this->passwordHashRules;
100
    }
101
102
    /**
103
     * Set rules of password hash.
104
     * @param array $rules password hash rules.
105
     */
106 2
    public function setPasswordHashRules($rules)
107
    {
108 2
        if (!empty($rules) && is_array($rules)) {
109 2
            $this->passwordHashRules = $rules;
110 2
        }
111 2
    }
112
113
    /**
114
     * Get the rules associated with password reset token attribute.
115
     * If password reset feature is not enabled, the empty array will be given.
116
     * @return mixed
117
     */
118 87
    public function getPasswordResetTokenRules()
119
    {
120 87
        if (!is_string($this->passwordResetTokenAttribute)) {
121
            return [];
122
        }
123 87
        if (empty($this->passwordResetTokenRules) || !is_array($this->passwordResetTokenRules)) {
124 85
            $this->passwordResetTokenRules = [
125 85
                [[$this->passwordResetTokenAttribute], 'string', 'length' => 40],
126 85
                [[$this->passwordResetTokenAttribute], 'unique'],
127
            ];
128 85
        }
129 87
        return $this->passwordResetTokenRules;
130
    }
131
132
    /**
133
     * Set the rules associated with password reset token attribute.
134
     * @param mixed $rules
135
     */
136 3
    public function setPasswordResetTokenRules($rules)
137
    {
138 3
        if (!empty($rules) && is_array($rules)) {
139 2
            $this->passwordResetTokenRules = $rules;
140 2
        }
141 3
    }
142
143
    /**
144
     * Generates a secure hash from a password and a random salt.
145
     *
146
     * The generated hash can be stored in database.
147
     * Later when a password needs to be validated, the hash can be fetched and passed
148
     * to [[validatePassword()]]. For example,
149
     *
150
     * ~~~
151
     * // generates the hash (usually done during user registration or when the password is changed)
152
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
153
     * // ...save $hash in database...
154
     *
155
     * // during login, validate if the password entered is correct using $hash fetched from database
156
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
157
     *     // password is good
158
     * } else {
159
     *     // password is bad
160
     * }
161
     * ~~~
162
     *
163
     * @param string $password The password to be hashed.
164
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
165
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
166
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
167
     */
168 12
    public function generatePasswordHash($password)
169
    {
170 12
        return Yii::$app->security->generatePasswordHash((string)$password, $this->passwordCost);
171
    }
172
173
    /**
174
     * Verifies a password against a hash.
175
     * @param string $password The password to verify.
176
     * @return boolean whether the password is correct.
177
     */
178 8
    public function validatePassword($password)
179
    {
180 8
        $phAttribute = $this->passwordHashAttribute;
181 8
        $result = Yii::$app->security->validatePassword($password, $this->$phAttribute);
182 8
        if ($result) {
183 7
            $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...
184 7
            return $result;
185
        }
186 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...
187 2
        return $result;
188
    }
189
190
    /**
191
     * Set new password.
192
     * @param string $password the new password to be set.
193
     */
194 12
    public function setPassword($password = null)
195
    {
196 12
        if (empty($password)) {
197 2
            $password = $this->getEmptyPasswordSpecialty();
198 2
        }
199 12
        $phAttribute = $this->passwordHashAttribute;
200 12
        $this->$phAttribute = $this->generatePasswordHash($password);
201 12
        $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...
202 12
    }
203
    
204
    /**
205
     * Set empty password.
206
     */
207 2
    public function setEmptyPassword()
208
    {
209 2
        $this->password = $this->getEmptyPasswordSpecialty();
210 2
    }
211
    
212
    /**
213
     * Check whether password is empty.
214
     * @return boolean
215
     */
216 3
    public function getIsEmptyPassword()
217
    {
218
        return 
219 3
        (!is_string($this->passwordHashAttribute) || empty($this->passwordHashAttribute)) ? 
220 3
        true : $this->validatePassword($this->getEmptyPasswordSpecialty());
221
    }
222
223
    /**
224
     * Apply for new password.
225
     * If this model is new one, false will be given, and no events will be triggered.
226
     * If password reset feature is not enabled, `$eventNewPasswordAppliedFor`
227
     * will be triggered and return true directly.
228
     * Otherwise, the new password reset token will be regenerated and saved. Then
229
     * trigger the `$eventNewPasswordAppliedFor` and
230
     * `$eventPasswordResetTokenGenerated` events and return true.
231
     * @return boolean
232
     */
233 1
    public function applyForNewPassword()
234
    {
235 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...
236 1
            return false;
237
        }
238 1
        if (!is_string($this->passwordResetTokenAttribute)) {
239
            $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...
240
            return true;
241
        }
242 1
        $prtAttribute = $this->passwordResetTokenAttribute;
243 1
        $this->$prtAttribute = static::generatePasswordResetToken();
244 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...
245
            $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...
246
            return false;
247
        }
248 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...
249 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...
250 1
        return true;
251
    }
252
253
    /**
254
     * Reset password with password reset token.
255
     * It will validate password reset token, before reseting password.
256
     * @param string $password New password to be reset.
257
     * @param string $token Password reset token.
258
     * @return boolean whether reset password successfully or not.
259
     */
260 1
    public function resetPassword($password, $token)
261
    {
262 1
        if (!$this->validatePasswordResetToken($token)) {
263 1
            return false;
264
        }
265 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...
266 1
        $this->password = $password;
267 1
        if (is_string($this->passwordResetTokenAttribute)) {
268 1
            $this->setPasswordResetToken();
269 1
        }
270 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...
271
            $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...
272
            return false;
273
        }
274 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...
275 1
        return true;
276
    }
277
278
    /**
279
     * Generate password reset token.
280
     * @return string
281
     */
282 1
    public static function generatePasswordResetToken()
283
    {
284 1
        return sha1(Yii::$app->security->generateRandomString());
285
    }
286
287
    /**
288
     * The event triggered after new password set.
289
     * The auth key and access token should be regenerated if new password has applied.
290
     * @param ModelEvent $event
291
     */
292 8
    public function onAfterSetNewPassword($event)
293
    {
294 8
        $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...
295 8
        $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...
296 8
    }
297
298
    /**
299
     * Validate whether the $token is the valid password reset token.
300
     * If password reset feature is not enabled, true will be given.
301
     * @param string $token
302
     * @return boolean whether the token is correct.
303
     */
304 1
    protected function validatePasswordResetToken($token)
305
    {
306 1
        if (!is_string($this->passwordResetTokenAttribute)) {
307
            return true;
308
        }
309 1
        return $this->getPasswordResetToken() === $token;
310
    }
311
312
    /**
313
     * Initialize password reset token attribute.
314
     * @param ModelEvent $event
315
     */
316 93
    public function onInitPasswordResetToken($event)
317
    {
318 93
        $sender = $event->sender;
319 93
        if (!is_string($sender->passwordResetTokenAttribute)) {
320
            return;
321
        }
322 93
        $this->setPasswordResetToken();
323 93
    }
324
    
325
    /**
326
     * Set password reset token.
327
     * @param string $token
328
     * @return string
329
     */
330 93
    public function setPasswordResetToken($token = '')
331
    {
332 93
        return $this->{$this->passwordResetTokenAttribute} = $token;
333
    }
334
    
335
    /**
336
     * Get password reset token.
337
     * @return string
338
     */
339 1
    public function getPasswordResetToken()
340
    {
341 1
        return $this->{$this->passwordResetTokenAttribute};
342
    }
343
}
344