LoginForm.php 7.0 KB

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