LoginForm.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. Yii::$app->tokenRedis->incr($cacheKey);
  86. if(isset($this->_user)){
  87. UserLoginLogger::fail($this->_userInfo,$returnResult);
  88. }
  89. }
  90. /**
  91. * 更新成功次数
  92. */
  93. private function _updateSuccessTimes(){
  94. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  95. Yii::$app->tokenRedis->del($cacheKey);
  96. $userInfo = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  97. if ($userInfo['FAIL_NUMS'] > 0) {
  98. UserInfo::updateAllCounters([
  99. 'LOGIN_NUMS' => 1,
  100. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  101. } else {
  102. UserInfo::updateAll(['LOGIN_NUMS' => 1], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  103. }
  104. }
  105. /**
  106. * 登录
  107. * @return array|bool
  108. * @throws \yii\base\Exception
  109. * @throws \yii\db\Exception
  110. */
  111. public function login(){
  112. if(!$this->validate()){
  113. return false;
  114. }
  115. $transaction = \Yii::$app->db->beginTransaction();
  116. try{
  117. $this->getUser();
  118. if(!$this->_user){
  119. throw new Exception(Yii::t('app', 'accountDoesNotExist'));
  120. }
  121. if (!$this->_user->validatePassword($this->password)) {
  122. $this->_updateFailTimes($transaction,Yii::t('app', 'memberNameOrPasswordIncorrect'));
  123. throw new Exception(Yii::t('app', 'memberNameOrPasswordIncorrect'));
  124. }
  125. // 找到会员的基本信息来判断其是否可登录
  126. if(!$this->_user['ALLOW_LOGIN']){
  127. $this->_updateFailTimes($transaction,Yii::t('app', 'abnormalMemberCode'));
  128. throw new Exception(Yii::t('app', 'abnormalMemberCode'));
  129. }
  130. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  131. $this->_updateFailTimes($transaction,Yii::t('app', 'memberNotActivated'));
  132. throw new Exception(Yii::t('app', 'memberNotActivated'));
  133. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  134. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenCancelled'));
  135. throw new Exception(Yii::t('app', 'memberHasBeenCancelled'));
  136. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  137. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenBlacklisted'));
  138. throw new Exception(Yii::t('app', 'memberHasBeenBlacklisted'));
  139. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  140. $this->_updateFailTimes($transaction,Yii::t('app', 'memberHasBeenPermanentlySuspended'));
  141. throw new Exception(Yii::t('app', 'memberHasBeenPermanentlySuspended'));
  142. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  143. $this->_updateFailTimes($transaction,Yii::t('app', 'memberPartOfFunctionClosed'));
  144. throw new Exception(Yii::t('app', 'memberPartOfFunctionClosed'));
  145. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  146. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  147. }
  148. //验证IP
  149. /*$bindIp = trim($this->_user['BIND_IP']);
  150. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  151. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  152. throw new Exception('登录IP与此账号绑定的IP不符'.$bindIp);
  153. }*/
  154. //更新clientid
  155. $clientId = Yii::$app->request->post('clientid');
  156. if( $clientId ) {
  157. $update = [
  158. 'BONUS_APP_CLIENT_ID' => $clientId,
  159. ];
  160. // if (!$this->_whetherBA) {
  161. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  162. $this->_updateFailTimes($transaction, Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  163. throw new Exception(Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  164. }
  165. // } else {
  166. // if (!BaUser::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  167. // $this->_updateFailTimes($transaction, Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  168. // throw new Exception(Yii::t('app', 'memberAppDeviceInformationUpdateFailed'));
  169. // }
  170. // }
  171. }
  172. $this->_updateSuccessTimes();
  173. $transaction->commit();
  174. UserLoginLogger::success($this->_userInfo, $this->version);
  175. // 把用户的登录时间存在操作时间里
  176. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  177. // if (!$this->_whetherBA) {
  178. return Yii::$app->user->loginWithUAndP($this->_user);
  179. // } else {
  180. // return Yii::$app->brand->loginWithUAndP($this->_user);
  181. // }
  182. }catch(\Exception $e){
  183. $transaction->rollBack();
  184. // $this->setError($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  185. throw new Exception($e->getMessage());
  186. }
  187. }
  188. /**
  189. * Finds user by [[username]]
  190. *
  191. * @return User|null
  192. */
  193. public function getUser() {
  194. if ($this->_user === null) {
  195. $this->_user = User::findByUsername($this->userName);
  196. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  197. if (!$this->_user || !$this->_userInfo) {
  198. $this->_user = Brand::findByUsername($this->userName);
  199. $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
  200. // 是否BA会员
  201. $this->_whetherBA = $this->_user && $this->_userInfo;
  202. }
  203. }
  204. return $this->_user;
  205. }
  206. /**
  207. * 登录是否需要验证
  208. * @return bool
  209. */
  210. public function isLoginVerify() {
  211. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  212. $times = Yii::$app->tokenRedis->get($cacheKey);
  213. return $times && $times >= 3;
  214. }
  215. }