You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.9 KiB

8 months ago
  1. <?php
  2. namespace app\models;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * LoginForm is the model behind the login form.
  7. *
  8. * @property-read User|null $user
  9. *
  10. */
  11. class LoginForm extends Model
  12. {
  13. public $username;
  14. public $password;
  15. public $rememberMe = true;
  16. private $_user = false;
  17. /**
  18. * @return array the validation rules.
  19. */
  20. public function rules()
  21. {
  22. return [
  23. // username and password are both required
  24. [['username', 'password'], 'required'],
  25. // rememberMe must be a boolean value
  26. ['rememberMe', 'boolean'],
  27. // password is validated by validatePassword()
  28. ['password', 'validatePassword'],
  29. ];
  30. }
  31. /**
  32. * Validates the password.
  33. * This method serves as the inline validation for password.
  34. *
  35. * @param string $attribute the attribute currently being validated
  36. * @param array $params the additional name-value pairs given in the rule
  37. */
  38. public function validatePassword($attribute, $params)
  39. {
  40. if (!$this->hasErrors()) {
  41. $user = $this->getUser();
  42. if (!$user || !$user->validatePassword($this->password)) {
  43. $this->addError($attribute, 'Incorrect username or password.');
  44. }
  45. }
  46. }
  47. /**
  48. * Logs in a user using the provided username and password.
  49. * @return bool whether the user is logged in successfully
  50. */
  51. public function login()
  52. {
  53. if ($this->validate()) {
  54. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
  55. }
  56. return false;
  57. }
  58. /**
  59. * Finds user by [[username]]
  60. *
  61. * @return User|null
  62. */
  63. public function getUser()
  64. {
  65. if ($this->_user === false) {
  66. $this->_user = User::findByUsername($this->username);
  67. }
  68. return $this->_user;
  69. }
  70. }