SysLoginService.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package org.dromara.web.service;
  2. import cn.dev33.satoken.exception.NotLoginException;
  3. import cn.dev33.satoken.stp.StpUtil;
  4. import cn.hutool.core.bean.BeanUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import lombok.RequiredArgsConstructor;
  7. import lombok.extern.slf4j.Slf4j;
  8. import me.zhyd.oauth.model.AuthUser;
  9. import org.dromara.common.core.constant.Constants;
  10. import org.dromara.common.core.constant.GlobalConstants;
  11. import org.dromara.common.core.constant.TenantConstants;
  12. import org.dromara.common.core.domain.dto.RoleDTO;
  13. import org.dromara.common.core.domain.model.LoginUser;
  14. import org.dromara.common.core.enums.LoginType;
  15. import org.dromara.common.core.enums.TenantStatus;
  16. import org.dromara.common.core.exception.user.UserException;
  17. import org.dromara.common.core.utils.*;
  18. import org.dromara.common.log.event.LogininforEvent;
  19. import org.dromara.common.redis.utils.RedisUtils;
  20. import org.dromara.common.satoken.utils.LoginHelper;
  21. import org.dromara.common.tenant.exception.TenantException;
  22. import org.dromara.common.tenant.helper.TenantHelper;
  23. import org.dromara.system.domain.SysUser;
  24. import org.dromara.system.domain.bo.SysSocialBo;
  25. import org.dromara.system.domain.vo.SysSocialVo;
  26. import org.dromara.system.domain.vo.SysTenantVo;
  27. import org.dromara.system.domain.vo.SysUserVo;
  28. import org.dromara.system.mapper.SysUserMapper;
  29. import org.dromara.system.service.ISysPermissionService;
  30. import org.dromara.system.service.ISysSocialService;
  31. import org.dromara.system.service.ISysTenantService;
  32. import org.springframework.beans.factory.annotation.Value;
  33. import org.springframework.stereotype.Service;
  34. import java.time.Duration;
  35. import java.util.Date;
  36. import java.util.List;
  37. import java.util.function.Supplier;
  38. /**
  39. * 登录校验方法
  40. *
  41. * @author Lion Li
  42. */
  43. @RequiredArgsConstructor
  44. @Slf4j
  45. @Service
  46. public class SysLoginService {
  47. @Value("${user.password.maxRetryCount}")
  48. private Integer maxRetryCount;
  49. @Value("${user.password.lockTime}")
  50. private Integer lockTime;
  51. private final ISysTenantService tenantService;
  52. private final ISysPermissionService permissionService;
  53. private final ISysSocialService sysSocialService;
  54. private final SysUserMapper userMapper;
  55. /**
  56. * 绑定第三方用户
  57. *
  58. * @param authUserData 授权响应实体
  59. * @return 统一响应实体
  60. */
  61. public void socialRegister(AuthUser authUserData) {
  62. String authId = authUserData.getSource() + authUserData.getUuid();
  63. // 第三方用户信息
  64. SysSocialBo bo = BeanUtil.toBean(authUserData, SysSocialBo.class);
  65. BeanUtil.copyProperties(authUserData.getToken(), bo);
  66. bo.setUserId(LoginHelper.getUserId());
  67. bo.setAuthId(authId);
  68. bo.setOpenId(authUserData.getUuid());
  69. bo.setUserName(authUserData.getUsername());
  70. bo.setNickName(authUserData.getNickname());
  71. // 查询是否已经绑定用户
  72. SysSocialVo vo = sysSocialService.selectByAuthId(authId);
  73. if (ObjectUtil.isEmpty(vo)) {
  74. // 没有绑定用户, 新增用户信息
  75. sysSocialService.insertByBo(bo);
  76. } else {
  77. // 更新用户信息
  78. bo.setId(vo.getId());
  79. sysSocialService.updateByBo(bo);
  80. }
  81. }
  82. /**
  83. * 退出登录
  84. */
  85. public void logout() {
  86. try {
  87. LoginUser loginUser = LoginHelper.getLoginUser();
  88. if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
  89. // 超级管理员 登出清除动态租户
  90. TenantHelper.clearDynamic();
  91. }
  92. recordLogininfor(loginUser.getTenantId(), loginUser.getUsername(), Constants.LOGOUT, MessageUtils.message("user.logout.success"));
  93. } catch (NotLoginException ignored) {
  94. } finally {
  95. try {
  96. StpUtil.logout();
  97. } catch (NotLoginException ignored) {
  98. }
  99. }
  100. }
  101. /**
  102. * 记录登录信息
  103. *
  104. * @param tenantId 租户ID
  105. * @param username 用户名
  106. * @param status 状态
  107. * @param message 消息内容
  108. */
  109. public void recordLogininfor(String tenantId, String username, String status, String message) {
  110. LogininforEvent logininforEvent = new LogininforEvent();
  111. logininforEvent.setTenantId(tenantId);
  112. logininforEvent.setUsername(username);
  113. logininforEvent.setStatus(status);
  114. logininforEvent.setMessage(message);
  115. logininforEvent.setRequest(ServletUtils.getRequest());
  116. SpringUtils.context().publishEvent(logininforEvent);
  117. }
  118. /**
  119. * 构建登录用户
  120. */
  121. public LoginUser buildLoginUser(SysUserVo user) {
  122. LoginUser loginUser = new LoginUser();
  123. loginUser.setTenantId(user.getTenantId());
  124. loginUser.setUserId(user.getUserId());
  125. loginUser.setDeptId(user.getDeptId());
  126. loginUser.setUsername(user.getUserName());
  127. loginUser.setNickname(user.getNickName());
  128. loginUser.setUserType(user.getUserType());
  129. loginUser.setMenuPermission(permissionService.getMenuPermission(user.getUserId()));
  130. loginUser.setRolePermission(permissionService.getRolePermission(user.getUserId()));
  131. loginUser.setDeptName(ObjectUtil.isNull(user.getDept()) ? "" : user.getDept().getDeptName());
  132. List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
  133. loginUser.setRoles(roles);
  134. return loginUser;
  135. }
  136. /**
  137. * 记录登录信息
  138. *
  139. * @param userId 用户ID
  140. */
  141. public void recordLoginInfo(Long userId) {
  142. SysUser sysUser = new SysUser();
  143. sysUser.setUserId(userId);
  144. sysUser.setLoginIp(ServletUtils.getClientIP());
  145. sysUser.setLoginDate(DateUtils.getNowDate());
  146. sysUser.setUpdateBy(userId);
  147. userMapper.updateById(sysUser);
  148. }
  149. /**
  150. * 登录校验
  151. */
  152. public void checkLogin(LoginType loginType, String tenantId, String username, Supplier<Boolean> supplier) {
  153. String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
  154. String loginFail = Constants.LOGIN_FAIL;
  155. // 获取用户登录错误次数,默认为0 (可自定义限制策略 例如: key + username + ip)
  156. int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
  157. // 锁定时间内登录 则踢出
  158. if (errorNumber >= maxRetryCount) {
  159. recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
  160. throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
  161. }
  162. if (supplier.get()) {
  163. // 错误次数递增
  164. errorNumber++;
  165. RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
  166. // 达到规定错误次数 则锁定登录
  167. if (errorNumber >= maxRetryCount) {
  168. recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
  169. throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
  170. } else {
  171. // 未达到规定错误次数
  172. recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
  173. throw new UserException(loginType.getRetryLimitCount(), errorNumber);
  174. }
  175. }
  176. // 登录成功 清空错误次数
  177. RedisUtils.deleteObject(errorKey);
  178. }
  179. /**
  180. * 校验租户
  181. *
  182. * @param tenantId 租户ID
  183. */
  184. public void checkTenant(String tenantId) {
  185. if (!TenantHelper.isEnable()) {
  186. return;
  187. }
  188. if (TenantConstants.DEFAULT_TENANT_ID.equals(tenantId)) {
  189. return;
  190. }
  191. if (StringUtils.isBlank(tenantId)) {
  192. throw new TenantException("tenant.number.not.blank");
  193. }
  194. SysTenantVo tenant = tenantService.queryByTenantId(tenantId);
  195. if (ObjectUtil.isNull(tenant)) {
  196. log.info("登录租户:{} 不存在.", tenantId);
  197. throw new TenantException("tenant.not.exists");
  198. } else if (TenantStatus.DISABLE.getCode().equals(tenant.getStatus())) {
  199. log.info("登录租户:{} 已被停用.", tenantId);
  200. throw new TenantException("tenant.blocked");
  201. } else if (ObjectUtil.isNotNull(tenant.getExpireTime())
  202. && new Date().after(tenant.getExpireTime())) {
  203. log.info("登录租户:{} 已超过有效期.", tenantId);
  204. throw new TenantException("tenant.expired");
  205. }
  206. }
  207. }