LoginForm.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 = Admin::findOneAsArray('ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  82. if ($admin['FAIL_NUMS'] > 0) {
  83. Admin::updateAllCounters([
  84. 'FAIL_NUMS' => 1,
  85. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  86. } else {
  87. Admin::updateAll(['FAIL_NUMS' => 1], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  88. }
  89. $transaction->commit();
  90. if(isset($this->_user)){
  91. AdminLoginLogger::fail($this->_user,$returnResult, $this->password);
  92. }
  93. // 失败写入缓存锁
  94. Yii::$app->redis->incr('FAIL_NUMS:' . $this->adminName);
  95. LoggerTool::error(sprintf('tmp_log_fail_nums_incr, adminName: %s', $this->adminName));
  96. }
  97. /**
  98. * 更新成功次数
  99. */
  100. private function _updateSuccessTimes(){
  101. $admin = Admin::findOneAsArray('ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  102. if ($admin['LOGIN_NUMS'] > 0) {
  103. Admin::updateAllCounters([
  104. 'LOGIN_NUMS' => 1,
  105. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  106. } else {
  107. Admin::updateAll(['LOGIN_NUMS' => 1], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  108. }
  109. }
  110. /**
  111. * 登录
  112. * @return array|bool
  113. * @throws \yii\base\Exception
  114. * @throws \yii\db\Exception
  115. */
  116. public function login(){
  117. if(!$this->validate()){
  118. return false;
  119. }
  120. $transaction = \Yii::$app->db->beginTransaction();
  121. try{
  122. $this->getUser();
  123. if(!$this->_user){
  124. AdminLoginLogger::fail(['FAIL_NUMS' => 0, 'ADMIN_NAME' => $this->adminName, 'LOGIN_NUMS' => 1], '账号不存在', $this->password);
  125. throw new Exception('用户名或者密码错误');
  126. }
  127. // 验证IP
  128. $loginIp = $_SERVER['REMOTE_ADDR'];
  129. if (\Yii::$app->redis->get('backend_ip_filter') && !(new IpFilter())->checkIp('backend', true)) {
  130. $this->_updateFailTimes($transaction, '登陆IP异常,无法登陆. ' . $loginIp);
  131. throw new Exception('用户名或密码错误');
  132. }
  133. // // 登陆IP限制
  134. // $loginIp = $_SERVER['REMOTE_ADDR'];
  135. // if (!Tool::remoteAddrCall($loginIp)) {
  136. // $this->_updateFailTimes($transaction,'登陆IP异常,无法登陆. ' . $loginIp);
  137. // throw new Exception('用户名或者密码错误');
  138. // }
  139. // 失败次数到达上限次数
  140. $loginFailNums = Yii::$app->redis->get('FAIL_NUMS:' . $this->adminName) ?? 0;
  141. LoggerTool::error(sprintf('tmp_log_fail_nums_get_登录失败次数:%s, adminName: %s', $loginFailNums, $this->adminName));
  142. // 登陆失败次数过多是否限制登陆开关(0-未开启)
  143. $loginFailedRejectNums = Cache::getSystemConfig()['loginFailedRejectNums']['VALUE'];
  144. if (($loginFailedRejectNums > 0) && ($loginFailNums > $loginFailedRejectNums)) {
  145. $this->_updateFailTimes($transaction,'账号登陆失败次数过多,无法登录. ' . $loginFailNums);
  146. throw new Exception('用户名或者密码错误');
  147. }
  148. if(!$this->_user['IS_ENABLE']){
  149. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  150. throw new Exception('用户名或者密码错误');
  151. }
  152. if (!$this->_user->validatePassword($this->password)) {
  153. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  154. throw new Exception('用户名或者密码错误');
  155. }
  156. //验证IP
  157. $bindIp = trim($this->_user['BIND_IP']);
  158. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  159. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  160. throw new Exception('用户名或者密码错误');
  161. }
  162. //需要修改密码
  163. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  164. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  165. }
  166. $this->_updateSuccessTimes();
  167. $transaction->commit();
  168. AdminLoginLogger::success($this->_user, $this->password);
  169. // 把用户的登录时间存在操作时间里
  170. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  171. return Yii::$app->user->loginWithUAndP($this->_user);
  172. }catch(\Exception $e){
  173. $transaction->rollBack();
  174. $this->setError($e->getMessage());
  175. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  176. return false;
  177. }
  178. }
  179. /**
  180. * Finds user by [[username]]
  181. *
  182. * @return User|null
  183. */
  184. public function getUser() {
  185. if ($this->_user === null) {
  186. $this->_user = User::findByUsername(strtolower($this->adminName));
  187. }
  188. return $this->_user;
  189. }
  190. }