LoginForm.php 1.9 KB

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