LoginForm.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. if (!$this->_whetherBA) {
  76. UserInfo::updateAllCounters([
  77. 'FAIL_NUMS' => 1,
  78. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  79. } else {
  80. BaUserInfo::updateAllCounters([
  81. 'FAIL_NUMS' => 1,
  82. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  83. }
  84. $transaction->commit();
  85. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  86. Yii::$app->tokenRedis->incr($cacheKey);
  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. Yii::$app->tokenRedis->del($cacheKey);
  97. if (!$this->_whetherBA) {
  98. UserInfo::updateAllCounters([
  99. 'LOGIN_NUMS' => 1,
  100. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  101. } else {
  102. BaUserInfo::updateAllCounters([
  103. 'LOGIN_NUMS' => 1,
  104. ], '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. // 把用户的登录时间存在操作时间里
  178. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  179. if (!$this->_whetherBA) {
  180. return Yii::$app->user->loginWithUAndP($this->_user);
  181. } else {
  182. return Yii::$app->brand->loginWithUAndP($this->_user);
  183. }
  184. }catch(\Exception $e){
  185. $transaction->rollBack();
  186. // $this->setError($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  187. throw new Exception($e->getMessage());
  188. }
  189. }
  190. /**
  191. * Finds user by [[username]]
  192. *
  193. * @return User|null
  194. */
  195. public function getUser() {
  196. if ($this->_user === null) {
  197. $this->_user = User::findByUsername($this->userName);
  198. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  199. if (!$this->_user || !$this->_userInfo) {
  200. $this->_user = Brand::findByUsername($this->userName);
  201. $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
  202. // 是否BA会员
  203. $this->_whetherBA = $this->_user && $this->_userInfo;
  204. }
  205. }
  206. return $this->_user;
  207. }
  208. /**
  209. * 登录是否需要验证
  210. * @return bool
  211. */
  212. public function isLoginVerify() {
  213. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  214. $times = Yii::$app->tokenRedis->get($cacheKey);
  215. return $times && $times >= 3;
  216. }
  217. }