LoginForm.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. /**
  14. * @return array the validation rules.
  15. */
  16. public function rules()
  17. {
  18. return [
  19. // username and password are both required
  20. [['username', 'password'], 'required'],
  21. // password is validated by validatePassword()
  22. ['password', 'validatePassword'],
  23. // rememberMe must be a boolean value
  24. ['rememberMe', 'boolean'],
  25. ];
  26. }
  27. /**
  28. * Validates the password.
  29. * This method serves as the inline validation for password.
  30. */
  31. public function validatePassword()
  32. {
  33. $user = User::findByUsername($this->username);
  34. if (!$user || !$user->validatePassword($this->password)) {
  35. $this->addError('password', 'Incorrect username or password.');
  36. }
  37. }
  38. /**
  39. * Logs in a user using the provided username and password.
  40. * @return boolean whether the user is logged in successfully
  41. */
  42. public function login()
  43. {
  44. if ($this->validate()) {
  45. $user = User::findByUsername($this->username);
  46. Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);
  47. return true;
  48. } else {
  49. return false;
  50. }
  51. }
  52. }