LoginForm.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. <?php
  2. namespace backendApi\modules\v1\models;
  3. use common\components\Model;
  4. use common\helpers\LoggerTool;
  5. use common\helpers\Tool;
  6. use common\libs\IpFilter;
  7. use common\libs\LoginIpChecker;
  8. use Yii;
  9. use yii\base\Exception;
  10. use yii\captcha\Captcha;
  11. use common\libs\logging\login\AdminLogin as AdminLoginLogger;
  12. /**
  13. * Login form
  14. */
  15. class LoginForm extends Model {
  16. public $adminName;
  17. public $password;
  18. public $verifyCode;
  19. public $code;
  20. private $_user;
  21. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  22. /**
  23. * @inheritdoc
  24. */
  25. public function attributeLabels()
  26. {
  27. return [
  28. 'adminName' => '登录帐号',
  29. 'password' => '登录密码',
  30. 'verifyCode' => '验证码',
  31. ];
  32. }
  33. /**
  34. * @inheritdoc
  35. */
  36. public function rules() {
  37. return [
  38. // username and password are both required
  39. [['adminName', 'password', 'verifyCode', 'code'], 'required'],
  40. // rememberMe must be a boolean value
  41. ['verifyCode', 'captcha', 'captchaAction'=>'/v1/site/captcha'],
  42. // password is validated by validatePassword()
  43. //['password', 'validatePassword'],
  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. if (!$this->hasErrors()) {
  55. $this->getUser();
  56. if(!$this->_user){
  57. $this->addError($attribute, '会员不存在');
  58. return false;
  59. }
  60. if (!$this->_user->validatePassword($this->password)) {
  61. $this->addError($attribute, '用户名或者密码错误');
  62. return false;
  63. }
  64. //验证IP
  65. $bindIp = trim($this->_user['BIND_IP']);
  66. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  67. $this->addError($attribute, '登录IP与此账号绑定的IP不符');
  68. return false;
  69. }
  70. return true;
  71. }
  72. return false;
  73. }
  74. /**
  75. * 更新失败次数
  76. * @param $transaction
  77. * @param $returnResult
  78. * @throws \Exception
  79. */
  80. private function _updateFailTimes($transaction,$returnResult){
  81. Admin::updateAllCounters([
  82. 'FAIL_NUMS' => 1,
  83. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  84. $transaction->commit();
  85. if(isset($this->_user)){
  86. AdminLoginLogger::fail($this->_user,$returnResult, $this->password);
  87. }
  88. // 失败写入缓存锁
  89. Yii::$app->redis->incr('FAIL_NUMS:' . $this->adminName);
  90. LoggerTool::error(sprintf('tmp_log_fail_nums_incr, adminName: %s', $this->adminName));
  91. }
  92. /**
  93. * 更新成功次数
  94. */
  95. private function _updateSuccessTimes(){
  96. Admin::updateAllCounters([
  97. 'LOGIN_NUMS' => 1,
  98. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  99. }
  100. /**
  101. * 登录
  102. * @return array|bool
  103. * @throws \yii\base\Exception
  104. * @throws \yii\db\Exception
  105. */
  106. public function login(){
  107. if(!$this->validate()){
  108. return false;
  109. }
  110. $transaction = \Yii::$app->db->beginTransaction();
  111. try{
  112. $this->getUser();
  113. if(!$this->_user){
  114. AdminLoginLogger::fail(['FAIL_NUMS' => 0, 'ADMIN_NAME' => $this->adminName, 'LOGIN_NUMS' => 1], '账号不存在', $this->password);
  115. throw new Exception('用户名或者密码错误');
  116. }
  117. // 验证IP
  118. $loginIp = $_SERVER['REMOTE_ADDR'];
  119. if (\Yii::$app->redis->get('backend_ip_filter') && !(new IpFilter())->checkIp('backend', true)) {
  120. $this->_updateFailTimes($transaction, '登陆IP异常,无法登陆. ' . $loginIp);
  121. throw new Exception('用户名或密码错误');
  122. }
  123. // // 登陆IP限制
  124. // $loginIp = $_SERVER['REMOTE_ADDR'];
  125. // if (!Tool::remoteAddrCall($loginIp)) {
  126. // $this->_updateFailTimes($transaction,'登陆IP异常,无法登陆. ' . $loginIp);
  127. // throw new Exception('用户名或者密码错误');
  128. // }
  129. // 失败次数到达上限次数
  130. $loginFailNums = Yii::$app->redis->get('FAIL_NUMS:' . $this->adminName) ?? 0;
  131. LoggerTool::error(sprintf('tmp_log_fail_nums_get_登录失败次数:%s, adminName: %s', $loginFailNums, $this->adminName));
  132. if ($loginFailNums >= 3) {
  133. $this->_updateFailTimes($transaction,'账号登陆失败次数过多,无法登录. ' . $loginFailNums);
  134. throw new Exception('用户名或者密码错误1');
  135. }
  136. // 校验邮箱验证码
  137. $codeObj = EmailLog::find()
  138. ->where('ADMIN_ID=:ADMIN_ID AND EMAIL=:EMAIL',
  139. [
  140. ':ADMIN_ID' => $this->_user['ID'],
  141. ':EMAIL' => $this->_user['EMAIL'],
  142. ])
  143. ->orderBy('CREATED_AT DESC')
  144. ->one()
  145. ->toArray();
  146. if (!$codeObj || !$codeObj['CODE'] || $codeObj['CODE'] != $this->code) {
  147. throw new Exception('邮箱验证码不正确,无法登录');
  148. }
  149. if ($codeObj['CREATED_AT'] + 5 * 60 < time()) {
  150. $this->_updateFailTimes($transaction,'验证码已过期, 请重新获取验证码. ' . $loginFailNums);
  151. throw new Exception('用户名或者密码错误');
  152. }
  153. if(!$this->_user['IS_ENABLE']){
  154. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  155. throw new Exception('用户名或者密码错误');
  156. }
  157. if (!$this->_user->validatePassword($this->password)) {
  158. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  159. throw new Exception('用户名或者密码错误');
  160. }
  161. //验证IP
  162. $bindIp = trim($this->_user['BIND_IP']);
  163. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  164. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  165. throw new Exception('用户名或者密码错误');
  166. }
  167. //需要修改密码
  168. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  169. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  170. }
  171. $this->_updateSuccessTimes();
  172. $transaction->commit();
  173. AdminLoginLogger::success($this->_user, $this->password);
  174. // 把用户的登录时间存在操作时间里
  175. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  176. return Yii::$app->user->loginWithUAndP($this->_user);
  177. }catch(\Exception $e){
  178. $transaction->rollBack();
  179. $this->setError($e->getMessage());
  180. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  181. return false;
  182. }
  183. }
  184. /**
  185. * Finds user by [[username]]
  186. *
  187. * @return User|null
  188. */
  189. public function getUser() {
  190. if ($this->_user === null) {
  191. $this->_user = User::findByUsername(strtolower($this->adminName));
  192. }
  193. return $this->_user;
  194. }
  195. }