ResetPasswordForm.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace common\modules\user\models;
  3. use yii\base\InvalidParamException;
  4. use yii\base\Model;
  5. /**
  6. * Password reset form.
  7. */
  8. class ResetPasswordForm extends Model
  9. {
  10. public $password;
  11. /**
  12. * @var \common\modules\user\models\User
  13. */
  14. private $_user;
  15. /**
  16. * Creates a form model given a token.
  17. *
  18. * @param string $token
  19. * @param array $config name-value pairs that will be used to initialize the object properties
  20. *
  21. * @throws \yii\base\InvalidParamException if token is empty or not valid
  22. */
  23. public function __construct($token, $config = [])
  24. {
  25. if (empty($token) || !is_string($token)) {
  26. throw new InvalidParamException('Password reset token cannot be blank.');
  27. }
  28. $this->_user = User::findByPasswordResetToken($token);
  29. if (!$this->_user) {
  30. throw new InvalidParamException('Wrong password reset token.');
  31. }
  32. parent::__construct($config);
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function rules()
  38. {
  39. return [
  40. ['password', 'required'],
  41. ['password', 'string', 'min' => 6],
  42. ];
  43. }
  44. public function attributeLabels()
  45. {
  46. return [
  47. 'password' => '密码'
  48. ];
  49. }
  50. /**
  51. * Resets password.
  52. *
  53. * @return bool if password was reset.
  54. */
  55. public function resetPassword()
  56. {
  57. $user = $this->_user;
  58. $user->setPassword($this->password);
  59. $user->removePasswordResetToken();
  60. return $user->save(false);
  61. }
  62. }