SysLoginService.java 7.2 KB

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