LoginForm.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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\LoginIpChecker;
  7. use Yii;
  8. use yii\base\Exception;
  9. use yii\captcha\Captcha;
  10. use common\libs\logging\login\AdminLogin as AdminLoginLogger;
  11. /**
  12. * Login form
  13. */
  14. class LoginForm extends Model {
  15. public $adminName;
  16. public $password;
  17. public $verifyCode;
  18. public $lang;
  19. private $_user;
  20. const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
  21. /**
  22. * @inheritdoc
  23. */
  24. public function attributeLabels()
  25. {
  26. return [
  27. 'adminName' => '登录帐号',
  28. 'password' => '登录密码',
  29. 'verifyCode' => '验证码',
  30. 'lang' => '语言标识',
  31. ];
  32. }
  33. /**
  34. * @inheritdoc
  35. */
  36. public function rules() {
  37. return [
  38. // username and password are both required
  39. [['adminName', 'password', 'verifyCode'], '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, 'Member does not exist');
  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 = Admin::findOneAsArray('ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  82. if ($admin['FAIL_NUMS'] > 0) {
  83. Admin::updateAllCounters([
  84. 'FAIL_NUMS' => 1,
  85. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  86. } else {
  87. Admin::updateAll(['FAIL_NUMS' => 1], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  88. }
  89. $transaction->commit();
  90. if(isset($this->_user)){
  91. AdminLoginLogger::fail($this->_user,$returnResult, $this->password);
  92. }
  93. // 失败写入缓存锁
  94. Yii::$app->redis->incr('FAIL_NUMS:' . $this->adminName);
  95. LoggerTool::error(sprintf('tmp_log_fail_nums_incr, adminName: %s', $this->adminName));
  96. }
  97. /**
  98. * 更新成功次数
  99. */
  100. private function _updateSuccessTimes(){
  101. $admin = Admin::findOneAsArray('ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  102. if ($admin['LOGIN_NUMS'] > 0) {
  103. Admin::updateAllCounters([
  104. 'LOGIN_NUMS' => 1,
  105. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  106. } else {
  107. Admin::updateAll(['LOGIN_NUMS' => 1], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  108. }
  109. }
  110. /**
  111. * 更新系统语言类型
  112. * @param $lang
  113. * @return void
  114. */
  115. private function _updateLang($lang) {
  116. $lang = Tool::langConvert($lang);
  117. Admin::updateAll([
  118. 'LANG' => $lang,
  119. ], 'ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME' => $this->adminName]);
  120. }
  121. /**
  122. * 登录
  123. * @return array|bool
  124. * @throws \yii\base\Exception
  125. * @throws \yii\db\Exception
  126. */
  127. public function login(){
  128. if(!$this->validate()){
  129. return false;
  130. }
  131. $transaction = \Yii::$app->db->beginTransaction();
  132. try{
  133. $this->getUser();
  134. if(!$this->_user){
  135. throw new Exception('The account does not exist'); // 账号不存在
  136. }
  137. if(!$this->_user['IS_ENABLE']){
  138. $this->_updateFailTimes($transaction,'账号已经被锁定,无法登录');
  139. throw new Exception('The account has been locked and cannot be logged in'); // 账号已经被锁定,无法登录
  140. }
  141. if (!$this->_user->validatePassword($this->password)) {
  142. $this->_updateFailTimes($transaction,'用户名或者密码错误');
  143. throw new Exception('Incorrect user name or password'); // 用户名或者密码错误
  144. }
  145. //验证IP
  146. $bindIp = trim($this->_user['BIND_IP']);
  147. if(!empty($bindIp) && !(new LoginIpChecker(Yii::$app->request->getUserIP(), $bindIp))->validate()){
  148. $this->_updateFailTimes($transaction,'登录IP与此账号绑定的IP不符');
  149. throw new Exception('The login IP does not match the IP bound to this account'.$bindIp); // 登录IP与此账号绑定的IP不符
  150. }
  151. //需要修改密码
  152. if($this->_user['IS_MODIFY_PASSWORD'] == 1){
  153. throw new Exception(self::ERROR_IS_MODIFY_PASSWORD);
  154. }
  155. $this->_updateSuccessTimes();
  156. // 如果用户没有设置语言类型,则选择前端传递的语言类型,并存储到表中
  157. if (!$this->_user['LANG']) {
  158. $this->_updateLang($this->lang);
  159. }
  160. $transaction->commit();
  161. AdminLoginLogger::success($this->_user);
  162. // 把用户的登录时间存在操作时间里
  163. Yii::$app->tokenRedis->hset('admin:timeOut', $this->_user->getId(), time());
  164. return Yii::$app->user->loginWithUAndP($this->_user);
  165. }catch(\Exception $e){
  166. $transaction->rollBack();
  167. $this->setError($e->getMessage());
  168. //AdminLoginLogger::fail($this->_user, $e->getMessage());
  169. return false;
  170. }
  171. }
  172. /**
  173. * Finds user by [[username]]
  174. *
  175. * @return User|null
  176. */
  177. public function getUser() {
  178. if ($this->_user === null) {
  179. $this->_user = User::findByUsername(strtolower($this->adminName));
  180. }
  181. return $this->_user;
  182. }
  183. }