LoginForm.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. namespace backendApi\modules\v1\models;
  3. use common\components\Model;
  4. use common\helpers\DingTalk;
  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. private $_user;
  18. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  19. const BACKEND_LOGIN_FAIL_TIMES = 'backend:loginFail:times_%s';
  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'], '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, 'Member does not exist');
  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. $cacheKey = sprintf(self::BACKEND_LOGIN_FAIL_TIMES, $this->adminName);
  84. Yii::$app->tokenRedis->incr($cacheKey);
  85. // 连续登录失败次数
  86. $loginFailTimes = (int)Yii::$app->tokenRedis->get($cacheKey);
  87. // 连续登录失败次数上限
  88. $loginFailedTopLimit = (int)Yii::$app->params['backendLoginFailedTimesTopLimit'];
  89. if ($loginFailTimes >= $loginFailedTopLimit) {
  90. // 发送钉钉提醒
  91. $content = [
  92. 'env' => 'backend',
  93. 'message' => sprintf('(NG)提醒:管理员[%s]连续登录失败%d次', $this->adminName, $loginFailTimes),
  94. ];
  95. DingTalk::sendNotice($content);
  96. }
  97. if(isset($this->_user)){
  98. AdminLoginLogger::fail($this->_user,$returnResult);
  99. }
  100. }
  101. /**
  102. * 更新成功次数
  103. */
  104. private function _updateSuccessTimes(){
  105. $cacheKey = sprintf(self::BACKEND_LOGIN_FAIL_TIMES, $this->adminName);
  106. Yii::$app->tokenRedis->del($cacheKey);
  107. Admin::updateAllCounters([
  108. 'LOGIN_NUMS' => 1,
  109. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  110. }
  111. /**
  112. * 登录
  113. * @return array|bool
  114. * @throws \yii\base\Exception
  115. * @throws \yii\db\Exception
  116. */
  117. public function login(){
  118. if(!$this->validate()){
  119. return false;
  120. }
  121. $transaction = \Yii::$app->db->beginTransaction();
  122. try{
  123. $this->getUser();
  124. if(!$this->_user){
  125. throw new Exception('The account does not exist'); // 账号不存在
  126. }
  127. if(!$this->_user['IS_ENABLE']){
  128. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  129. throw new Exception('The account has been locked and cannot be logged in'); // 账号已经被锁定,无法登录
  130. }
  131. if (!$this->_user->validatePassword($this->password)) {
  132. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  133. throw new Exception('Incorrect user name or password'); // 用户名或者密码错误
  134. }
  135. //验证IP
  136. $bindIp = trim($this->_user['BIND_IP']);
  137. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  138. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  139. throw new Exception('The login IP does not match the IP bound to this account'.$bindIp); // 登录IP与此账号绑定的IP不符
  140. }
  141. //需要修改密码
  142. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  143. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  144. }
  145. $this->_updateSuccessTimes();
  146. $transaction->commit();
  147. AdminLoginLogger::success($this->_user);
  148. // 把用户的登录时间存在操作时间里
  149. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  150. return Yii::$app->user->loginWithUAndP($this->_user);
  151. }catch(\Exception $e){
  152. $transaction->rollBack();
  153. $this->setError($e->getMessage());
  154. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  155. return false;
  156. }
  157. }
  158. /**
  159. * Finds user by [[username]]
  160. *
  161. * @return User|null
  162. */
  163. public function getUser() {
  164. if ($this->_user === null) {
  165. $this->_user = User::findByUsername(strtolower($this->adminName));
  166. }
  167. return $this->_user;
  168. }
  169. }