LoginForm.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-03-15 21:16
  7. */
  8. namespace backend\models\form;
  9. use yii;
  10. use yii\base\Model;
  11. use common\models\AdminUser;
  12. /**
  13. * Login form
  14. */
  15. class LoginForm extends Model
  16. {
  17. public $username;
  18. public $password;
  19. public $rememberMe = false;
  20. public $captcha;
  21. private $_user;
  22. /**
  23. * @inheritdoc
  24. */
  25. public function rules()
  26. {
  27. return [
  28. // username and password are both required
  29. [['username', 'password'], 'required'],
  30. // rememberMe must be a boolean value
  31. ['rememberMe', 'boolean'],
  32. // password is validated by validatePassword()
  33. ['password', 'validatePassword'],
  34. [
  35. 'captcha',
  36. 'captcha',
  37. 'captchaAction' => 'site/captcha',
  38. 'message' => yii::t('app', 'Verification code error.')
  39. ],
  40. ];
  41. }
  42. /**
  43. * Validates the password.
  44. * This method serves as the inline validation for password.
  45. *
  46. * @param string $attribute the attribute currently being validated
  47. * @param array $params the additional name-value pairs given in the rule
  48. */
  49. public function validatePassword($attribute, $params)
  50. {
  51. if (! $this->hasErrors()) {
  52. $user = $this->getUser();
  53. if (! $user || ! $user->validatePassword($this->password)) {
  54. $this->addError($attribute, yii::t('app', 'Incorrect username or password.'));
  55. }
  56. }
  57. }
  58. /**
  59. * Logs in a user using the provided username and password.
  60. *
  61. * @return boolean whether the user is logged in successfully
  62. */
  63. public function login()
  64. {
  65. if ($this->validate()) {
  66. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  67. } else {
  68. return false;
  69. }
  70. }
  71. /**
  72. * Finds user by [[username]]
  73. *
  74. * @return AdminUser|null
  75. */
  76. protected function getUser()
  77. {
  78. if ($this->_user === null) {
  79. $this->_user = AdminUser::findByUsername($this->username);
  80. }
  81. return $this->_user;
  82. }
  83. /**
  84. * @inheritdoc
  85. */
  86. public function attributeLabels()
  87. {
  88. return [
  89. 'username' => yii::t('app', 'Username'),
  90. 'password' => yii::t('app', 'Password'),
  91. ];
  92. }
  93. }