LoginForm.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. class LoginForm extends Model
  9. {
  10. public $username;
  11. public $password;
  12. public $rememberMe = true;
  13. private $_user = false;
  14. /**
  15. * @return array the validation rules.
  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. public function validatePassword()
  33. {
  34. if (!$this->hasErrors()) {
  35. $user = $this->getUser();
  36. if (!$user || !$user->validatePassword($this->password)) {
  37. $this->addError('password', 'Incorrect username or password.');
  38. }
  39. }
  40. }
  41. /**
  42. * Logs in a user using the provided username and password.
  43. * @return boolean whether the user is logged in successfully
  44. */
  45. public function login()
  46. {
  47. if ($this->validate()) {
  48. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
  49. } else {
  50. return false;
  51. }
  52. }
  53. /**
  54. * Finds user by [[username]]
  55. *
  56. * @return User|null
  57. */
  58. public function getUser()
  59. {
  60. if ($this->_user === false) {
  61. $this->_user = User::findByUsername($this->username);
  62. }
  63. return $this->_user;
  64. }
  65. }