LoginForm.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. namespace frontendApi\modules\v1\models;
  3. use common\components\Model;
  4. use common\components\Redis;
  5. use common\helpers\Date;
  6. use common\libs\LoginIpChecker;
  7. use common\models\BaUser;
  8. use common\models\BaUserInfo;
  9. use common\models\UserInfo;
  10. use ReflectionProperty;
  11. use Yii;
  12. use yii\base\Exception;
  13. use yii\captcha\Captcha;
  14. use common\libs\logging\login\UserLogin as UserLoginLogger;
  15. use \frontendApi\modules\v1\models\brand\User as Brand;
  16. /**
  17. * Login form
  18. */
  19. class LoginForm extends Model
  20. {
  21. public $userName;
  22. public $password;
  23. public $verifyCode;
  24. public $rememberMe = true;
  25. public $version;
  26. private $_user;
  27. private $_userInfo;
  28. private $_whetherBA;
  29. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  30. const FRONTEND_LOGIN_FAIL_TIMES = 'frontend:loginFail:times_%s';
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function rules()
  35. {
  36. return [
  37. // username and password are both required
  38. [['userName', 'password'], 'required', 'on'=>['login', 'loginVerify']],
  39. [['verifyCode'], 'required', 'on'=>['loginVerify']],
  40. // rememberMe must be a boolean value
  41. ['rememberMe', 'boolean'],
  42. // password is validated by validatePassword()
  43. ['password', 'validatePassword'],
  44. ['verifyCode', 'captcha', 'captchaAction'=>'/v1/site/captcha', 'on'=>['loginVerify']],
  45. ];
  46. }
  47. /**
  48. * Validates the password.
  49. * This method serves as the inline validation for password.
  50. *
  51. * @param string $attribute the attribute currently being validated
  52. * @param array $params the additional name-value pairs given in the rule
  53. */
  54. public function validatePassword($attribute, $params)
  55. {
  56. if (!$this->hasErrors()) {
  57. $user = $this->getUser();
  58. if(!$user){
  59. $this->addError($attribute, 'Member name error');// 用户名错误
  60. } else {
  61. // $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$user['ID']]);
  62. // if($userInfo['CLOSE_LOGIN'] == 1){
  63. // $this->addError($attribute, '会员已被禁止登录');
  64. // return ;
  65. // }
  66. }
  67. }
  68. }
  69. /**
  70. * 更新失败次数
  71. * @param $transaction
  72. * @param $returnResult
  73. * @throws \Exception
  74. */
  75. private function _updateFailTimes($transaction,$returnResult){
  76. $userInfo = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  77. if ($userInfo['FAIL_NUMS'] > 0) {
  78. UserInfo::updateAllCounters([
  79. 'FAIL_NUMS' => 1,
  80. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  81. } else {
  82. UserInfo::updateAll(['FAIL_NUMS' => 1], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  83. }
  84. $transaction->commit();
  85. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  86. $redisKey = Redis::key($cacheKey);
  87. Yii::$app->tokenRedis->incr($redisKey);
  88. if(isset($this->_user)){
  89. UserLoginLogger::fail($this->_userInfo,$returnResult);
  90. }
  91. }
  92. /**
  93. * 更新成功次数
  94. */
  95. private function _updateSuccessTimes(){
  96. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  97. $redisKey = Redis::key($cacheKey);
  98. Yii::$app->tokenRedis->del($redisKey);
  99. $userInfo = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  100. if ($userInfo['FAIL_NUMS'] > 0) {
  101. UserInfo::updateAllCounters([
  102. 'LOGIN_NUMS' => 1,
  103. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  104. } else {
  105. UserInfo::updateAll(['LOGIN_NUMS' => 1], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  106. }
  107. }
  108. /**
  109. * 登录
  110. * @return array|bool
  111. * @throws \yii\base\Exception
  112. * @throws \yii\db\Exception
  113. */
  114. public function login(){
  115. if(!$this->validate()){
  116. return false;
  117. }
  118. $transaction = \Yii::$app->db->beginTransaction();
  119. try{
  120. $this->getUser();
  121. if(!$this->_user){
  122. throw new Exception(Yii::t('app', 'accountDoesNotExist'));
  123. }
  124. if (!$this->_user->validatePassword($this->password)) {
  125. $this->_updateFailTimes($transaction,Yii::t('app', 'memberNameOrPasswordIncorrect'));
  126. throw new Exception(Yii::t('app', 'memberNameOrPasswordIncorrect'));
  127. }
  128. // 找到会员的基本信息来判断其是否可登录
  129. if(!$this->_user['ALLOW_LOGIN']){
  130. $this->_updateFailTimes($transaction,Yii::t('app', 'abnormalMemberCode'));
  131. throw new Exception(Yii::t('app', 'abnormalMemberCode'));
  132. }
  133. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  134. $this->_updateFailTimes($transaction,Yii::t('app', 'memberNotActivated'));
  135. throw new Exception(Yii::t('app', 'memberNotActivated'));
  136. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  137. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenCancelled'));
  138. throw new Exception(Yii::t('app', 'memberHasBeenCancelled'));
  139. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  140. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenBlacklisted'));
  141. throw new Exception(Yii::t('app', 'memberHasBeenBlacklisted'));
  142. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  143. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenPermanentlySuspended'));
  144. throw new Exception(Yii::t('app', 'memberHasBeenPermanentlySuspended'));
  145. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  146. $this->_updateFailTimes($transaction,Yii::t('app', 'memberPartOfFunctionClosed'));
  147. throw new Exception(Yii::t('app', 'memberPartOfFunctionClosed'));
  148. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  149. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  150. }
  151. //验证IP
  152. /*$bindIp = trim($this->_user['BIND_IP']);
  153. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  154. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  155. throw new Exception('登录IP与此账号绑定的IP不符'.$bindIp);
  156. }*/
  157. //更新clientid
  158. $clientId = Yii::$app->request->post('clientid');
  159. if( $clientId ) {
  160. $update = [
  161. 'BONUS_APP_CLIENT_ID' => $clientId,
  162. ];
  163. // if (!$this->_whetherBA) {
  164. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  165. $this->_updateFailTimes($transaction, Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  166. throw new Exception(Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  167. }
  168. // } else {
  169. // if (!BaUser::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  170. // $this->_updateFailTimes($transaction, Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  171. // throw new Exception(Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  172. // }
  173. // }
  174. }
  175. $this->_updateSuccessTimes();
  176. $transaction->commit();
  177. UserLoginLogger::success($this->_userInfo, $this->version);
  178. // 把用户的登录时间存在操作时间里,使用Redis::key方法加密
  179. $redisKey = Redis::key('user:timeOut');
  180. Yii::$app->tokenRedis->hset($redisKey, $this->_userInfo['USER_ID'], time());
  181. // if (!$this->_whetherBA) {
  182. return Yii::$app->user->loginWithUAndP($this->_user);
  183. // } else {
  184. // return Yii::$app->brand->loginWithUAndP($this->_user);
  185. // }
  186. }catch(\Exception $e){
  187. $transaction->rollBack();
  188. // $this->setError($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  189. throw new Exception($e->getMessage());
  190. }
  191. }
  192. /**
  193. * Finds user by [[username]]
  194. *
  195. * @return User|null
  196. */
  197. public function getUser() {
  198. if ($this->_user === null) {
  199. $this->_user = User::findByUsername($this->userName);
  200. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  201. if (!$this->_user || !$this->_userInfo) {
  202. $this->_user = Brand::findByUsername($this->userName);
  203. $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
  204. // 是否BA会员
  205. $this->_whetherBA = $this->_user && $this->_userInfo;
  206. }
  207. }
  208. return $this->_user;
  209. }
  210. /**
  211. * 登录是否需要验证
  212. * @return bool
  213. */
  214. public function isLoginVerify() {
  215. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  216. $redisKey = Redis::key($cacheKey);
  217. $times = Yii::$app->tokenRedis->get($redisKey);
  218. return $times && $times >= 3;
  219. }
  220. }