LoginForm.php 5.7 KB

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