LoginForm.php 9.4 KB

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