PasswordResetRequestForm.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * @inheritdoc
  30. */
  31. public function attributeLabels()
  32. {
  33. return [
  34. 'username' => '验证码',
  35. 'name' => '姓名',
  36. 'email' => '电子邮件',
  37. 'password' => '密码',
  38. 'body' => '内容',
  39. ];
  40. }
  41. /**
  42. * Sends an email with a link, for resetting the password.
  43. *
  44. * @return bool whether the email was send
  45. */
  46. public function sendEmail()
  47. {
  48. /* @var $user User */
  49. $user = User::findOne([
  50. 'status' => User::STATUS_ACTIVE,
  51. 'email' => $this->email,
  52. ]);
  53. if (!$user) {
  54. return false;
  55. }
  56. if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
  57. $user->generatePasswordResetToken();
  58. if (!$user->save()) {
  59. return false;
  60. }
  61. }
  62. return Yii::$app
  63. ->mailer
  64. ->compose(
  65. ['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
  66. ['user' => $user]
  67. )
  68. ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
  69. ->setTo($this->email)
  70. ->setSubject('Password reset for ' . Yii::$app->name)
  71. ->send();
  72. }
  73. }