LoginForm.php 5.6 KB

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