LoginForm.php 5.6 KB

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