LoginForm.php 6.7 KB

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