LoginForm.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. public $code;
  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', 'code'], '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);
  85. }
  86. // 失败写入缓存锁
  87. Yii::$app->redis->incrby('FAIL_NUMS:' . $this->adminName, 1);
  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. Yii::$app->redis->delete('FAIL_NUMS:' . $this->adminName);
  98. }
  99. /**
  100. * 登录
  101. * @return array|bool
  102. * @throws \yii\base\Exception
  103. * @throws \yii\db\Exception
  104. */
  105. public function login(){
  106. if(!$this->validate()){
  107. return false;
  108. }
  109. $transaction = \Yii::$app->db->beginTransaction();
  110. try{
  111. $this->getUser();
  112. if(!$this->_user){
  113. throw new Exception('账号不存在');
  114. }
  115. // 失败次数到达上限次数
  116. $loginFailNums = Yii::$app->redis->get('FAIL_NUMS:' . $this->adminName) ?? 0;
  117. LoggerTool::info('FAIL_NUMS:' . $this->adminName . ': ' . $loginFailNums);
  118. if ($loginFailNums >= 3) {
  119. $this->_updateFailTimes($transaction, '用户名或者密码错误1');
  120. throw new Exception('用户名或者密码错误1');
  121. }
  122. // 校验邮箱验证码
  123. // $codeObj = EmailLog::find()
  124. // ->where('ADMIN_ID=:ADMIN_ID AND EMAIL=:EMAIL',
  125. // [
  126. // ':ADMIN_ID' => $this->_user['ID'],
  127. // ':EMAIL' => $this->_user['EMAIL'],
  128. // ])
  129. // ->orderBy('CREATED_AT DESC')
  130. // ->one()
  131. // ->toArray();
  132. // if (!$codeObj || !$codeObj['CODE'] || $codeObj['CODE'] != $this->code) {
  133. // throw new Exception('邮箱验证码不正确,无法登录');
  134. // }
  135. // if ($codeObj['CREATED_AT'] + 5 * 60 < time()) {
  136. // throw new Exception('验证码已过期, 请重新获取验证码');
  137. // }
  138. if(!$this->_user['IS_ENABLE']){
  139. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  140. throw new Exception('用户名或者密码错误');
  141. }
  142. if (!$this->_user->validatePassword($this->password)) {
  143. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  144. throw new Exception('用户名或者密码错误');
  145. }
  146. //验证IP
  147. $bindIp = trim($this->_user['BIND_IP']);
  148. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  149. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  150. throw new Exception('用户名或者密码错误');
  151. }
  152. //需要修改密码
  153. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  154. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  155. }
  156. $this->_updateSuccessTimes();
  157. $transaction->commit();
  158. AdminLoginLogger::success($this->_user);
  159. // 把用户的登录时间存在操作时间里
  160. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  161. return Yii::$app->user->loginWithUAndP($this->_user);
  162. }catch(\Exception $e){
  163. $transaction->rollBack();
  164. $this->setError($e->getMessage());
  165. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  166. return false;
  167. }
  168. }
  169. /**
  170. * Finds user by [[username]]
  171. *
  172. * @return User|null
  173. */
  174. public function getUser() {
  175. if ($this->_user === null) {
  176. $this->_user = User::findByUsername(strtolower($this->adminName));
  177. }
  178. return $this->_user;
  179. }
  180. }