LoginForm.php 9.7 KB

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