LoginForm.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. private $_user;
  25. private $_userInfo;
  26. private $_whetherBA;
  27. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  28. const FRONTEND_LOGIN_FAIL_TIMES = 'frontend:loginFail:times_%s';
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function rules()
  33. {
  34. return [
  35. // username and password are both required
  36. [['userName', 'password'], 'required', 'on'=>['login', 'loginVerify']],
  37. [['verifyCode'], 'required', 'on'=>['loginVerify']],
  38. // rememberMe must be a boolean value
  39. ['rememberMe', 'boolean'],
  40. // password is validated by validatePassword()
  41. ['password', 'validatePassword'],
  42. ['verifyCode', 'captcha', 'captchaAction'=>'/v1/site/captcha', 'on'=>['loginVerify']],
  43. ];
  44. }
  45. /**
  46. * Validates the password.
  47. * This method serves as the inline validation for password.
  48. *
  49. * @param string $attribute the attribute currently being validated
  50. * @param array $params the additional name-value pairs given in the rule
  51. */
  52. public function validatePassword($attribute, $params)
  53. {
  54. if (!$this->hasErrors()) {
  55. $user = $this->getUser();
  56. if(!$user){
  57. $this->addError($attribute, 'Member name error');// 用户名错误
  58. } else {
  59. // $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$user['ID']]);
  60. // if($userInfo['CLOSE_LOGIN'] == 1){
  61. // $this->addError($attribute, '会员已被禁止登录');
  62. // return ;
  63. // }
  64. }
  65. }
  66. }
  67. /**
  68. * 更新失败次数
  69. * @param $transaction
  70. * @param $returnResult
  71. * @throws \Exception
  72. */
  73. private function _updateFailTimes($transaction,$returnResult){
  74. if (!$this->_whetherBA) {
  75. UserInfo::updateAllCounters([
  76. 'FAIL_NUMS' => 1,
  77. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  78. } else {
  79. BaUserInfo::updateAllCounters([
  80. 'FAIL_NUMS' => 1,
  81. ], '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. if (!$this->_whetherBA) {
  97. UserInfo::updateAllCounters([
  98. 'LOGIN_NUMS' => 1,
  99. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  100. } else {
  101. BaUserInfo::updateAllCounters([
  102. 'LOGIN_NUMS' => 1,
  103. ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
  104. }
  105. }
  106. /**
  107. * 登录
  108. * @return array|bool
  109. * @throws \yii\base\Exception
  110. * @throws \yii\db\Exception
  111. */
  112. public function login(){
  113. if(!$this->validate()){
  114. return false;
  115. }
  116. $transaction = \Yii::$app->db->beginTransaction();
  117. try{
  118. $this->getUser();
  119. if(!$this->_user){
  120. throw new Exception('The account does not exist'); // 账号不存在
  121. }
  122. if (!$this->_user->validatePassword($this->password)) {
  123. $this->_updateFailTimes($transaction,'The member name or password is incorrect'); // 用户名或密码错误
  124. throw new Exception('The member name or password is incorrect'); // 用户名或密码错误
  125. }
  126. // 找到会员的基本信息来判断其是否可登录
  127. if(!$this->_user['ALLOW_LOGIN']){
  128. $this->_updateFailTimes($transaction,'Abnormal member code'); // 会员编号异常
  129. throw new Exception('Abnormal member code'); // 会员编号异常
  130. }
  131. if($this->_user['STATUS'] == Yii::$app->params['userStatus'][0]['value']){
  132. $this->_updateFailTimes($transaction,'Member not activated'); // 会员未激活
  133. throw new Exception('Member not activated'); // 会员未激活
  134. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][2]['value']){
  135. $this->_updateFailTimes($transaction,'The member has been cancelled'); // 会员已被注销
  136. throw new Exception('The member has been cancelled'); // 会员已被注销
  137. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][3]['value']){
  138. $this->_updateFailTimes($transaction,'The member has been blacklisted'); // 会员已被列入黑名单
  139. throw new Exception('The member has been blacklisted'); // 会员已被列入黑名单
  140. } elseif($this->_user['STATUS'] == Yii::$app->params['userStatus'][9]['value']){
  141. $this->_updateFailTimes($transaction,'The member has been permanently suspended'); // 会员已被永久关停
  142. throw new Exception('The member has been permanently suspended'); // 会员已被永久关停
  143. } elseif($this->_user['PART_FUNC_CLOSED'] == 1){
  144. $this->_updateFailTimes($transaction,'Member part of the function is closed, unable to log in.'); // 会员部分功能关闭,无法登录
  145. throw new Exception('Member part of the function is closed, unable to log in.'); // 会员部分功能关闭,无法登录
  146. } elseif($this->_user['IS_MODIFY_PASSWORD'] == 1){
  147. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  148. }
  149. //验证IP
  150. /*$bindIp = trim($this->_user['BIND_IP']);
  151. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  152. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  153. throw new Exception('登录IP与此账号绑定的IP不符'.$bindIp);
  154. }*/
  155. //更新clientid
  156. $clientId = Yii::$app->request->post('clientid');
  157. if( $clientId ) {
  158. $update = [
  159. 'BONUS_APP_CLIENT_ID' => $clientId,
  160. ];
  161. if (!$this->_whetherBA) {
  162. if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  163. $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
  164. throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
  165. }
  166. } else {
  167. if (!BaUser::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
  168. $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
  169. throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
  170. }
  171. }
  172. }
  173. $this->_updateSuccessTimes();
  174. $transaction->commit();
  175. UserLoginLogger::success($this->_userInfo);
  176. // 把用户的登录时间存在操作时间里
  177. Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
  178. if (!$this->_whetherBA) {
  179. return Yii::$app->user->loginWithUAndP($this->_user);
  180. } else {
  181. return Yii::$app->brand->loginWithUAndP($this->_user);
  182. }
  183. }catch(\Exception $e){
  184. $transaction->rollBack();
  185. $this->setError($e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage());
  186. return false;
  187. }
  188. }
  189. /**
  190. * Finds user by [[username]]
  191. *
  192. * @return User|null
  193. */
  194. public function getUser() {
  195. if ($this->_user === null) {
  196. $this->_user = User::findByUsername($this->userName);
  197. $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
  198. if (!$this->_user || !$this->_userInfo) {
  199. $this->_user = Brand::findByUsername($this->userName);
  200. $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
  201. // 是否BA会员
  202. $this->_whetherBA = $this->_user && $this->_userInfo;
  203. }
  204. }
  205. return $this->_user;
  206. }
  207. /**
  208. * 登录是否需要验证
  209. * @return bool
  210. */
  211. public function isLoginVerify() {
  212. $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
  213. $times = Yii::$app->tokenRedis->get($cacheKey);
  214. return $times && $times >= 3;
  215. }
  216. }