SysLoginService.java 9.8 KB

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