LoginForm.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 $_users = [];
  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. return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);
  48. } else {
  49. return false;
  50. }
  51. }
  52. /**
  53. * Finds user by username
  54. *
  55. * @param string $username
  56. * @return User|null
  57. */
  58. private function getUserByUsername($username)
  59. {
  60. if (empty($this->_users[$username])) {
  61. $this->_users[$username] = User::findByUsername($username);
  62. }
  63. return $this->_users[$username];
  64. }
  65. }