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.

86 lines
2.0 KiB

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