refactor: 多租户开发和代码规范调整
This commit is contained in:
@@ -27,7 +27,7 @@ import java.util.List;
|
||||
*/
|
||||
@Tag(name = "租户管理接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/tenant")
|
||||
@RequestMapping("/api/v1/tenants")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
@@ -44,7 +44,7 @@ public class TenantController {
|
||||
* @return 租户列表
|
||||
*/
|
||||
@Operation(summary = "获取当前用户的租户列表")
|
||||
@GetMapping("/list")
|
||||
@GetMapping
|
||||
public Result<List<TenantVO>> getTenantList() {
|
||||
Long userId = SecurityUtils.getUserId();
|
||||
List<TenantVO> tenantList = tenantService.getTenantListByUserId(userId);
|
||||
@@ -72,14 +72,13 @@ public class TenantController {
|
||||
* 切换租户
|
||||
* <p>
|
||||
* 切换当前用户的租户上下文,需要验证用户是否有权限访问该租户
|
||||
* 并记录审计日志
|
||||
* </p>
|
||||
*
|
||||
* @param tenantId 目标租户ID
|
||||
* @return 切换结果
|
||||
*/
|
||||
@Operation(summary = "切换租户")
|
||||
@PostMapping("/switch/{tenantId}")
|
||||
@PostMapping("/{tenantId}/switch")
|
||||
public Result<TenantVO> switchTenant(
|
||||
@Parameter(description = "租户ID") @PathVariable Long tenantId,
|
||||
HttpServletRequest request
|
||||
@@ -89,41 +88,30 @@ public class TenantController {
|
||||
|
||||
log.info("用户 {} 请求切换租户:{} -> {}", userId, fromTenantId, tenantId);
|
||||
|
||||
try {
|
||||
// 验证用户是否有权限访问该租户
|
||||
boolean hasPermission = tenantService.hasTenantPermission(userId, tenantId);
|
||||
if (!hasPermission) {
|
||||
log.warn("用户 {} 无权限访问租户 {}", userId, tenantId);
|
||||
// 记录失败日志
|
||||
tenantService.recordTenantSwitch(userId, fromTenantId, tenantId, false, "无权限访问该租户", request);
|
||||
return Result.failed("无权限访问该租户");
|
||||
}
|
||||
|
||||
// 验证租户是否存在且正常
|
||||
TenantVO tenant = tenantService.getTenantById(tenantId);
|
||||
if (tenant == null) {
|
||||
tenantService.recordTenantSwitch(userId, fromTenantId, tenantId, false, "租户不存在", request);
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
if (tenant.getStatus() == null || tenant.getStatus() != 1) {
|
||||
tenantService.recordTenantSwitch(userId, fromTenantId, tenantId, false, "租户已禁用", request);
|
||||
return Result.failed("租户已禁用");
|
||||
}
|
||||
|
||||
// 设置新的租户上下文
|
||||
TenantContextHolder.setTenantId(tenantId);
|
||||
|
||||
// 记录成功日志
|
||||
tenantService.recordTenantSwitch(userId, fromTenantId, tenantId, true, null, request);
|
||||
|
||||
log.info("用户 {} 成功切换租户到 {}", userId, tenantId);
|
||||
|
||||
return Result.success(tenant);
|
||||
} catch (Exception e) {
|
||||
log.error("用户 {} 切换租户失败", userId, e);
|
||||
tenantService.recordTenantSwitch(userId, fromTenantId, tenantId, false, e.getMessage(), request);
|
||||
return Result.failed("切换租户失败:" + e.getMessage());
|
||||
// 验证用户是否有权限访问该租户
|
||||
boolean hasPermission = tenantService.hasTenantPermission(userId, tenantId);
|
||||
if (!hasPermission) {
|
||||
log.warn("用户 {} 无权限访问租户 {}", userId, tenantId);
|
||||
return Result.failed("无权限访问该租户");
|
||||
}
|
||||
|
||||
// 验证租户是否存在且正常
|
||||
TenantVO tenant = tenantService.getTenantById(tenantId);
|
||||
if (tenant == null) {
|
||||
log.warn("用户 {} 尝试切换到不存在的租户 {}", userId, tenantId);
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
if (tenant.getStatus() == null || tenant.getStatus() != 1) {
|
||||
log.warn("用户 {} 尝试切换到已禁用的租户 {}", userId, tenantId);
|
||||
return Result.failed("租户已禁用");
|
||||
}
|
||||
|
||||
// 设置新的租户上下文
|
||||
TenantContextHolder.setTenantId(tenantId);
|
||||
|
||||
log.info("用户 {} 成功切换租户:{} -> {}", userId, fromTenantId, tenantId);
|
||||
|
||||
return Result.success(tenant);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.youlai.boot.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.system.model.entity.TenantSwitchLog;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 租户切换审计日志 Mapper
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface TenantSwitchLogMapper extends BaseMapper<TenantSwitchLog> {
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.youlai.boot.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.system.model.entity.UserTenant;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 用户租户关联 Mapper
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface UserTenantMapper extends BaseMapper<UserTenant> {
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 租户切换审计日志实体
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@TableName("sys_tenant_switch_log")
|
||||
public class TenantSwitchLog {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 原租户ID
|
||||
*/
|
||||
private Long fromTenantId;
|
||||
|
||||
/**
|
||||
* 原租户名称
|
||||
*/
|
||||
private String fromTenantName;
|
||||
|
||||
/**
|
||||
* 目标租户ID
|
||||
*/
|
||||
private Long toTenantId;
|
||||
|
||||
/**
|
||||
* 目标租户名称
|
||||
*/
|
||||
private String toTenantName;
|
||||
|
||||
/**
|
||||
* 切换时间
|
||||
*/
|
||||
private LocalDateTime switchTime;
|
||||
|
||||
/**
|
||||
* IP地址
|
||||
*/
|
||||
private String ipAddress;
|
||||
|
||||
/**
|
||||
* 浏览器信息
|
||||
*/
|
||||
private String userAgent;
|
||||
|
||||
/**
|
||||
* 切换状态(1-成功 0-失败)
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 失败原因
|
||||
*/
|
||||
private String failReason;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.youlai.boot.system.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 用户租户关联实体
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_user_tenant")
|
||||
public class UserTenant extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
private Long tenantId;
|
||||
|
||||
/**
|
||||
* 是否默认租户(1-是 0-否)
|
||||
*/
|
||||
private Integer isDefault;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.youlai.boot.system.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.platform.codegen.model.entity.GenConfig;
|
||||
import com.youlai.boot.platform.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.system.model.form.MenuForm;
|
||||
import com.youlai.boot.common.model.Option;
|
||||
import com.youlai.boot.system.model.entity.Menu;
|
||||
@@ -79,5 +79,5 @@ public interface MenuService extends IService<Menu> {
|
||||
* @param parentMenuId 父菜单ID
|
||||
* @param genConfig 实体名
|
||||
*/
|
||||
void addMenuForCodegen(Long parentMenuId, GenConfig genConfig);
|
||||
void addMenuForCodegen(Long parentMenuId, GenTable genTable);
|
||||
}
|
||||
|
||||
@@ -46,17 +46,4 @@ public interface TenantService extends IService<Tenant> {
|
||||
* @return true-有权限,false-无权限
|
||||
*/
|
||||
boolean hasTenantPermission(Long userId, Long tenantId);
|
||||
|
||||
/**
|
||||
* 记录租户切换审计日志
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param fromTenantId 原租户ID
|
||||
* @param toTenantId 目标租户ID
|
||||
* @param success 是否成功
|
||||
* @param failReason 失败原因
|
||||
* @param request HTTP请求对象
|
||||
*/
|
||||
void recordTenantSwitch(Long userId, Long fromTenantId, Long toTenantId,
|
||||
boolean success, String failReason, jakarta.servlet.http.HttpServletRequest request);
|
||||
}
|
||||
|
||||
@@ -71,9 +71,25 @@ public interface UserService extends IService<User> {
|
||||
* @param username 用户名
|
||||
* @return {@link UserAuthCredentials}
|
||||
*/
|
||||
|
||||
UserAuthCredentials getAuthCredentialsByUsername(String username);
|
||||
|
||||
/**
|
||||
* 根据用户名和租户ID获取认证信息(用于多租户登录)
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param tenantId 租户ID
|
||||
* @return {@link UserAuthCredentials}
|
||||
*/
|
||||
UserAuthCredentials getAuthCredentialsByUsernameAndTenant(String username, Long tenantId);
|
||||
|
||||
/**
|
||||
* 根据用户名查询该用户在所有租户下的记录(用于多租户登录时判断是否需要选择租户)
|
||||
*
|
||||
* @param username 用户名
|
||||
* @return 用户列表(每个租户一条记录)
|
||||
*/
|
||||
List<User> listUsersByUsername(String username);
|
||||
|
||||
|
||||
/**
|
||||
* 获取导出用户列表
|
||||
|
||||
@@ -10,7 +10,7 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.youlai.boot.platform.codegen.model.entity.GenConfig;
|
||||
import com.youlai.boot.platform.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.security.util.SecurityUtils;
|
||||
import com.youlai.boot.system.converter.MenuConverter;
|
||||
import com.youlai.boot.system.mapper.MenuMapper;
|
||||
@@ -427,14 +427,14 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements Me
|
||||
* 代码生成时添加菜单
|
||||
*
|
||||
* @param parentMenuId 父菜单ID
|
||||
* @param genConfig 实体名称
|
||||
* @param genTable 实体名称
|
||||
*/
|
||||
@Override
|
||||
public void addMenuForCodegen(Long parentMenuId, GenConfig genConfig) {
|
||||
public void addMenuForCodegen(Long parentMenuId, GenTable genTable) {
|
||||
Menu parentMenu = this.getById(parentMenuId);
|
||||
Assert.notNull(parentMenu, "上级菜单不存在");
|
||||
|
||||
String entityName = genConfig.getEntityName();
|
||||
String entityName = genTable.getEntityName();
|
||||
|
||||
long count = this.count(new LambdaQueryWrapper<Menu>().eq(Menu::getRouteName, entityName));
|
||||
if (count > 0) {
|
||||
@@ -453,11 +453,11 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements Me
|
||||
|
||||
Menu menu = new Menu();
|
||||
menu.setParentId(parentMenuId);
|
||||
menu.setName(genConfig.getBusinessName());
|
||||
menu.setName(genTable.getBusinessName());
|
||||
|
||||
menu.setRouteName(entityName);
|
||||
menu.setRoutePath(StrUtil.toSymbolCase(entityName, '-'));
|
||||
menu.setComponent(genConfig.getModuleName() + "/" + StrUtil.toSymbolCase(entityName, '-') + "/index");
|
||||
menu.setComponent(genTable.getModuleName() + "/" + StrUtil.toSymbolCase(entityName, '-') + "/index");
|
||||
menu.setType(MenuTypeEnum.MENU.getValue());
|
||||
menu.setSort(sort);
|
||||
menu.setVisible(1);
|
||||
@@ -470,7 +470,7 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements Me
|
||||
this.updateById(menu);
|
||||
|
||||
// 生成CURD按钮权限
|
||||
String permPrefix = genConfig.getModuleName() + ":" + genConfig.getTableName().replace("_", "-") + ":";
|
||||
String permPrefix = genTable.getModuleName() + ":" + genTable.getTableName().replace("_", "-") + ":";
|
||||
String[] actions = {"查询", "新增", "修改", "删除"};
|
||||
String[] perms = {"list", "create", "update", "delete"};
|
||||
|
||||
|
||||
@@ -1,28 +1,22 @@
|
||||
package com.youlai.boot.system.service.impl;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.system.mapper.TenantMapper;
|
||||
import com.youlai.boot.system.mapper.TenantSwitchLogMapper;
|
||||
import com.youlai.boot.system.mapper.UserMapper;
|
||||
import com.youlai.boot.system.mapper.UserTenantMapper;
|
||||
import com.youlai.boot.system.model.entity.Tenant;
|
||||
import com.youlai.boot.system.model.entity.TenantSwitchLog;
|
||||
import com.youlai.boot.system.model.entity.User;
|
||||
import com.youlai.boot.system.model.entity.UserTenant;
|
||||
import com.youlai.boot.system.model.vo.TenantVO;
|
||||
import com.youlai.boot.system.service.TenantService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* 租户服务实现类
|
||||
@@ -35,8 +29,6 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
|
||||
|
||||
private final UserTenantMapper userTenantMapper;
|
||||
private final TenantSwitchLogMapper tenantSwitchLogMapper;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@Override
|
||||
@@ -44,21 +36,34 @@ public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> impleme
|
||||
// 临时忽略租户过滤,查询所有租户
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
// 查询用户关联的租户ID列表
|
||||
List<UserTenant> userTenants = userTenantMapper.selectList(
|
||||
new LambdaQueryWrapper<UserTenant>()
|
||||
.eq(UserTenant::getUserId, userId)
|
||||
);
|
||||
|
||||
if (userTenants.isEmpty()) {
|
||||
// 先根据用户ID查询用户信息(获取 username)
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 提取租户ID列表
|
||||
List<Long> tenantIds = userTenants.stream()
|
||||
.map(UserTenant::getTenantId)
|
||||
// 通过 username 查询该用户在所有租户下的记录,获取租户ID列表
|
||||
List<User> users = userMapper.selectList(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, user.getUsername())
|
||||
.eq(User::getIsDeleted, 0)
|
||||
);
|
||||
|
||||
if (users.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 提取租户ID列表(去重)
|
||||
List<Long> tenantIds = users.stream()
|
||||
.map(User::getTenantId)
|
||||
.filter(tenantId -> tenantId != null)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (tenantIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 查询租户信息
|
||||
List<Tenant> tenants = this.list(
|
||||
new LambdaQueryWrapper<Tenant>()
|
||||
@@ -67,17 +72,19 @@ public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> impleme
|
||||
.orderByDesc(Tenant::getId)
|
||||
);
|
||||
|
||||
// 转换为VO并标记默认租户
|
||||
return tenants.stream().map(tenant -> {
|
||||
TenantVO vo = new TenantVO();
|
||||
BeanUtils.copyProperties(tenant, vo);
|
||||
// 查找是否为默认租户
|
||||
userTenants.stream()
|
||||
.filter(ut -> ut.getTenantId().equals(tenant.getId()) && ut.getIsDefault() == 1)
|
||||
.findFirst()
|
||||
.ifPresent(ut -> vo.setIsDefault(true));
|
||||
return vo;
|
||||
}).collect(Collectors.toList());
|
||||
// 转换为VO,第一个租户作为默认租户
|
||||
return IntStream.range(0, tenants.size())
|
||||
.mapToObj(index -> {
|
||||
Tenant tenant = tenants.get(index);
|
||||
TenantVO vo = new TenantVO();
|
||||
BeanUtils.copyProperties(tenant, vo);
|
||||
// 第一个租户作为默认租户
|
||||
if (index == 0) {
|
||||
vo.setIsDefault(true);
|
||||
}
|
||||
return vo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
@@ -119,94 +126,25 @@ public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> impleme
|
||||
public boolean hasTenantPermission(Long userId, Long tenantId) {
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
UserTenant userTenant = userTenantMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserTenant>()
|
||||
.eq(UserTenant::getUserId, userId)
|
||||
.eq(UserTenant::getTenantId, tenantId)
|
||||
// 先根据用户ID查询用户信息(获取 username)
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查该 username 在指定租户下是否存在用户记录
|
||||
User tenantUser = userMapper.selectOne(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, user.getUsername())
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return userTenant != null;
|
||||
return tenantUser != null;
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordTenantSwitch(Long userId, Long fromTenantId, Long toTenantId,
|
||||
boolean success, String failReason, HttpServletRequest request) {
|
||||
try {
|
||||
// 临时忽略租户过滤,确保日志可以写入
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
|
||||
// 创建审计日志
|
||||
TenantSwitchLog log = new TenantSwitchLog();
|
||||
log.setUserId(userId);
|
||||
log.setFromTenantId(fromTenantId);
|
||||
log.setToTenantId(toTenantId);
|
||||
log.setSwitchTime(LocalDateTime.now());
|
||||
log.setStatus(success ? 1 : 0);
|
||||
log.setFailReason(failReason);
|
||||
|
||||
// 获取用户名
|
||||
if (userId != null) {
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user != null) {
|
||||
log.setUsername(user.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
// 获取租户名称
|
||||
if (fromTenantId != null) {
|
||||
Tenant fromTenant = this.getById(fromTenantId);
|
||||
if (fromTenant != null) {
|
||||
log.setFromTenantName(fromTenant.getName());
|
||||
}
|
||||
}
|
||||
if (toTenantId != null) {
|
||||
Tenant toTenant = this.getById(toTenantId);
|
||||
if (toTenant != null) {
|
||||
log.setToTenantName(toTenant.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// 获取IP地址和User-Agent
|
||||
if (request != null) {
|
||||
log.setIpAddress(getIpAddress(request));
|
||||
log.setUserAgent(request.getHeader("User-Agent"));
|
||||
}
|
||||
|
||||
// 保存审计日志
|
||||
tenantSwitchLogMapper.insert(log);
|
||||
} catch (Exception e) {
|
||||
// 记录日志失败不应影响业务,仅记录错误
|
||||
Slf4j.getLogger(this.getClass()).error("记录租户切换日志失败", e);
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端IP地址
|
||||
*/
|
||||
private String getIpAddress(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("X-Real-IP");
|
||||
}
|
||||
if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
// 处理多级代理的情况
|
||||
if (ip != null && ip.contains(",")) {
|
||||
ip = ip.split(",")[0].trim();
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.youlai.boot.security.model.UserAuthCredentials;
|
||||
import com.youlai.boot.security.service.PermissionService;
|
||||
import com.youlai.boot.security.token.TokenManager;
|
||||
import com.youlai.boot.security.util.SecurityUtils;
|
||||
import com.youlai.boot.common.tenant.TenantContextHolder;
|
||||
import com.youlai.boot.platform.mail.service.MailService;
|
||||
import com.youlai.boot.system.converter.UserConverter;
|
||||
import com.youlai.boot.system.enums.DictCodeEnum;
|
||||
@@ -78,7 +79,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
|
||||
private final com.youlai.boot.config.property.TenantProperties tenantProperties;
|
||||
|
||||
private final com.youlai.boot.system.mapper.UserTenantMapper userTenantMapper;
|
||||
|
||||
/**
|
||||
* 获取用户分页列表
|
||||
@@ -126,17 +126,26 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
public boolean saveUser(UserForm userForm) {
|
||||
|
||||
String username = userForm.getUsername();
|
||||
|
||||
long count = this.count(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
|
||||
Assert.isTrue(count == 0, "用户名已存在");
|
||||
|
||||
|
||||
// 实体转换 form->entity
|
||||
User entity = userConverter.toEntity(userForm);
|
||||
|
||||
// 获取当前操作员的租户ID(新增用户时,租户ID由 MyMetaObjectHandler 自动填充)
|
||||
Long tenantId = TenantContextHolder.getTenantId();
|
||||
Assert.notNull(tenantId, "租户ID不能为空");
|
||||
|
||||
// 检查同一租户下用户名是否已存在(新设计:用户名在租户内唯一)
|
||||
long count = this.count(new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, tenantId));
|
||||
Assert.isTrue(count == 0, "该租户下用户名已存在");
|
||||
|
||||
// 设置默认加密密码
|
||||
String defaultEncryptPwd = passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD);
|
||||
entity.setPassword(defaultEncryptPwd);
|
||||
entity.setCreateBy(SecurityUtils.getUserId());
|
||||
|
||||
// 注意:租户ID由 MyMetaObjectHandler.insertFill() 自动填充,无需手动设置
|
||||
|
||||
// 新增用户
|
||||
boolean result = this.save(entity);
|
||||
@@ -144,11 +153,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
if (result) {
|
||||
// 保存用户角色
|
||||
userRoleService.saveUserRoles(entity.getId(), userForm.getRoleIds());
|
||||
|
||||
// 如果启用多租户,保存用户租户关联
|
||||
if (Boolean.TRUE.equals(tenantProperties.getEnabled())) {
|
||||
saveUserTenantRelation(entity.getId(), entity.getTenantId(), true);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -165,20 +169,32 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
public boolean updateUser(Long userId, UserForm userForm) {
|
||||
|
||||
String username = userForm.getUsername();
|
||||
|
||||
// 获取原用户信息
|
||||
User oldUser = this.getById(userId);
|
||||
Assert.notNull(oldUser, "用户不存在");
|
||||
|
||||
Long oldTenantId = oldUser.getTenantId();
|
||||
Long currentTenantId = TenantContextHolder.getTenantId();
|
||||
|
||||
// 验证:只能修改当前租户下的用户(防止跨租户修改)
|
||||
Assert.isTrue(oldTenantId != null && oldTenantId.equals(currentTenantId),
|
||||
"只能修改当前租户下的用户");
|
||||
|
||||
// 检查同一租户下用户名是否已存在(排除当前用户)
|
||||
long count = this.count(new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, currentTenantId)
|
||||
.ne(User::getId, userId)
|
||||
);
|
||||
Assert.isTrue(count == 0, "用户名已存在");
|
||||
|
||||
// 获取原用户信息,用于比较租户是否变更
|
||||
User oldUser = this.getById(userId);
|
||||
Long oldTenantId = oldUser != null ? oldUser.getTenantId() : null;
|
||||
Assert.isTrue(count == 0, "该租户下用户名已存在");
|
||||
|
||||
// form -> entity
|
||||
User entity = userConverter.toEntity(userForm);
|
||||
entity.setUpdateBy(SecurityUtils.getUserId());
|
||||
|
||||
// 保持租户ID不变(不允许跨租户修改用户)
|
||||
entity.setTenantId(oldTenantId);
|
||||
|
||||
// 修改用户
|
||||
boolean result = this.updateById(entity);
|
||||
@@ -186,23 +202,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
if (result) {
|
||||
// 保存用户角色
|
||||
userRoleService.saveUserRoles(entity.getId(), userForm.getRoleIds());
|
||||
|
||||
// 如果启用多租户且租户发生变更,更新用户租户关联
|
||||
if (Boolean.TRUE.equals(tenantProperties.getEnabled())) {
|
||||
Long newTenantId = entity.getTenantId();
|
||||
if (newTenantId != null && !newTenantId.equals(oldTenantId)) {
|
||||
// 删除旧的租户关联
|
||||
if (oldTenantId != null) {
|
||||
userTenantMapper.delete(
|
||||
new LambdaQueryWrapper<com.youlai.boot.system.model.entity.UserTenant>()
|
||||
.eq(com.youlai.boot.system.model.entity.UserTenant::getUserId, userId)
|
||||
.eq(com.youlai.boot.system.model.entity.UserTenant::getTenantId, oldTenantId)
|
||||
);
|
||||
}
|
||||
// 保存新的租户关联
|
||||
saveUserTenantRelation(userId, newTenantId, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -224,16 +223,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
|
||||
boolean result = this.removeByIds(ids);
|
||||
|
||||
// 如果启用多租户,删除用户租户关联
|
||||
if (result && Boolean.TRUE.equals(tenantProperties.getEnabled())) {
|
||||
for (Long userId : ids) {
|
||||
userTenantMapper.delete(
|
||||
new LambdaQueryWrapper<com.youlai.boot.system.model.entity.UserTenant>()
|
||||
.eq(com.youlai.boot.system.model.entity.UserTenant::getUserId, userId)
|
||||
);
|
||||
log.info("删除用户租户关联:userId={}", userId);
|
||||
}
|
||||
}
|
||||
// 新设计:用户删除时,tenant_id 字段会随用户记录一起逻辑删除,无需额外处理
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -256,6 +246,46 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
return userAuthCredentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserAuthCredentials getAuthCredentialsByUsernameAndTenant(String username, Long tenantId) {
|
||||
// 临时忽略租户过滤,查询指定租户下的用户
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
// 先查询用户
|
||||
User user = this.getOne(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getTenantId, tenantId)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
// 设置租户上下文,然后查询认证信息(这样会包含该租户下的角色)
|
||||
TenantContextHolder.setTenantId(tenantId);
|
||||
return getAuthCredentialsByUsername(username);
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> listUsersByUsername(String username) {
|
||||
// 临时忽略租户过滤,查询该用户名在所有租户下的记录
|
||||
TenantContextHolder.setIgnoreTenant(true);
|
||||
try {
|
||||
return this.list(
|
||||
new LambdaQueryWrapper<User>()
|
||||
.eq(User::getUsername, username)
|
||||
.eq(User::getIsDeleted, 0)
|
||||
.orderByAsc(User::getTenantId) // 按租户ID排序,优先返回较小的租户ID
|
||||
);
|
||||
} finally {
|
||||
TenantContextHolder.setIgnoreTenant(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据OpenID获取用户认证信息
|
||||
*
|
||||
@@ -731,45 +761,5 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
return userConverter.toOptions(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存用户租户关联关系
|
||||
* <p>
|
||||
* 仅在启用多租户时调用此方法
|
||||
* </p>
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param tenantId 租户ID
|
||||
* @param isDefault 是否为默认租户
|
||||
*/
|
||||
private void saveUserTenantRelation(Long userId, Long tenantId, boolean isDefault) {
|
||||
if (userId == null || tenantId == null) {
|
||||
log.warn("用户ID或租户ID为空,跳过保存用户租户关联");
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查关联是否已存在
|
||||
com.youlai.boot.system.model.entity.UserTenant existingRelation = userTenantMapper.selectOne(
|
||||
new LambdaQueryWrapper<com.youlai.boot.system.model.entity.UserTenant>()
|
||||
.eq(com.youlai.boot.system.model.entity.UserTenant::getUserId, userId)
|
||||
.eq(com.youlai.boot.system.model.entity.UserTenant::getTenantId, tenantId)
|
||||
);
|
||||
|
||||
if (existingRelation != null) {
|
||||
// 如果已存在,更新 is_default 标识
|
||||
if (isDefault && existingRelation.getIsDefault() != 1) {
|
||||
existingRelation.setIsDefault(1);
|
||||
userTenantMapper.updateById(existingRelation);
|
||||
log.info("更新用户租户关联:userId={}, tenantId={}, isDefault=true", userId, tenantId);
|
||||
}
|
||||
} else {
|
||||
// 不存在则新增
|
||||
com.youlai.boot.system.model.entity.UserTenant userTenant = new com.youlai.boot.system.model.entity.UserTenant();
|
||||
userTenant.setUserId(userId);
|
||||
userTenant.setTenantId(tenantId);
|
||||
userTenant.setIsDefault(isDefault ? 1 : 0);
|
||||
userTenantMapper.insert(userTenant);
|
||||
log.info("保存用户租户关联:userId={}, tenantId={}, isDefault={}", userId, tenantId, isDefault);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user