feat(tenant): 实现多租户功能支持

This commit is contained in:
Ray.Hao
2025-12-10 21:14:37 +08:00
parent f16c1e6227
commit 329b3551f7
17 changed files with 1787 additions and 0 deletions

View File

@@ -0,0 +1,110 @@
package com.youlai.boot.system.controller;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.core.web.Result;
import com.youlai.boot.security.util.SecurityUtils;
import com.youlai.boot.system.model.vo.TenantVO;
import com.youlai.boot.system.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 租户管理控制器
* <p>
* 提供租户切换、查询等功能
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Tag(name = "租户管理接口")
@RestController
@RequestMapping("/api/v1/tenant")
@RequiredArgsConstructor
@Slf4j
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantController {
private final TenantService tenantService;
/**
* 获取当前用户的租户列表
* <p>
* 根据当前登录用户查询其所属的所有租户
* </p>
*
* @return 租户列表
*/
@Operation(summary = "获取当前用户的租户列表")
@GetMapping("/list")
public Result<List<TenantVO>> getTenantList() {
Long userId = SecurityUtils.getUserId();
List<TenantVO> tenantList = tenantService.getTenantListByUserId(userId);
log.info("获取用户 {} 的租户列表,共 {} 个租户", userId, tenantList.size());
return Result.success(tenantList);
}
/**
* 获取当前租户信息
*
* @return 当前租户信息
*/
@Operation(summary = "获取当前租户信息")
@GetMapping("/current")
public Result<TenantVO> getCurrentTenant() {
Long tenantId = TenantContextHolder.getTenantId();
if (tenantId == null) {
return Result.success(null);
}
TenantVO tenant = tenantService.getTenantById(tenantId);
return Result.success(tenant);
}
/**
* 切换租户
* <p>
* 切换当前用户的租户上下文,需要验证用户是否有权限访问该租户
* </p>
*
* @param tenantId 目标租户ID
* @return 切换结果
*/
@Operation(summary = "切换租户")
@PostMapping("/switch/{tenantId}")
public Result<TenantVO> switchTenant(
@Parameter(description = "租户ID") @PathVariable Long tenantId
) {
Long userId = SecurityUtils.getUserId();
log.info("用户 {} 请求切换租户到 {}", userId, tenantId);
// 验证用户是否有权限访问该租户
boolean hasPermission = tenantService.hasTenantPermission(userId, tenantId);
if (!hasPermission) {
log.warn("用户 {} 无权限访问租户 {}", userId, tenantId);
return Result.failed("无权限访问该租户");
}
// 验证租户是否存在且正常
TenantVO tenant = tenantService.getTenantById(tenantId);
if (tenant == null) {
return Result.failed("租户不存在");
}
if (tenant.getStatus() == null || tenant.getStatus() != 1) {
return Result.failed("租户已禁用");
}
// 设置新的租户上下文
TenantContextHolder.setTenantId(tenantId);
log.info("用户 {} 成功切换租户到 {}", userId, tenantId);
return Result.success(tenant);
}
}

View File

@@ -0,0 +1,16 @@
package com.youlai.boot.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.boot.system.model.entity.Tenant;
import org.apache.ibatis.annotations.Mapper;
/**
* 租户 Mapper
*
* @author Ray.Hao
* @since 3.0.0
*/
@Mapper
public interface TenantMapper extends BaseMapper<Tenant> {
}

View File

@@ -0,0 +1,16 @@
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> {
}

View File

@@ -0,0 +1,71 @@
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;
import java.time.LocalDateTime;
/**
* 租户实体
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_tenant")
public class Tenant extends BaseEntity {
/**
* 租户名称
*/
private String name;
/**
* 租户编码(唯一)
*/
private String code;
/**
* 联系人姓名
*/
private String contactName;
/**
* 联系人电话
*/
private String contactPhone;
/**
* 联系人邮箱
*/
private String contactEmail;
/**
* 租户域名(用于域名识别)
*/
private String domain;
/**
* 租户Logo
*/
private String logo;
/**
* 状态(1-正常 0-禁用)
*/
private Integer status;
/**
* 备注
*/
private String remark;
/**
* 过期时间NULL表示永不过期
*/
private LocalDateTime expireTime;
}

