LoginForm.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-03-15 21:16
  7. */
  8. namespace frontend\models\form;
  9. use Yii;
  10. use common\models\User;
  11. /**
  12. * Login form
  13. */
  14. class LoginForm extends yii\base\Model
  15. {
  16. public $username;
  17. public $password;
  18. public $rememberMe = true;
  19. private $_user;
  20. /**
  21. * @inheritdoc
  22. */
  23. public function rules()
  24. {
  25. return [
  26. // username and password are both required
  27. [['username', 'password'], 'required'],
  28. // rememberMe must be a boolean value
  29. ['rememberMe', 'boolean'],
  30. // password is validated by validatePassword()
  31. ['password', 'validatePassword'],
  32. ];
  33. }
  34. /**
  35. * @inheritdoc
  36. */
  37. public function attributeLabels()
  38. {
  39. return [
  40. 'username' => yii::t('app', 'Username'),
  41. 'email' => yii::t('app', 'Email'),
  42. 'old_password' => yii::t('app', 'Old Password'),
  43. 'password' => yii::t('app', 'Password'),
  44. 'repassword' => yii::t('app', 'Repeat Password'),
  45. 'avatar' => yii::t('app', 'Avatar'),
  46. 'created_at' => yii::t('app', 'Created At'),
  47. 'updated_at' => yii::t('app', 'Updated At'),
  48. 'rememberMe' => yii::t('frontend', 'Remember Me'),
  49. ];
  50. }
  51. /**
  52. * Validates the password.
  53. * This method serves as the inline validation for password.
  54. *
  55. * @param string $attribute the attribute currently being validated
  56. * @param array $params the additional name-value pairs given in the rule
  57. */
  58. public function validatePassword($attribute, $params)
  59. {
  60. if (! $this->hasErrors()) {
  61. $user = $this->getUser();
  62. if (! $user || ! $user->validatePassword($this->password)) {
  63. $this->addError($attribute, yii::t('app', 'Incorrect username or password.'));
  64. }
  65. }
  66. }
  67. /**
  68. * Logs in a user using the provided username and password.
  69. *
  70. * @return boolean whether the user is logged in successfully
  71. */
  72. public function login()
  73. {
  74. if ($this->validate()) {
  75. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  76. } else {
  77. return false;
  78. }
  79. }
  80. /**
  81. * Finds user by [[username]]
  82. *
  83. * @return User|null
  84. */
  85. protected function getUser()
  86. {
  87. if ($this->_user === null) {
  88. $this->_user = User::findByUsername($this->username);
  89. }
  90. return $this->_user;
  91. }
  92. }