LoginForm.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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;
  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. // password is validated by validatePassword()
  23. ['password', 'validatePassword'],
  24. // rememberMe must be a boolean value
  25. ['rememberMe', 'boolean'],
  26. ];
  27. }
  28. /**
  29. * Validates the password.
  30. * This method serves as the inline validation for password.
  31. */
  32. public function validatePassword()
  33. {
  34. $user = $this->getUserByUsername($this->username);
  35. if (!$user || !$user->validatePassword($this->password)) {
  36. $this->addError('password', 'Incorrect username or password.');
  37. }
  38. }
  39. /**
  40. * Logs in a user using the provided username and password.
  41. * @return boolean whether the user is logged in successfully
  42. */
  43. public function login()
  44. {
  45. if ($this->validate()) {
  46. $user = $this->getUserByUsername($this->username);
  47. Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. /**
  54. * Finds user by username
  55. *
  56. * @param string $username
  57. * @return User|null
  58. */
  59. private function getUserByUsername($username)
  60. {
  61. if ($this->_user === null) {
  62. $this->_user = User::findByUsername($username);
  63. }
  64. return $this->_user;
  65. }
  66. }