LoginForm.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace common\models;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * Login form
  7. */
  8. class LoginForm extends Model
  9. {
  10. public $username;
  11. public $password;
  12. public $rememberMe = true;
  13. private $_user;
  14. /**
  15. * @inheritdoc
  16. */
  17. public function rules()
  18. {
  19. return [
  20. // username and password are both required
  21. [['username', 'password'], 'required'],
  22. // rememberMe must be a boolean value
  23. ['rememberMe', 'boolean'],
  24. // password is validated by validatePassword()
  25. ['password', 'validatePassword'],
  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. * Validates the password.
  43. * This method serves as the inline validation for password.
  44. *
  45. * @param string $attribute the attribute currently being validated
  46. * @param array $params the additional name-value pairs given in the rule
  47. */
  48. public function validatePassword($attribute, $params)
  49. {
  50. if (!$this->hasErrors()) {
  51. $user = $this->getUser();
  52. if (!$user || !$user->validatePassword($this->password)) {
  53. $this->addError($attribute, 'Incorrect username or password.');
  54. }
  55. }
  56. }
  57. /**
  58. * Logs in a user using the provided username and password.
  59. *
  60. * @return bool whether the user is logged in successfully
  61. */
  62. public function login()
  63. {
  64. if ($this->validate()) {
  65. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  66. }
  67. return false;
  68. }
  69. /**
  70. * Finds user by [[username]]
  71. *
  72. * @return User|null
  73. */
  74. protected function getUser()
  75. {
  76. if ($this->_user === null) {
  77. $this->_user = User::findByUsername($this->username);
  78. }
  79. return $this->_user;
  80. }
  81. }