SysLoginService.java 6.5 KB

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