You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.0 KiB

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