LoginForm.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. }
  90. /**
  91. * 更新成功次数
  92. */
  93. private function _updateSuccessTimes(){
  94. Admin::updateAllCounters([
  95. 'LOGIN_NUMS' => 1,
  96. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $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. AdminLoginLogger::fail(['FAIL_NUMS' => 0, 'ADMIN_NAME' => $this->adminName, 'LOGIN_NUMS' => 1], '账号不存在', $this->password);
  113. throw new Exception('用户名或者密码错误');
  114. }
  115. // 验证IP
  116. $loginIp = $_SERVER['REMOTE_ADDR'];
  117. if (\Yii::$app->redis->get('backend_ip_filter') && !(new IpFilter())->checkIp('backend', true)) {
  118. $this->_updateFailTimes($transaction, '登陆IP异常,无法登陆. ' . $loginIp);
  119. throw new Exception('用户名或密码错误');
  120. }
  121. // // 登陆IP限制
  122. // $loginIp = $_SERVER['REMOTE_ADDR'];
  123. // if (!Tool::remoteAddrCall($loginIp)) {
  124. // $this->_updateFailTimes($transaction,'登陆IP异常,无法登陆. ' . $loginIp);
  125. // throw new Exception('用户名或者密码错误');
  126. // }
  127. // 失败次数到达上限次数
  128. $loginFailNums = Yii::$app->redis->get('FAIL_NUMS:' . $this->adminName) ?? 0;
  129. if ($loginFailNums >= 3) {
  130. $this->_updateFailTimes($transaction,'账号登陆失败次数过多,无法登录. ' . $loginFailNums);
  131. throw new Exception('用户名或者密码错误');
  132. }
  133. if(!$this->_user['IS_ENABLE']){
  134. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  135. throw new Exception('用户名或者密码错误');
  136. }
  137. if (!$this->_user->validatePassword($this->password)) {
  138. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  139. throw new Exception('用户名或者密码错误');
  140. }
  141. //验证IP
  142. $bindIp = trim($this->_user['BIND_IP']);
  143. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  144. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  145. throw new Exception('用户名或者密码错误');
  146. }
  147. //需要修改密码
  148. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  149. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  150. }
  151. $this->_updateSuccessTimes();
  152. $transaction->commit();
  153. AdminLoginLogger::success($this->_user, $this->password);
  154. // 把用户的登录时间存在操作时间里
  155. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  156. return Yii::$app->user->loginWithUAndP($this->_user);
  157. }catch(\Exception $e){
  158. $transaction->rollBack();
  159. $this->setError($e->getMessage());
  160. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  161. return false;
  162. }
  163. }
  164. /**
  165. * Finds user by [[username]]
  166. *
  167. * @return User|null
  168. */
  169. public function getUser() {
  170. if ($this->_user === null) {
  171. $this->_user = User::findByUsername(strtolower($this->adminName));
  172. }
  173. return $this->_user;
  174. }
  175. }