1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace app\models\forms; |
4
|
|
|
|
5
|
|
|
use Yii; |
6
|
|
|
use yii\base\Exception; |
7
|
|
|
use yii\base\UserException; |
8
|
|
|
use app\models\entity\User; |
9
|
|
|
use app\services\Tokenizer; |
10
|
|
|
|
11
|
|
|
class PasswordResetRequestForm extends \yii\base\Model |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
public $email; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @inheritdoc |
20
|
|
|
*/ |
21
|
14 |
|
public function rules() |
22
|
|
|
{ |
23
|
|
|
return [ |
24
|
14 |
|
['email', 'filter', 'filter' => 'trim'], |
25
|
|
|
['email', 'required'], |
26
|
|
|
['email', 'email'], |
27
|
14 |
|
['email', 'exist', |
28
|
14 |
|
'targetClass' => '\app\models\entity\User', |
29
|
|
|
'filter' => ['status' => User::STATUS_ACTIVE], |
30
|
14 |
|
'message' => Yii::t('app.msg', 'There is no user with such email') |
31
|
|
|
], |
32
|
|
|
]; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @inheritdoc |
37
|
|
|
*/ |
38
|
12 |
|
public function attributeLabels() |
39
|
|
|
{ |
40
|
|
|
return [ |
41
|
12 |
|
'email' => Yii::t('app', 'Email'), |
42
|
|
|
]; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Sends an email with a link, for resetting the password |
47
|
|
|
* |
48
|
|
|
* @throws Exception |
49
|
|
|
* @throws UserException |
50
|
|
|
*/ |
51
|
6 |
|
public function sendEmail(): void |
52
|
|
|
{ |
53
|
|
|
/* @var $user User */ |
54
|
6 |
|
$user = User::find()->email($this->email)->one(); |
55
|
6 |
|
if (!$user) { |
56
|
3 |
|
throw new UserException(Yii::t('app.msg', 'User not found')); |
57
|
|
|
} |
58
|
|
|
|
59
|
3 |
|
$tokenizer = new Tokenizer(); |
60
|
3 |
|
if (!$tokenizer->validate($user->password_reset_token)) { |
61
|
1 |
|
$user->setPasswordResetToken($tokenizer->generate()); |
62
|
1 |
|
if (!$user->save()) { |
63
|
|
|
throw new Exception(Yii::t('app.msg', 'An error occurred while saving user')); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
3 |
|
$sent = Yii::$app->notify->sendMessage( |
68
|
3 |
|
$user->email, |
69
|
3 |
|
Yii::t('app', 'Password Reset'), |
70
|
3 |
|
'passwordResetToken', |
71
|
3 |
|
['user' => $user] |
72
|
|
|
); |
73
|
|
|
|
74
|
3 |
|
if (!$sent) { |
75
|
|
|
throw new UserException(Yii::t('app.msg', 'An error occurred while sending a message to reset password')); |
76
|
|
|
} |
77
|
3 |
|
} |
78
|
|
|
} |
79
|
|
|
|