LoginForm.php 5.9 KB

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