View File

@@ -0,0 +1,34 @@
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;
}

View File

@@ -0,0 +1,48 @@
package com.youlai.boot.system.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 租户VO
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@Schema(description = "租户信息")
public class TenantVO implements Serializable {
@Schema(description = "租户ID")
private Long id;
@Schema(description = "租户名称")
private String name;
@Schema(description = "租户编码")
private String code;
@Schema(description = "租户状态(1-正常 0-禁用)")
private Integer status;
@Schema(description = "联系人姓名")
private String contactName;
@Schema(description = "联系人电话")
private String contactPhone;
@Schema(description = "联系人邮箱")
private String contactEmail;
@Schema(description = "租户域名")
private String domain;
@Schema(description = "租户Logo")
private String logo;
@Schema(description = "是否默认租户")
private Boolean isDefault;
}

View File

@@ -0,0 +1,50 @@
package com.youlai.boot.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.youlai.boot.system.model.entity.Tenant;
import com.youlai.boot.system.model.vo.TenantVO;
import java.util.List;
/**
* 租户服务接口
*
* @author Ray.Hao
* @since 3.0.0
*/
public interface TenantService extends IService<Tenant> {
/**
* 根据用户ID查询用户所属的租户列表
*
* @param userId 用户ID
* @return 租户列表
*/
List<TenantVO> getTenantListByUserId(Long userId);
/**
* 根据租户ID查询租户信息
*
* @param tenantId 租户ID
* @return 租户信息
*/
TenantVO getTenantById(Long tenantId);
/**
* 根据域名查询租户ID
*
* @param domain 域名
* @return 租户ID
*/
Long getTenantIdByDomain(String domain);
/**
* 验证用户是否有权限访问指定租户
*
* @param userId 用户ID
* @param tenantId 租户ID
* @return true-有权限false-无权限
*/
boolean hasTenantPermission(Long userId, Long tenantId);
}

View File

@@ -0,0 +1,125 @@
package com.youlai.boot.system.service.impl;
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.UserTenantMapper;
import com.youlai.boot.system.model.entity.Tenant;
import com.youlai.boot.system.model.entity.UserTenant;
import com.youlai.boot.system.model.vo.TenantVO;
import com.youlai.boot.system.service.TenantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* 租户服务实现类
*
* @author Ray.Hao
* @since 3.0.0
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
private final UserTenantMapper userTenantMapper;
@Override
public List<TenantVO> getTenantListByUserId(Long userId) {
// 临时忽略租户过滤,查询所有租户
TenantContextHolder.setIgnoreTenant(true);
try {
// 查询用户关联的租户ID列表
List<UserTenant> userTenants = userTenantMapper.selectList(
new LambdaQueryWrapper<UserTenant>()
.eq(UserTenant::getUserId, userId)
);
if (userTenants.isEmpty()) {
return List.of();
}
// 提取租户ID列表
List<Long> tenantIds = userTenants.stream()
.map(UserTenant::getTenantId)
.collect(Collectors.toList());
// 查询租户信息
List<Tenant> tenants = this.list(
new LambdaQueryWrapper<Tenant>()
.in(Tenant::getId, tenantIds)
.eq(Tenant::getStatus, 1) // 只查询正常状态的租户
.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());
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
public TenantVO getTenantById(Long tenantId) {
TenantContextHolder.setIgnoreTenant(true);
try {
Tenant tenant = this.getById(tenantId);
if (tenant == null) {
return null;
}
TenantVO vo = new TenantVO();
BeanUtils.copyProperties(tenant, vo);
return vo;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
public Long getTenantIdByDomain(String domain) {
TenantContextHolder.setIgnoreTenant(true);
try {
Tenant tenant = this.getOne(
new LambdaQueryWrapper<Tenant>()
.eq(Tenant::getDomain, domain)
.eq(Tenant::getStatus, 1)
.last("LIMIT 1")
);
return tenant != null ? tenant.getId() : null;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
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)
.last("LIMIT 1")
);
return userTenant != null;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
}