SysLoginService.java 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. package com.ruoyi.system.service;
  2. import cn.dev33.satoken.stp.StpUtil;
  3. import cn.hutool.core.util.ObjectUtil;
  4. import com.ruoyi.common.constant.Constants;
  5. import com.ruoyi.common.core.domain.entity.SysUser;
  6. import com.ruoyi.common.core.domain.model.LoginUser;
  7. import com.ruoyi.common.core.service.LogininforService;
  8. import com.ruoyi.common.enums.DeviceType;
  9. import com.ruoyi.common.enums.UserStatus;
  10. import com.ruoyi.common.enums.UserType;
  11. import com.ruoyi.common.exception.user.CaptchaException;
  12. import com.ruoyi.common.exception.user.CaptchaExpireException;
  13. import com.ruoyi.common.exception.user.UserException;
  14. import com.ruoyi.common.helper.LoginHelper;
  15. import com.ruoyi.common.utils.*;
  16. import com.ruoyi.common.utils.redis.RedisUtils;
  17. import lombok.RequiredArgsConstructor;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.springframework.stereotype.Service;
  20. import javax.servlet.http.HttpServletRequest;
  21. import java.util.concurrent.TimeUnit;
  22. /**
  23. * 登录校验方法
  24. *
  25. * @author Lion Li
  26. */
  27. @RequiredArgsConstructor
  28. @Slf4j
  29. @Service
  30. public class SysLoginService {
  31. private final ISysUserService userService;
  32. private final ISysConfigService configService;
  33. private final LogininforService asyncService;
  34. private final SysPermissionService permissionService;
  35. /**
  36. * 登录验证
  37. *
  38. * @param username 用户名
  39. * @param password 密码
  40. * @param code 验证码
  41. * @param uuid 唯一标识
  42. * @return 结果
  43. */
  44. public String login(String username, String password, String code, String uuid) {
  45. HttpServletRequest request = ServletUtils.getRequest();
  46. boolean captchaOnOff = configService.selectCaptchaOnOff();
  47. // 验证码开关
  48. if (captchaOnOff) {
  49. validateCaptcha(username, code, uuid, request);
  50. }
  51. // 获取用户登录错误次数(可自定义限制策略 例如: key + username + ip)
  52. Integer errorNumber = RedisUtils.getCacheObject(Constants.LOGIN_ERROR + username);
  53. // 锁定时间内登录 则踢出
  54. if (ObjectUtil.isNotNull(errorNumber) && errorNumber.equals(Constants.LOGIN_ERROR_NUMBER)) {
  55. asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", Constants.LOGIN_ERROR_LIMIT_TIME), request);
  56. throw new UserException("user.password.retry.limit.exceed", Constants.LOGIN_ERROR_LIMIT_TIME);
  57. }
  58. SysUser user = userService.selectUserByUserName(username);
  59. if (StringUtils.isNull(user)) {
  60. log.info("登录用户:{} 不存在.", username);
  61. throw new UserException("user.not.exists", username);
  62. } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
  63. log.info("登录用户:{} 已被删除.", username);
  64. throw new UserException("user.password.delete", username);
  65. } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
  66. log.info("登录用户:{} 已被停用.", username);
  67. throw new UserException("user.blocked", username);
  68. }
  69. if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
  70. // 是否第一次
  71. errorNumber = ObjectUtil.isNull(errorNumber) ? 1 : errorNumber + 1;
  72. // 达到规定错误次数 则锁定登录
  73. if (errorNumber.equals(Constants.LOGIN_ERROR_NUMBER)) {
  74. RedisUtils.setCacheObject(Constants.LOGIN_ERROR + username, errorNumber, Constants.LOGIN_ERROR_LIMIT_TIME, TimeUnit.MINUTES);
  75. asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", Constants.LOGIN_ERROR_LIMIT_TIME), request);
  76. throw new UserException("user.password.retry.limit.exceed", Constants.LOGIN_ERROR_LIMIT_TIME);
  77. } else {
  78. // 未达到规定错误次数 则递增
  79. RedisUtils.setCacheObject(Constants.LOGIN_ERROR + username, errorNumber);
  80. asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", errorNumber), request);
  81. throw new UserException("user.password.retry.limit.count", errorNumber);
  82. }
  83. }
  84. // 登录成功 清空错误次数
  85. RedisUtils.deleteObject(Constants.LOGIN_ERROR + username);
  86. asyncService.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
  87. recordLoginInfo(user.getUserId(), username);
  88. LoginUser loginUser = new LoginUser();
  89. loginUser.setUserId(user.getUserId());
  90. loginUser.setDeptId(user.getDeptId());
  91. loginUser.setUsername(user.getUserName());
  92. loginUser.setUserType(UserType.SYS_USER.getUserType());
  93. loginUser.setMenuPermission(permissionService.getMenuPermission(user));
  94. loginUser.setRolePermission(permissionService.getRolePermission(user));
  95. // 生成token
  96. LoginHelper.loginByDevice(loginUser, DeviceType.PC);
  97. return StpUtil.getTokenValue();
  98. }
  99. /**
  100. * 校验验证码
  101. *
  102. * @param username 用户名
  103. * @param code 验证码
  104. * @param uuid 唯一标识
  105. */
  106. public void validateCaptcha(String username, String code, String uuid, HttpServletRequest request) {
  107. String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
  108. String captcha = RedisUtils.getCacheObject(verifyKey);
  109. RedisUtils.deleteObject(verifyKey);
  110. if (captcha == null) {
  111. asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"), request);
  112. throw new CaptchaExpireException();
  113. }
  114. if (!code.equalsIgnoreCase(captcha)) {
  115. asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"), request);
  116. throw new CaptchaException();
  117. }
  118. }
  119. /**
  120. * 记录登录信息
  121. *
  122. * @param userId 用户ID
  123. */
  124. public void recordLoginInfo(Long userId, String username) {
  125. SysUser sysUser = new SysUser();
  126. sysUser.setUserId(userId);
  127. sysUser.setLoginIp(ServletUtils.getClientIP());
  128. sysUser.setLoginDate(DateUtils.getNowDate());
  129. sysUser.setUpdateBy(username);
  130. userService.updateUserProfile(sysUser);
  131. }
  132. }