Test Failed
Push — master ( 5196a6...aaaa1a )
by vistart
08:44
created

traits/PasswordTrait.php (4 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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