LoginForm.php 7.9 KB

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