PasswordResetRequestForm.php 1.43 KB
Newer Older
1
<?php
2
namespace frontend\models;
3 4 5 6 7 8 9 10 11

use common\models\User;
use yii\base\Model;

/**
 * Password reset request form
 */
class PasswordResetRequestForm extends Model
{
12
    public $email;
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'exist',
                'targetClass' => '\common\models\User',
                'filter' => ['status' => User::STATUS_ACTIVE],
                'message' => 'There is no user with such email.'
            ],
        ];
    }
30

31 32 33 34 35 36 37 38
    /**
     * Sends an email with a link, for resetting the password.
     *
     * @return boolean whether the email was send
     */
    public function sendEmail()
    {
        /** @var User $user */
Alexander Makarov committed
39
        $user = User::findOne([
40 41 42
            'status' => User::STATUS_ACTIVE,
            'email' => $this->email,
        ]);
43

44 45 46 47 48 49 50 51 52 53
        if ($user) {
            $user->generatePasswordResetToken();
            if ($user->save()) {
                return \Yii::$app->mail->compose('passwordResetToken', ['user' => $user])
                    ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
                    ->setTo($this->email)
                    ->setSubject('Password reset for ' . \Yii::$app->name)
                    ->send();
            }
        }
54

55 56
        return false;
    }
57
}