LoginForm.php 6.4 KB

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