package cn.iocoder.yudao.module.system.framework.agent;
|
|
import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService;
|
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
|
import jakarta.annotation.Resource;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.http.HttpStatus;
|
import org.springframework.stereotype.Component;
|
|
import java.nio.charset.StandardCharsets;
|
import java.security.MessageDigest;
|
|
/** 桥接统一鉴权:服务令牌 + 当前登录用户 + 业务权限,缺一不可。 */
|
@Component
|
public class SystemAgentBridgeGuard {
|
|
public static final String PERMISSION_ITEM_IMPORT = "mdm:item:import";
|
|
@Value("${yudao.agent.bridge-service-token:}")
|
private String bridgeServiceToken;
|
|
@Resource
|
private SecurityFrameworkService securityFrameworkService;
|
|
public void verifyServiceToken(String provided) {
|
if (bridgeServiceToken == null || bridgeServiceToken.isBlank() || provided == null
|
|| !MessageDigest.isEqual(bridgeServiceToken.getBytes(StandardCharsets.UTF_8),
|
provided.getBytes(StandardCharsets.UTF_8))) {
|
throw new AgentBridgeException(HttpStatus.FORBIDDEN, "SERVICE_TOKEN_INVALID",
|
"智能体服务身份无效,请检查服务密钥配置");
|
}
|
}
|
|
public AgentPrincipal require(String providedServiceToken, String permission) {
|
verifyServiceToken(providedServiceToken);
|
Long userId = SecurityFrameworkUtils.getLoginUserId();
|
if (userId == null) {
|
throw new AgentBridgeException(HttpStatus.UNAUTHORIZED, "UNAUTHORIZED", "未登录或登录已过期");
|
}
|
if (!securityFrameworkService.hasPermission(permission)) {
|
throw new AgentBridgeException(HttpStatus.FORBIDDEN, "FORBIDDEN",
|
"当前用户缺少物料导入权限(" + permission + ")");
|
}
|
Long tenantId = TenantContextHolder.getTenantId();
|
return new AgentPrincipal(userId, tenantId == null ? 0L : tenantId, "live");
|
}
|
}
|