LoginForm.php 7.5 KB

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