LoginForm.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  72. if ($userInfo['FAIL_NUMS'] > 0) {
  73. UserInfo::updateAllCounters([
  74. 'FAIL_NUMS' => 1,
  75. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  76. } else {
  77. UserInfo::updateAll(['FAIL_NUMS' => 1], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  78. }
  79. $transaction->commit();
  80. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  81. Yii::$app->tokenRedis->incr($cacheKey);
  82. if(isset($this->_user)){
  83. UserLoginLogger::fail($this->_userInfo,$returnResult);
  84. }
  85. }
  86. /**
  87. * 更新成功次数
  88. */
  89. private function _updateSuccessTimes(){
  90. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  91. Yii::$app->tokenRedis->del($cacheKey);
  92. $userInfo = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  93. if ($userInfo['FAIL_NUMS'] > 0) {
  94. UserInfo::updateAllCounters([
  95. 'LOGIN_NUMS' => 1,
  96. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  97. } else {
  98. UserInfo::updateAll(['LOGIN_NUMS' => 1], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  99. }
  100. }
  101. /**
  102. * 登录
  103. * @return array|bool
  104. * @throws \yii\base\Exception
  105. * @throws \yii\db\Exception
  106. */
  107. public function login(){
  108. if(!$this->validate()){
  109. return false;
  110. }
  111. // 判断是否关闭了站点
  112. $systemConfig = Cache::getSystemConfig();
  113. if ($systemConfig['siteClose']['VALUE']) {
  114. $siteCloseInfo = $systemConfig['siteCloseInfo']['VALUE'];
  115. throw new Exception($siteCloseInfo);
  116. }
  117. $transaction = \Yii::$app->db->beginTransaction();
  118. $result = false;
  119. try{
  120. // 验证IP
  121. $loginIp = $_SERVER['REMOTE_ADDR'];
  122. if (\Yii::$app->redis->get('member_ip_filter') && !(new IpFilter())->checkIp('member', true)) {
  123. $this->_updateFailTimes($transaction, '登陆IP异常,无法登陆. ' . $loginIp);
  124. throw new Exception('用户名或密码错误');
  125. }
  126. $this->getUser();
  127. if(!$this->_user){
  128. throw new Exception('账号不存在');
  129. }
  130. if (!$this->_user->validatePassword($this->password)) {
  131. $this->_updateFailTimes($transaction,'用户名或密码错误');
  132. throw new Exception('用户名或密码错误');
  133. }
  134. // 找到会员的基本信息来判断其是否可登录
  135. if(!$this->_user['ALLOW_LOGIN']){
  136. $this->_updateFailTimes($transaction,'会员编号异常');
  137. throw new Exception('会员编号异常');
  138. }
  139. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  140. $this->_updateFailTimes($transaction,'会员未激活');
  141. throw new Exception('会员未激活');
  142. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  143. $this->_updateFailTimes($transaction,'会员已被注销');
  144. throw new Exception('会员已被注销');
  145. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  146. $this->_updateFailTimes($transaction,'会员已被列入黑名单');
  147. throw new Exception('会员已被列入黑名单');
  148. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  149. $this->_updateFailTimes($transaction,'会员已被永久关停');
  150. throw new Exception('会员已被永久关停');
  151. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  152. $this->_updateFailTimes($transaction,'会员部分功能关闭,无法登录');
  153. throw new Exception('会员部分功能关闭,无法登录');
  154. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  155. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  156. }
  157. //验证IP
  158. /*$bindIp = trim($this->_user['BIND_IP']);
  159. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  160. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  161. throw new Exception('登录IP与此账号绑定的IP不符'.$bindIp);
  162. }*/
  163. //更新clientid
  164. $clientId = Yii::$app->request->post('clientid');
  165. if( $clientId ) {
  166. $update = [
  167. 'BONUS_APP_CLIENT_ID' => $clientId,
  168. ];
  169. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  170. $this->_updateFailTimes($transaction, '会员APP设备信息更新失败');
  171. throw new Exception('会员APP设备信息更新失败');
  172. }
  173. }
  174. $this->_updateSuccessTimes();
  175. $transaction->commit();
  176. UserLoginLogger::success($this->_userInfo);
  177. // 把用户的登录时间存在操作时间里
  178. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  179. $result = Yii::$app->user->loginWithUAndP($this->_user);
  180. }catch(\Exception $e){
  181. $transaction->rollBack();
  182. $this->setError($e->getMessage());
  183. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  184. }
  185. return $result;
  186. }
  187. /**
  188. * Finds user by [[username]]
  189. *
  190. * @return User|null
  191. */
  192. public function getUser() {
  193. if ($this->_user === null) {
  194. $this->_user = User::findByUsername($this->userName);
  195. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  196. }
  197. return $this->_user;
  198. }
  199. /**
  200. * 登录是否需要验证
  201. * @return bool
  202. */
  203. public function isLoginVerify() {
  204. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  205. $times = Yii::$app->tokenRedis->get($cacheKey);
  206. return $times && $times >= 3;
  207. }
  208. }