0
0

PasswordResetRequestForm.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace frontend\models;
  3. use Yii;
  4. use yii\base\Model;
  5. use common\models\User;
  6. /**
  7. * Password reset request form
  8. */
  9. class PasswordResetRequestForm extends Model
  10. {
  11. public $email;
  12. /**
  13. * @inheritdoc
  14. */
  15. public function rules()
  16. {
  17. return [
  18. ['email', 'trim'],
  19. ['email', 'required'],
  20. ['email', 'email'],
  21. ['email', 'exist',
  22. 'targetClass' => '\common\models\User',
  23. 'filter' => ['status' => User::STATUS_ACTIVE],
  24. 'message' => 'There is no user with this email address.'
  25. ],
  26. ];
  27. }
  28. /**
  29. * Sends an email with a link, for resetting the password.
  30. *
  31. * @return bool whether the email was send
  32. */
  33. public function sendEmail()
  34. {
  35. /* @var $user User */
  36. $user = User::findOne([
  37. 'status' => User::STATUS_ACTIVE,
  38. 'email' => $this->email,
  39. ]);
  40. if (!$user) {
  41. return false;
  42. }
  43. if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
  44. $user->generatePasswordResetToken();
  45. if (!$user->save()) {
  46. return false;
  47. }
  48. }
  49. return Yii::$app
  50. ->mailer
  51. ->compose(
  52. ['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
  53. ['user' => $user]
  54. )
  55. ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
  56. ->setTo($this->email)
  57. ->setSubject('Password reset for ' . Yii::$app->name)
  58. ->send();
  59. }
  60. }