Drupal investigation

LoginForm.php 1.9KB

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