LoginForm.php 6.1 KB

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