LoginForm.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. <?php
  2. namespace backendApi\modules\v1\models;
  3. use common\components\Model;
  4. use common\libs\LoginIpChecker;
  5. use Yii;
  6. use yii\base\Exception;
  7. use yii\captcha\Captcha;
  8. use common\libs\logging\login\AdminLogin as AdminLoginLogger;
  9. /**
  10. * Login form
  11. */
  12. class LoginForm extends Model {
  13. public $adminName;
  14. public $password;
  15. public $verifyCode;
  16. private $_user;
  17. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  18. /**
  19. * @inheritdoc
  20. */
  21. public function attributeLabels()
  22. {
  23. return [
  24. 'adminName' => '登录帐号',
  25. 'password' => '登录密码',
  26. 'verifyCode' => '验证码',
  27. ];
  28. }
  29. /**
  30. * @inheritdoc
  31. */
  32. public function rules() {
  33. return [
  34. // username and password are both required
  35. [['adminName', 'password', 'verifyCode'], 'required'],
  36. // rememberMe must be a boolean value
  37. ['verifyCode', 'captcha', 'captchaAction'=>'/v1/site/captcha'],
  38. // password is validated by validatePassword()
  39. //['password', 'validatePassword'],
  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. if (!$this->hasErrors()) {
  51. $this->getUser();
  52. if(!$this->_user){
  53. $this->addError($attribute, Yii::t('ctx', 'memberDoesNotExist'));
  54. return false;
  55. }
  56. if (!$this->_user->validatePassword($this->password)) {
  57. $this->addError($attribute, Yii::t('ctx', 'nameOrPasswdError'));
  58. return false;
  59. }
  60. //验证IP
  61. $bindIp = trim($this->_user['BIND_IP']);
  62. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  63. $this->addError($attribute, Yii::t('ctx', 'ipBindAccountNumberError'));
  64. return false;
  65. }
  66. return true;
  67. }
  68. return false;
  69. }
  70. /**
  71. * 更新失败次数
  72. * @param $transaction
  73. * @param $returnResult
  74. * @throws \Exception
  75. */
  76. private function _updateFailTimes($transaction,$returnResult){
  77. Admin::updateAllCounters([
  78. 'FAIL_NUMS' => 1,
  79. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  80. $transaction->commit();
  81. if(isset($this->_user)){
  82. AdminLoginLogger::fail($this->_user,$returnResult);
  83. }
  84. }
  85. /**
  86. * 更新成功次数
  87. */
  88. private function _updateSuccessTimes(){
  89. Admin::updateAllCounters([
  90. 'LOGIN_NUMS' => 1,
  91. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  92. }
  93. /**
  94. * 登录
  95. * @return array|bool
  96. * @throws \yii\base\Exception
  97. * @throws \yii\db\Exception
  98. */
  99. public function login(){
  100. if(!$this->validate()){
  101. return false;
  102. }
  103. $transaction = \Yii::$app->db->beginTransaction();
  104. try{
  105. $this->getUser();
  106. if(!$this->_user){
  107. throw new Exception(Yii::t('ctx', 'accountDoesNotExist')); // 账号不存在
  108. }
  109. if(!$this->_user['IS_ENABLE']){
  110. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  111. throw new Exception(Yii::t('ctx', 'accountLockCannotLoggedIn')); // 账号已经被锁定,无法登录
  112. }
  113. if (!$this->_user->validatePassword($this->password)) {
  114. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  115. throw new Exception(Yii::t('ctx', 'nameOrPasswdError')); // 用户名或者密码错误
  116. }
  117. //验证IP
  118. $bindIp = trim($this->_user['BIND_IP']);
  119. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  120. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  121. $exceptionMessage = Yii::t('ctx', 'ipBindAccountNumberError');
  122. throw new Exception($exceptionMessage.$bindIp); // 登录IP与此账号绑定的IP不符
  123. }
  124. //需要修改密码
  125. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  126. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  127. }
  128. $this->_updateSuccessTimes();
  129. $transaction->commit();
  130. AdminLoginLogger::success($this->_user);
  131. // 把用户的登录时间存在操作时间里
  132. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  133. return Yii::$app->user->loginWithUAndP($this->_user);
  134. }catch(\Exception $e){
  135. $transaction->rollBack();
  136. $this->setError($e->getMessage());
  137. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  138. return false;
  139. }
  140. }
  141. /**
  142. * Finds user by [[username]]
  143. *
  144. * @return User|null
  145. */
  146. public function getUser() {
  147. if ($this->_user === null) {
  148. $this->_user = User::findByUsername(strtolower($this->adminName));
  149. }
  150. return $this->_user;
  151. }
  152. }