LoginForm.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. $result = false;
  109. try{
  110. // 验证IP
  111. if (\Yii::$app->redis->get('member_ip_filter') && !(new IpFilter())->frontApiCheck('member', true)) {
  112. $this->_updateFailTimes($transaction, '用户名或密码错误!');
  113. throw new Exception('用户名或密码错误');
  114. }
  115. $this->getUser();
  116. if(!$this->_user){
  117. throw new Exception('账号不存在');
  118. }
  119. if (!$this->_user->validatePassword($this->password)) {
  120. $this->_updateFailTimes($transaction,'用户名或密码错误');
  121. throw new Exception('用户名或密码错误');
  122. }
  123. // 找到会员的基本信息来判断其是否可登录
  124. if(!$this->_user['ALLOW_LOGIN']){
  125. $this->_updateFailTimes($transaction,'会员编号异常');
  126. throw new Exception('会员编号异常');
  127. }
  128. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  129. $this->_updateFailTimes($transaction,'会员未激活');
  130. throw new Exception('会员未激活');
  131. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  132. $this->_updateFailTimes($transaction,'会员已被注销');
  133. throw new Exception('会员已被注销');
  134. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  135. $this->_updateFailTimes($transaction,'会员已被列入黑名单');
  136. throw new Exception('会员已被列入黑名单');
  137. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  138. $this->_updateFailTimes($transaction,'会员已被永久关停');
  139. throw new Exception('会员已被永久关停');
  140. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  141. $this->_updateFailTimes($transaction,'会员部分功能关闭,无法登录');
  142. throw new Exception('会员部分功能关闭,无法登录');
  143. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  144. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  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('登录IP与此账号绑定的IP不符'.$bindIp);
  151. }*/
  152. //更新clientid
  153. $clientId = Yii::$app->request->post('clientid');
  154. if( $clientId ) {
  155. $update = [
  156. 'BONUS_APP_CLIENT_ID' => $clientId,
  157. ];
  158. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  159. $this->_updateFailTimes($transaction, '会员APP设备信息更新失败');
  160. throw new Exception('会员APP设备信息更新失败');
  161. }
  162. }
  163. $this->_updateSuccessTimes();
  164. $transaction->commit();
  165. UserLoginLogger::success($this->_userInfo);
  166. // 把用户的登录时间存在操作时间里
  167. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  168. $result = Yii::$app->user->loginWithUAndP($this->_user);
  169. }catch(\Exception $e){
  170. $transaction->rollBack();
  171. $this->setError($e->getMessage());
  172. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  173. }
  174. return $result;
  175. }
  176. /**
  177. * Finds user by [[username]]
  178. *
  179. * @return User|null
  180. */
  181. public function getUser() {
  182. if ($this->_user === null) {
  183. $this->_user = User::findByUsername($this->userName);
  184. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  185. }
  186. return $this->_user;
  187. }
  188. /**
  189. * 登录是否需要验证
  190. * @return bool
  191. */
  192. public function isLoginVerify() {
  193. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  194. $times = Yii::$app->tokenRedis->get($cacheKey);
  195. return $times && $times >= 3;
  196. }
  197. }