LoginForm.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. <?php
  2. namespace frontendApi\modules\v1\models;
  3. use common\components\Model;
  4. use common\helpers\Date;
  5. use common\libs\LoginIpChecker;
  6. use common\models\UserInfo;
  7. use Yii;
  8. use yii\base\Exception;
  9. use yii\captcha\Captcha;
  10. use common\libs\logging\login\UserLogin as UserLoginLogger;
  11. /**
  12. * Login form
  13. */
  14. class LoginForm extends Model
  15. {
  16. public $userName;
  17. public $password;
  18. public $verifyCode;
  19. public $rememberMe = true;
  20. private $_user;
  21. private $_userInfo;
  22. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  23. const FRONTEND_LOGIN_FAIL_TIMES = 'frontend:loginFail:times_%s';
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function rules()
  28. {
  29. return [
  30. // username and password are both required
  31. [['userName', 'password'], 'required', 'on'=>['login', 'loginVerify']],
  32. [['verifyCode'], 'required', 'on'=>['loginVerify']],
  33. // rememberMe must be a boolean value
  34. ['rememberMe', 'boolean'],
  35. // password is validated by validatePassword()
  36. ['password', 'validatePassword'],
  37. ['verifyCode', 'captcha', 'captchaAction'=>'/v1/site/captcha', 'on'=>['loginVerify']],
  38. ];
  39. }
  40. /**
  41. * Validates the password.
  42. * This method serves as the inline validation for password.
  43. *
  44. * @param string $attribute the attribute currently being validated
  45. * @param array $params the additional name-value pairs given in the rule
  46. */
  47. public function validatePassword($attribute, $params)
  48. {
  49. if (!$this->hasErrors()) {
  50. $user = $this->getUser();
  51. if(!$user){
  52. $this->addError($attribute, '用户名错误');
  53. } else {
  54. // $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$user['ID']]);
  55. // if($userInfo['CLOSE_LOGIN'] == 1){
  56. // $this->addError($attribute, '会员已被禁止登录');
  57. // return ;
  58. // }
  59. }
  60. }
  61. }
  62. /**
  63. * 更新失败次数
  64. * @param $transaction
  65. * @param $returnResult
  66. * @throws \Exception
  67. */
  68. private function _updateFailTimes($transaction,$returnResult){
  69. UserInfo::updateAllCounters([
  70. 'FAIL_NUMS' => 1,
  71. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  72. $transaction->commit();
  73. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  74. Yii::$app->tokenRedis->incr($cacheKey);
  75. if(isset($this->_user)){
  76. UserLoginLogger::fail($this->_userInfo,$returnResult);
  77. }
  78. }
  79. /**
  80. * 更新成功次数
  81. */
  82. private function _updateSuccessTimes(){
  83. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  84. Yii::$app->tokenRedis->del($cacheKey);
  85. UserInfo::updateAllCounters([
  86. 'LOGIN_NUMS' => 1,
  87. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  88. }
  89. /**
  90. * 登录
  91. * @return array|bool
  92. * @throws \yii\base\Exception
  93. * @throws \yii\db\Exception
  94. */
  95. public function login(){
  96. if(!$this->validate()){
  97. return false;
  98. }
  99. $transaction = \Yii::$app->db->beginTransaction();
  100. try{
  101. $this->getUser();
  102. if(!$this->_user){
  103. throw new Exception('账号不存在');
  104. }
  105. if (!$this->_user->validatePassword($this->password)) {
  106. $this->_updateFailTimes($transaction,'用户名或密码错误');
  107. throw new Exception('用户名或密码错误');
  108. }
  109. // 找到会员的基本信息来判断其是否可登录
  110. if(!$this->_user['ALLOW_LOGIN']){
  111. $this->_updateFailTimes($transaction,'会员编号异常');
  112. throw new Exception('会员编号异常');
  113. }
  114. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  115. $this->_updateFailTimes($transaction,'会员未激活');
  116. throw new Exception('会员未激活');
  117. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  118. $this->_updateFailTimes($transaction,'会员已被注销');
  119. throw new Exception('会员已被注销');
  120. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  121. $this->_updateFailTimes($transaction,'会员已被列入黑名单');
  122. throw new Exception('会员已被列入黑名单');
  123. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  124. $this->_updateFailTimes($transaction,'会员已被永久关停');
  125. throw new Exception('会员已被永久关停');
  126. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  127. $this->_updateFailTimes($transaction,'会员部分功能关闭,无法登录');
  128. throw new Exception('会员部分功能关闭,无法登录');
  129. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  130. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  131. }
  132. //验证IP
  133. /*$bindIp = trim($this->_user['BIND_IP']);
  134. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  135. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  136. throw new Exception('登录IP与此账号绑定的IP不符'.$bindIp);
  137. }*/
  138. //更新clientid
  139. $clientId = Yii::$app->request->post('clientid');
  140. if( $clientId ) {
  141. $update = [
  142. 'BONUS_APP_CLIENT_ID' => $clientId,
  143. ];
  144. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  145. $this->_updateFailTimes($transaction, '会员APP设备信息更新失败');
  146. throw new Exception('会员APP设备信息更新失败');
  147. }
  148. }
  149. $this->_updateSuccessTimes();
  150. $transaction->commit();
  151. UserLoginLogger::success($this->_userInfo);
  152. // 把用户的登录时间存在操作时间里
  153. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  154. return Yii::$app->user->loginWithUAndP($this->_user);
  155. }catch(\Exception $e){
  156. $transaction->rollBack();
  157. $this->setError($e->getMessage());
  158. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  159. return false;
  160. }
  161. }
  162. /**
  163. * Finds user by [[username]]
  164. *
  165. * @return User|null
  166. */
  167. public function getUser() {
  168. if ($this->_user === null) {
  169. $this->_user = User::findByUsername($this->userName);
  170. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  171. }
  172. return $this->_user;
  173. }
  174. /**
  175. * 登录是否需要验证
  176. * @return bool
  177. */
  178. public function isLoginVerify() {
  179. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  180. $times = Yii::$app->tokenRedis->get($cacheKey);
  181. return $times && $times >= 3;
  182. }
  183. }