LoginForm.php 6.3 KB

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