Completed
Push — master ( 89be15...80fd60 )
by Igor
11:15
created

PasswordResetRequestForm::sendEmail()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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