LoginForm.php 1.7 KB

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