LoginForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace common\modules\user\models;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * Login form.
  7. */
  8. class LoginForm extends Model
  9. {
  10. public $username;
  11. public $password;
  12. public $rememberMe = true;
  13. public $verifyCode;
  14. private $_user;
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public function rules()
  19. {
  20. return [
  21. // username and password are both required
  22. [['username', 'password'], 'required'],
  23. // rememberMe must be a boolean value
  24. ['rememberMe', 'boolean'],
  25. // password is validated by validatePassword()
  26. ['password', 'validatePassword'],
  27. ];
  28. }
  29. public function attributeLabels()
  30. {
  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. {
  46. if (!$this->hasErrors()) {
  47. $user = $this->getUser();
  48. if (!$user || !$user->validatePassword($this->password)) {
  49. $this->addError($attribute, '帐号密码错误');
  50. }
  51. }
  52. }
  53. /**
  54. * Logs in a user using the provided username and password.
  55. *
  56. * @return bool whether the user is logged in successfully
  57. */
  58. public function login()
  59. {
  60. if ($this->validate()) {
  61. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  62. } else {
  63. return false;
  64. }
  65. }
  66. public function loginAdmin()
  67. {
  68. if ($this->validate()) {
  69. if ($this->getUser()->getIsAdmin()) {
  70. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  71. } else {
  72. $this->addError('username', '无权登录');
  73. return false;
  74. }
  75. } else {
  76. return false;
  77. }
  78. }
  79. /**
  80. * Finds user by [[username]].
  81. *
  82. * @return User|null
  83. */
  84. protected function getUser()
  85. {
  86. if ($this->_user === null) {
  87. $this->_user = User::findByUsernameOrEmailTel($this->username);
  88. }
  89. return $this->_user;
  90. }
  91. }