LoginForm.php 7.6 KB

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