LoginForm.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * Validates the password.
  30. * This method serves as the inline validation for password.
  31. *
  32. * @param string $attribute the attribute currently being validated
  33. * @param array $params the additional name-value pairs given in the rule
  34. */
  35. public function validatePassword($attribute, $params)
  36. {
  37. if (!$this->hasErrors()) {
  38. $user = $this->getUser();
  39. if (!$user || !$user->validatePassword($this->password)) {
  40. $this->addError($attribute, 'Incorrect username or password.');
  41. }
  42. }
  43. }
  44. /**
  45. * Logs in a user using the provided username and password.
  46. *
  47. * @return bool whether the user is logged in successfully
  48. */
  49. public function login()
  50. {
  51. if ($this->validate()) {
  52. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  53. }
  54. return false;
  55. }
  56. /**
  57. * Finds user by [[username]]
  58. *
  59. * @return User|null
  60. */
  61. protected function getUser()
  62. {
  63. if ($this->_user === null) {
  64. $this->_user = User::findByUsername($this->username);
  65. }
  66. return $this->_user;
  67. }
  68. }