mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
wip: 可能基本完成的开放模块
This commit is contained in:
@@ -0,0 +1,472 @@
|
||||
# 开放接口模块设计说明
|
||||
|
||||
## 1. 概述
|
||||
|
||||
### 1.1 背景
|
||||
|
||||
Ecom-DMB 内部接口基于 **JWT + RBAC**(`@RequirePermission`),面向 Web 前端。随着外部系统对接、AI Agent 集成等需求,需要对外开放部分能力,且调用方使用 **公司级 API Key**,无需维护用户账号。
|
||||
|
||||
### 1.2 核心设计决策:路由前缀区分身份
|
||||
|
||||
**推荐方案**:不改造现有 `/ec/*` 接口的认证逻辑,也不在同一 URL 上混用 JWT 与 API Key;而是在内部路径前增加 **`/open/v1` 前缀**,形成与内部接口 **一一镜像** 的开放路由,底层 **复用同一套 Service**。
|
||||
|
||||
```
|
||||
内部(JWT) POST /ec/order/batch-import
|
||||
开放(API Key) POST /open/v1/ec/order/batch-import
|
||||
└─ 前缀 ─┘└──── 与内部相同的路径 ────┘
|
||||
```
|
||||
|
||||
| 路径前缀 | 认证方式 | 授权 | 调用方 |
|
||||
|----------|----------|------|--------|
|
||||
| `/ec/*`、`/user/*`、`/auth/*`(除 login 等) | JWT | `@RequirePermission` + 岗位 | Web 前端 |
|
||||
| `/open/v1/*` | API Key | `@RequireOpenScope` + Key scopes | 外部系统、Agent |
|
||||
| `/sys/open-api-key/*` | JWT | 公司拥有者 / 超管 | 管理端配置 Key |
|
||||
|
||||
**好处**:
|
||||
|
||||
- 安全边界清晰:`/open/**` 只认 Key,`/ec/**` 只认 JWT,互不干扰
|
||||
- 路径语义对齐:看到 `/open/v1/ec/order/...` 即知对应内部 `/ec/order/...`
|
||||
- 业务零重复:Open Controller 薄封装,直接调现有 Service
|
||||
- 按需开放:只有实现了 Open Controller 的路径才对外,不会误暴露整个 `/ec/*`
|
||||
|
||||
### 1.3 目标与非目标
|
||||
|
||||
**目标**
|
||||
|
||||
| 目标 | 说明 |
|
||||
|------|------|
|
||||
| 前缀隔离身份 | `/open/v1` 与 `/ec` 分路认证 |
|
||||
| 镜像内部路径 | 开放 URL = `/open/v1` + 内部业务路径 |
|
||||
| 复用 Service | Facade 委托 `ecom`、`sys` 模块,不复制业务规则 |
|
||||
| Agent 友好 | 字段元数据、稳定版本、明确错误码 |
|
||||
|
||||
**非目标(首版)**
|
||||
|
||||
- 不在现有 `/ec/*` URL 上叠加 API Key 校验
|
||||
- 不替代 Web 端文件导入(`/ec/import-task`)流程
|
||||
- 不提供 OAuth2(后续可扩展)
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ 调用方 │
|
||||
└──────────────┬──────────────────────────┘
|
||||
│
|
||||
┌────────────────────┴────────────────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
Authorization: Bearer <JWT> Authorization: Bearer sk_live_xxx
|
||||
│ │
|
||||
▼ ▼
|
||||
/ec/order/batch-import /open/v1/ec/order/batch-import
|
||||
/ec/promotion-fee/... /open/v1/ec/promotion-fee/...
|
||||
│ │
|
||||
▼ ▼
|
||||
JwtAuthenticationFilter ApiKeyAuthenticationFilter
|
||||
@RequirePermission @RequireOpenScope
|
||||
│ │
|
||||
└────────────────────┬────────────────────┘
|
||||
▼
|
||||
OrderService / PromotionFeeService / ...
|
||||
(company_id 数据隔离,规则唯一)
|
||||
```
|
||||
|
||||
### 2.1 模块目录
|
||||
|
||||
```
|
||||
modules/open/
|
||||
├── api/ # 开放业务入口(镜像 /ec/* 等)
|
||||
│ ├── controller/
|
||||
│ │ ├── OpenOrderController # @RequestMapping("/open/v1/ec/order")
|
||||
│ │ ├── OpenPromotionFeeController
|
||||
│ │ ├── OpenMetaController # @RequestMapping("/open/v1/ec/meta") 或分散到各模块
|
||||
│ │ └── OpenImportTaskController
|
||||
│ ├── filter/ApiKeyAuthenticationFilter
|
||||
│ ├── context/OpenApiContext
|
||||
│ ├── annotation/@RequireOpenScope
|
||||
│ ├── aspect/OpenScopeAspect, OpenApiAuditAspect
|
||||
│ ├── model/dto|vo # 开放专用 DTO(如 snake_case),可选
|
||||
│ └── service/ # Facade:DTO 转换 + 调 ecom Service
|
||||
├── key/ # API Key 管理(JWT 保护)
|
||||
│ ├── controller/ # /sys/open-api-key/*
|
||||
│ ├── service/
|
||||
│ └── model/po|dto|vo
|
||||
└── audit/ # 调用日志(二期)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 路由与镜像规则
|
||||
|
||||
### 3.1 路径公式
|
||||
|
||||
```
|
||||
开放路径 = /open/{version} + 内部业务路径
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
| 内部路径(JWT) | 开放路径(API Key) | 说明 |
|
||||
|-----------------|---------------------|------|
|
||||
| `POST /ec/order/batch-import` | `POST /open/v1/ec/order/batch-import` | 订单 JSON 批量导入 |
|
||||
| `GET /ec/order/fields` | `GET /open/v1/ec/order/fields` | 订单导入字段元数据 |
|
||||
| `GET /ec/promotion-fee/fields` | `GET /open/v1/ec/promotion-fee/fields` | 推广费字段元数据 |
|
||||
| `POST /ec/promotion-fee`(或专用 batch) | `POST /open/v1/ec/promotion-fee/batch-import` | 推广费批量导入(开放专用子路径) |
|
||||
| `GET /ec/import-task/detail/{id}` | `GET /open/v1/ec/import-task/detail/{id}` | 导入任务状态(二期) |
|
||||
| `GET /ec/shop/list`(内部 POST list) | `POST /open/v1/ec/shop/list` | 店铺元数据(按需镜像) |
|
||||
|
||||
**说明**:
|
||||
|
||||
- 默认 **严格镜像** 内部 `@RequestMapping` + 方法路径
|
||||
- 若开放场景需要略有差异(如增加 `batch-import` 而内部只有 `batch-import` 已有则完全同名),在 Open Controller 中单独定义,但仍保持在 `/open/v1/ec/...` 树下
|
||||
- 版本升级:`/open/v2/ec/...`,内部 `/ec/...` 可继续演进
|
||||
|
||||
### 3.2 Controller 写法示例
|
||||
|
||||
内部(现有,不改动):
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/ec/order")
|
||||
public class OrderController {
|
||||
@PostMapping("/batch-import")
|
||||
@RequirePermission(value = "ecom:order:import", allowSuper = true)
|
||||
public ApiResponse<BatchImportResultVO> batchImportOrders(...) { }
|
||||
}
|
||||
```
|
||||
|
||||
开放(新增,薄封装):
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/open/v1/ec/order")
|
||||
@Tag(name = "开放接口-订单", description = "API Key 认证,镜像 /ec/order")
|
||||
public class OpenOrderController {
|
||||
|
||||
private final OpenOrderFacade openOrderFacade;
|
||||
|
||||
@PostMapping("/batch-import")
|
||||
@RequireOpenScope("order:import")
|
||||
public ApiResponse<BatchImportResultVO> batchImportOrders(
|
||||
@Valid @RequestBody OpenBatchImportOrderDTO dto) {
|
||||
return ApiResponse.success("批量导入订单成功",
|
||||
openOrderFacade.batchImportOrders(dto));
|
||||
}
|
||||
|
||||
@GetMapping("/fields")
|
||||
@RequireOpenScope("order:read")
|
||||
public ApiResponse<List<OrderFieldVO>> getOrderFieldDefs() {
|
||||
return ApiResponse.success("获取订单字段成功",
|
||||
openOrderFacade.getOrderFieldDefs());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Facade 内部:
|
||||
|
||||
```java
|
||||
public BatchImportResultVO batchImportOrders(OpenBatchImportOrderDTO openDto) {
|
||||
Long companyId = openApiContext.getCompanyId();
|
||||
Long operatorId = openApiContext.getOperatorUserId(); // Key 创建人
|
||||
BatchImportOrderDTO internal = openOrderConverter.toInternal(openDto);
|
||||
return orderService.batchImportOrdersForOpen(internal, companyId, operatorId);
|
||||
}
|
||||
```
|
||||
|
||||
若现有 `OrderService.batchImportOrders` 强依赖 `CurrentUserContext`,可在 Facade 层注入 companyId/operatorId,或短期内在 Open 请求线程内 **临时填充** `CurrentUserContext`(仅 `/open/**` 过滤器链内生效),避免大范围改 Service。
|
||||
|
||||
---
|
||||
|
||||
## 4. 认证与授权
|
||||
|
||||
### 4.1 双过滤器,各管一路
|
||||
|
||||
```
|
||||
请求进入
|
||||
│
|
||||
├─ URI 以 /open/ 开头 ──► ApiKeyAuthenticationFilter
|
||||
│ ├─ 有有效 API Key → 注入 OpenApiContext,继续
|
||||
│ ├─ 带 JWT 无 Key → 401(开放路由不接受 JWT)
|
||||
│ └─ 无 Key → 401
|
||||
│
|
||||
└─ 其他路径 ──► JwtAuthenticationFilter(现有)
|
||||
├─ 有效 JWT → 继续
|
||||
├─ 仅 API Key 无 JWT → 401(内部路由不接受 Key)
|
||||
└─ 无认证 → 401(除 permitAll 的 login/register/refresh)
|
||||
```
|
||||
|
||||
**关键约束**:
|
||||
|
||||
- **禁止**在 `/ec/order/batch-import` 上同时接受 JWT 和 API Key
|
||||
- **禁止**API Key 访问未实现 Open Controller 的内部路径(Spring 只映射已声明的 Handler)
|
||||
|
||||
### 4.2 API Key
|
||||
|
||||
**请求头**(二选一):
|
||||
|
||||
```http
|
||||
Authorization: Bearer sk_live_xxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
```http
|
||||
X-Api-Key: sk_live_xxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
Key 格式:`sk_{env}_{random}`,`env` = `live` | `test`。
|
||||
|
||||
### 4.3 数据表 `open_api_key`
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint | 主键 |
|
||||
| company_id | bigint | 绑定公司,开放请求固定此 companyId |
|
||||
| name | varchar | 备注名,如「Agent-订单导入」 |
|
||||
| key_prefix | varchar | 展示用前缀 `sk_live_abcd****` |
|
||||
| key_hash | varchar | 完整 Key 哈希,明文仅创建时返回一次 |
|
||||
| scopes | json | 权限范围列表 |
|
||||
| status | tinyint | 0=停用 1=正常 |
|
||||
| expire_at | datetime | 可选过期 |
|
||||
| ip_whitelist | json | 可选 IP/CIDR |
|
||||
| rate_limit | int | 每分钟上限,默认 60 |
|
||||
| create_by | bigint | 创建人,作 `create_by` 操作者 |
|
||||
| create_time / update_time | datetime | 审计 |
|
||||
|
||||
### 4.4 Scope 与内部权限映射
|
||||
|
||||
开放路由 **不使用** `@RequirePermission`,而用 `@RequireOpenScope`;Scope 与内部能力对应关系:
|
||||
|
||||
| Scope | 可访问的开放路由(镜像) | 委托 Service |
|
||||
|-------|--------------------------|--------------|
|
||||
| `order:import` | `POST /open/v1/ec/order/batch-import` | `OrderService` |
|
||||
| `order:read` | `GET /open/v1/ec/order/fields` | `OrderFieldConstants` |
|
||||
| `promotion_fee:import` | `POST /open/v1/ec/promotion-fee/batch-import` | 推广费写入逻辑 |
|
||||
| `promotion_fee:read` | `GET /open/v1/ec/promotion-fee/fields` | `PromotionFeeFieldConstants` |
|
||||
| `import_task:read` | `GET /open/v1/ec/import-task/detail/{id}` | `ImportTaskService` |
|
||||
| `meta:read` | `POST /open/v1/ec/shop/list` 等元数据 | `ShopService` 等 |
|
||||
| `brush_order:import` | `POST /open/v1/ec/brush-order/batch-import`(二期) | `BrushOrderService` |
|
||||
|
||||
### 4.5 OpenApiContext
|
||||
|
||||
```java
|
||||
public interface OpenApiContext {
|
||||
Long getCompanyId(); // 来自 Key 绑定
|
||||
Long getApiKeyId();
|
||||
Set<String> getScopes();
|
||||
Long getOperatorUserId(); // Key.create_by,写入 create_by
|
||||
String getClientName(); // Key.name,审计用
|
||||
boolean isOpenApiRequest(); // 恒 true(仅在 /open 链内注入)
|
||||
}
|
||||
```
|
||||
|
||||
`CurrentUserContext` 在 `/open/**` 请求中可委托给 `OpenApiContext`,使未改造的 Service 仍能通过 `getCurrentCompanyId()` 工作;**禁止**在开放链中依赖 `getCurrentUserRole()` / 岗位权限。
|
||||
|
||||
### 4.6 SecurityConfig
|
||||
|
||||
```java
|
||||
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
|
||||
.requestMatchers("/open/**").authenticated() // 由 ApiKey Filter 注入 Authentication
|
||||
.anyRequest().authenticated() // 由 Jwt Filter 注入
|
||||
```
|
||||
|
||||
过滤器顺序:
|
||||
|
||||
```java
|
||||
.addFilterBefore(apiKeyAuthenticationFilter, JwtAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
```
|
||||
|
||||
ApiKey Filter 对非 `/open/**` 请求 **直接放行**(不解析 Key);Jwt Filter 对 `/open/**` 请求 **跳过**(不解析 JWT)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 请求 / 响应约定
|
||||
|
||||
### 5.1 响应格式
|
||||
|
||||
与内部一致,使用 `ApiResponse<T>`。
|
||||
|
||||
### 5.2 开放 DTO 命名(可选)
|
||||
|
||||
面向 Agent 时,Open DTO 字段可用 **snake_case**,Facade 转为内部 camelCase DTO:
|
||||
|
||||
```json
|
||||
POST /open/v1/ec/order/batch-import
|
||||
{
|
||||
"shop_id": 1,
|
||||
"orders": [
|
||||
{
|
||||
"platform_order_no": "TB202401010001",
|
||||
"spec_code": "SKU-001",
|
||||
"received_amount": 99.00,
|
||||
"product_quantity": 1,
|
||||
"order_time": "2024-01-01T10:00:00",
|
||||
"status": "已完成"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
响应可直接复用 `BatchImportResultVO`(与内部 `/ec/order/batch-import` 相同结构),降低集成成本。
|
||||
|
||||
### 5.3 错误码
|
||||
|
||||
| code | 含义 |
|
||||
|------|------|
|
||||
| 40101 | API Key 无效或缺失 |
|
||||
| 40102 | API Key 已过期或停用 |
|
||||
| 40301 | Scope 不足 |
|
||||
| 42901 | 触发限流 |
|
||||
| 5xxxx | 业务错误(与内部 BusinessException 一致) |
|
||||
|
||||
### 5.4 追踪
|
||||
|
||||
- 响应头:`X-Request-Id`
|
||||
- 二期:请求头 `X-Idempotency-Key` 支持幂等
|
||||
|
||||
---
|
||||
|
||||
## 6. 一期接口清单
|
||||
|
||||
### 6.1 订单
|
||||
|
||||
| 方法 | 开放路径 | 内部镜像 | Scope |
|
||||
|------|----------|----------|-------|
|
||||
| GET | `/open/v1/ec/order/fields` | `/ec/order/fields` | `order:read` |
|
||||
| POST | `/open/v1/ec/order/batch-import` | `/ec/order/batch-import` | `order:import` |
|
||||
|
||||
### 6.2 推广费
|
||||
|
||||
| 方法 | 开放路径 | 内部镜像 | Scope |
|
||||
|------|----------|----------|-------|
|
||||
| GET | `/open/v1/ec/promotion-fee/fields` | `/ec/promotion-fee/fields` | `promotion_fee:read` |
|
||||
| POST | `/open/v1/ec/promotion-fee/batch-import` | 新增开放批量入口 | `promotion_fee:import` |
|
||||
|
||||
> 内部若尚无批量 JSON 导入,Facade 抽取 `PromotionFeeImportProcessor` 核心写入逻辑为 Service 方法,供 Open 与文件导入共用。
|
||||
|
||||
### 6.3 元数据(Agent 辅助)
|
||||
|
||||
| 方法 | 开放路径 | Scope |
|
||||
|------|----------|-------|
|
||||
| POST | `/open/v1/ec/shop/list` | `meta:read` |
|
||||
| POST | `/open/v1/ec/order-status/list` | `meta:read` |
|
||||
| POST | `/open/v1/ec/promotion-fee-type/list` | `meta:read` |
|
||||
|
||||
路径镜像内部 list 接口;若内部为 POST `/list`,开放层同样 POST。
|
||||
|
||||
### 6.4 导入任务(可选,一期末尾)
|
||||
|
||||
| 方法 | 开放路径 | 内部镜像 | Scope |
|
||||
|------|----------|----------|-------|
|
||||
| GET | `/open/v1/ec/import-task/detail/{id}` | 对齐内部 detail | `import_task:read` |
|
||||
|
||||
---
|
||||
|
||||
## 7. API Key 管理(JWT 保护,非开放)
|
||||
|
||||
| 方法 | 路径 | 权限 |
|
||||
|------|------|------|
|
||||
| POST | `/sys/open-api-key/create` | 公司拥有者 / 超管 |
|
||||
| GET | `/sys/open-api-key/list` | 同上 |
|
||||
| PUT | `/sys/open-api-key/{id}/disable` | 同上 |
|
||||
| DELETE | `/sys/open-api-key/{id}` | 同上 |
|
||||
|
||||
创建响应 **仅一次** 返回明文 Key;列表只显示 `key_prefix` 与 scopes。
|
||||
|
||||
---
|
||||
|
||||
## 8. 审计与限流
|
||||
|
||||
### 8.1 访问日志 `open_api_access_log`
|
||||
|
||||
记录:api_key_id、company_id、method、path(完整 `/open/v1/ec/...`)、request_id、status、duration_ms、ip、error_message。
|
||||
|
||||
### 8.2 限流
|
||||
|
||||
- Key 级:`rate_limit` 字段,Redis 滑动窗口
|
||||
- 仅对 `/open/**` 生效,不影响 JWT 路由
|
||||
|
||||
---
|
||||
|
||||
## 9. 安全要求
|
||||
|
||||
1. HTTPS 必须
|
||||
2. Key 只存哈希;`/open/**` 拒绝 JWT,`/ec/**` 拒绝 API Key
|
||||
3. 所有写操作 `company_id` 必须来自 Key,忽略请求体中的 company_id
|
||||
4. 单次批量上限(如 1000 条)可配置
|
||||
5. 可选 IP 白名单
|
||||
6. Knife4j 分两组文档:「电商-内部」「开放接口-v1(镜像路径说明)」
|
||||
|
||||
---
|
||||
|
||||
## 10. 实现步骤
|
||||
|
||||
### Phase 1 — 框架(约 1 周)
|
||||
|
||||
- [ ] 表 `open_api_key` + `/sys/open-api-key/*` 管理 CRUD
|
||||
- [ ] `ApiKeyAuthenticationFilter`(仅处理 `/open/**`)
|
||||
- [ ] 调整 `JwtAuthenticationFilter` 跳过 `/open/**`
|
||||
- [ ] `OpenApiContext` + `@RequireOpenScope` + Aspect
|
||||
- [ ] `CurrentUserContext` 在开放链下的适配(companyId / operatorUserId)
|
||||
- [ ] SecurityConfig 过滤器顺序
|
||||
- [ ] Knife4j 开放分组
|
||||
|
||||
### Phase 2 — 镜像 Controller(约 1 周)
|
||||
|
||||
- [ ] `OpenOrderController` → `/open/v1/ec/order/*`
|
||||
- [ ] `OpenPromotionFeeController` → `/open/v1/ec/promotion-fee/*`
|
||||
- [ ] `OpenMetaController` 或分散元数据镜像
|
||||
- [ ] Facade + Converter + 集成测试(公司隔离、Scope 校验)
|
||||
|
||||
### Phase 3 — 可观测(约 0.5 周)
|
||||
|
||||
- [ ] 访问审计、限流
|
||||
- [ ] 导入任务 detail 镜像
|
||||
|
||||
### Phase 4 — 扩展
|
||||
|
||||
- [ ] 刷单 / 商品镜像路由
|
||||
- [ ] `/open/v2` Breaking Change 通道
|
||||
- [ ] Webhook、幂等键
|
||||
|
||||
---
|
||||
|
||||
## 11. Agent 集成示例
|
||||
|
||||
```text
|
||||
1. GET /open/v1/ec/order/fields → 了解必填字段
|
||||
2. POST /open/v1/ec/shop/list → 获取 shop_id
|
||||
3. POST /open/v1/ec/order-status/list → 解析 status 名称
|
||||
4. POST /open/v1/ec/order/batch-import → 提交 JSON
|
||||
5. 根据 failure_records 修正失败行并重试
|
||||
```
|
||||
|
||||
所有请求携带:
|
||||
|
||||
```http
|
||||
Authorization: Bearer sk_live_xxxx
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. 附录:路径镜像速查
|
||||
|
||||
| 开放路径 | 内部路径 | Facade 委托 |
|
||||
|----------|----------|-------------|
|
||||
| `POST /open/v1/ec/order/batch-import` | `POST /ec/order/batch-import` | `OrderService.batchImportOrders` |
|
||||
| `GET /open/v1/ec/order/fields` | `GET /ec/order/fields` | `OrderFieldConstants.FIELDS` |
|
||||
| `GET /open/v1/ec/promotion-fee/fields` | `GET /ec/promotion-fee/fields` | `PromotionFeeFieldConstants.FIELDS` |
|
||||
| `POST /open/v1/ec/promotion-fee/batch-import` | (Facade 新增) | 推广费批量写入 |
|
||||
| `GET /open/v1/ec/import-task/detail/{id}` | 对齐内部 | `ImportTaskService` |
|
||||
|
||||
---
|
||||
|
||||
## 13. 修订记录
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
|------|------|------|
|
||||
| v0.1 | 2026-05-24 | 初稿:独立 `/open/v1` 资源路径 |
|
||||
| v0.2 | 2026-05-24 | 重构:**路由前缀区分身份**,开放路径镜像内部 `/ec/*`,双过滤器各管一路 |
|
||||
@@ -0,0 +1,59 @@
|
||||
-- ========================================
|
||||
-- 开放接口 API Key 模块
|
||||
-- 执行时间:2026-05-24
|
||||
-- 变更内容:
|
||||
-- 1. 新增 open_api_key 表
|
||||
-- 2. 新增 open:api-key:manage 权限
|
||||
-- 3. 新增「开放接口 / API Key 管理」菜单(需执行后为公司分配菜单)
|
||||
-- ========================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `open_api_key` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '绑定公司ID',
|
||||
`name` varchar(100) NOT NULL COMMENT 'Key名称/用途说明',
|
||||
`key_prefix` varchar(32) NOT NULL COMMENT 'Key前缀(展示用)',
|
||||
`key_hash` varchar(64) NOT NULL COMMENT 'Key SHA-256 哈希',
|
||||
`scopes` json NOT NULL COMMENT '权限范围 JSON 数组',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0=停用 1=正常',
|
||||
`expire_at` datetime DEFAULT NULL COMMENT '过期时间',
|
||||
`ip_whitelist` json DEFAULT NULL COMMENT 'IP白名单 JSON 数组,空表示不限制',
|
||||
`rate_limit` int NOT NULL DEFAULT 60 COMMENT '每分钟请求上限',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint unsigned DEFAULT NULL COMMENT '更新人ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_open_api_key_hash` (`key_hash`),
|
||||
KEY `idx_open_api_key_company` (`company_id`),
|
||||
KEY `idx_open_api_key_status` (`status`),
|
||||
CONSTRAINT `fk_open_api_key_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='开放接口 API Key';
|
||||
|
||||
-- 权限码
|
||||
INSERT INTO `sys_permission` (`code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 'open:api-key:manage', 'API Key管理', 'api', 1, '开放接口-API Key管理', 900
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:api-key:manage');
|
||||
|
||||
-- 菜单(catalog + menu)
|
||||
INSERT INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||
SELECT NULL, 0, 'OpenApi', '开放接口', '/open', 'BasicLayout', 'lucide:key-round', 'catalog', 1, 1, 900
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = 'OpenApi');
|
||||
|
||||
INSERT INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||
SELECT p.id, 0, 'OpenApiKeyManagement', 'API Key 管理', '/open/api-key', '/open/api-key/index', 'lucide:key', 'menu', 1, 1, 1
|
||||
FROM `sys_menu` p
|
||||
WHERE p.name = 'OpenApi'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = 'OpenApiKeyManagement');
|
||||
|
||||
-- 菜单-权限关联
|
||||
INSERT INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id
|
||||
FROM `sys_menu` m
|
||||
JOIN `sys_permission` p ON p.code = 'open:api-key:manage'
|
||||
WHERE m.name = 'OpenApiKeyManagement'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `sys_menu_permission` mp
|
||||
WHERE mp.menu_id = m.id AND mp.permission_id = p.id
|
||||
);
|
||||
@@ -0,0 +1,128 @@
|
||||
-- ========================================
|
||||
-- 开放接口 API Key 授权重构
|
||||
-- 执行时间:2026-05-25
|
||||
-- 前置:已执行 V20260524__open_api_key.sql
|
||||
-- 变更内容:
|
||||
-- 1. 新增 open:scope:* 开放能力权限(sys_permission)
|
||||
-- 2. 新增 open_api_key_permission,FK → org_company_permission
|
||||
-- 3. 将 open_api_key.scopes JSON 迁移至中间表
|
||||
-- 4. 删除 open_api_key.scopes 列
|
||||
--
|
||||
-- 旧 scope → 新 permission code:
|
||||
-- order:import → open:scope:order:import
|
||||
-- order:read → open:scope:order:read
|
||||
-- promotion_fee:import → open:scope:promotion_fee:import
|
||||
-- promotion_fee:read → open:scope:promotion_fee:read
|
||||
-- import_task:read → open:scope:import_task:read
|
||||
-- meta:read → open:scope:meta:read
|
||||
-- ========================================
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 1. 开放能力模块 + 权限码
|
||||
-- ----------------------------------------
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT NULL, 'MODULE:open', '开放接口', 'module', 1, '开放接口能力模块(API Key 可绑定权限)', 905
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'MODULE:open');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:order:import', '开放-订单导入', 'api', 1, 'POST /open/v1/ec/order/batch-import', 10
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:order:import');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:order:read', '开放-订单字段查询', 'api', 1, 'GET /open/v1/ec/order/fields', 20
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:order:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:promotion_fee:import', '开放-推广费导入', 'api', 1, 'POST /open/v1/ec/promotion-fee/batch-import', 30
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:promotion_fee:import');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:promotion_fee:read', '开放-推广费字段查询', 'api', 1, 'GET /open/v1/ec/promotion-fee/fields', 40
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:promotion_fee:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:import_task:read', '开放-导入任务查询', 'api', 1, 'GET /open/v1/ec/import-task/detail/{id}', 50
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:import_task:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT m.id, 'open:scope:meta:read', '开放-元数据查询', 'api', 1, 'shop/order-status/promotion-fee-type 等元数据', 60
|
||||
FROM `sys_permission` m
|
||||
WHERE m.code = 'MODULE:open'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'open:scope:meta:read');
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 2. 新增 Key ↔ 公司权限 中间表
|
||||
-- ----------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `open_api_key_permission` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`api_key_id` bigint unsigned NOT NULL COMMENT 'API Key ID',
|
||||
`company_permission_id` bigint unsigned NOT NULL COMMENT '公司权限关联ID(org_company_permission.id)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_open_api_key_company_permission` (`api_key_id`, `company_permission_id`),
|
||||
KEY `fk_open_api_key_permission_key` (`api_key_id`),
|
||||
KEY `fk_open_api_key_permission_company_perm` (`company_permission_id`),
|
||||
KEY `fk_open_api_key_permission_creator` (`create_by`),
|
||||
CONSTRAINT `fk_open_api_key_permission_key` FOREIGN KEY (`api_key_id`) REFERENCES `open_api_key` (`id`) ON DELETE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_permission_company_perm` FOREIGN KEY (`company_permission_id`) REFERENCES `org_company_permission` (`id`) ON DELETE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_permission_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='开放接口-API Key 与公司权限关联表';
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 3. 数据迁移(依赖 open_api_key.scopes 列,MySQL 8.0+)
|
||||
-- 3a. 按旧 JSON scopes 为公司补齐 org_company_permission
|
||||
-- 3b. 写入 open_api_key_permission
|
||||
-- 若 scopes 列已删除,请跳过本节
|
||||
-- ----------------------------------------
|
||||
INSERT INTO `org_company_permission` (`company_id`, `permission_id`, `create_by`)
|
||||
SELECT DISTINCT k.`company_id`, p.`id`, k.`create_by`
|
||||
FROM `open_api_key` k
|
||||
JOIN JSON_TABLE(k.`scopes`, '$[*]' COLUMNS (`scope_value` varchar(64) PATH '$')) jt
|
||||
JOIN `sys_permission` p ON p.`code` = CONCAT('open:scope:', jt.`scope_value`)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `org_company_permission` ocp
|
||||
WHERE ocp.`company_id` = k.`company_id` AND ocp.`permission_id` = p.`id`
|
||||
);
|
||||
|
||||
INSERT INTO `open_api_key_permission` (`api_key_id`, `company_permission_id`, `create_by`)
|
||||
SELECT DISTINCT k.`id`, ocp.`id`, k.`create_by`
|
||||
FROM `open_api_key` k
|
||||
JOIN JSON_TABLE(k.`scopes`, '$[*]' COLUMNS (`scope_value` varchar(64) PATH '$')) jt
|
||||
JOIN `sys_permission` p ON p.`code` = CONCAT('open:scope:', jt.`scope_value`)
|
||||
JOIN `org_company_permission` ocp
|
||||
ON ocp.`company_id` = k.`company_id` AND ocp.`permission_id` = p.`id`
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `open_api_key_permission` akp
|
||||
WHERE akp.`api_key_id` = k.`id` AND akp.`company_permission_id` = ocp.`id`
|
||||
);
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 4. 删除 scopes 列(执行后不可重复运行本节)
|
||||
-- ----------------------------------------
|
||||
ALTER TABLE `open_api_key` DROP COLUMN `scopes`;
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 执行后自检(手动运行)
|
||||
-- ----------------------------------------
|
||||
-- -- 开放权限定义
|
||||
-- SELECT id, code, name FROM sys_permission WHERE code LIKE 'open:scope:%' ORDER BY sort_order;
|
||||
--
|
||||
-- -- Key 授权链路
|
||||
-- SELECT k.id AS key_id, k.name AS key_name, p.code AS permission_code, p.name AS permission_name
|
||||
-- FROM open_api_key k
|
||||
-- JOIN open_api_key_permission akp ON akp.api_key_id = k.id
|
||||
-- JOIN org_company_permission ocp ON ocp.id = akp.company_permission_id
|
||||
-- JOIN sys_permission p ON p.id = ocp.permission_id
|
||||
-- ORDER BY k.id, p.sort_order;
|
||||
@@ -0,0 +1,62 @@
|
||||
-- ========================================
|
||||
-- 开放接口模块数据库设计
|
||||
-- 生成时间:2026-05-24
|
||||
-- 修订说明:
|
||||
-- API Key 授权通过 org_company_permission 间接关联 sys_permission,
|
||||
-- 不再使用 scopes JSON,也不直接 FK 到 sys_permission。
|
||||
-- 权限流转:
|
||||
-- sys_permission(定义 open:scope:* 开放能力)
|
||||
-- → org_company_permission(平台分配给公司)
|
||||
-- → open_api_key_permission(Key 勾选公司已分配权限的子集)
|
||||
-- → 开放接口校验 Key 是否持有对应 permission code
|
||||
-- ========================================
|
||||
|
||||
-- ========================================
|
||||
-- 开放接口 API Key 表
|
||||
-- ========================================
|
||||
DROP TABLE IF EXISTS `open_api_key_permission`;
|
||||
DROP TABLE IF EXISTS `open_api_key`;
|
||||
CREATE TABLE `open_api_key` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '绑定公司ID',
|
||||
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Key名称/用途说明',
|
||||
`key_prefix` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Key前缀(展示用)',
|
||||
`key_hash` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Key SHA-256 哈希',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0=停用 1=正常',
|
||||
`expire_at` datetime NULL DEFAULT NULL COMMENT '过期时间',
|
||||
`ip_whitelist` json NULL COMMENT 'IP白名单 JSON 数组,空表示不限制',
|
||||
`rate_limit` int NOT NULL DEFAULT 60 COMMENT '每分钟请求上限',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_open_api_key_hash`(`key_hash` ASC) USING BTREE,
|
||||
INDEX `idx_open_api_key_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_open_api_key_status`(`status` ASC) USING BTREE,
|
||||
INDEX `fk_open_api_key_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_open_api_key_updater`(`update_by` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_open_api_key_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '开放接口-API Key 表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- ========================================
|
||||
-- API Key 与公司权限关联表
|
||||
-- 关联 org_company_permission,而非直接关联 sys_permission
|
||||
-- ========================================
|
||||
CREATE TABLE `open_api_key_permission` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`api_key_id` bigint UNSIGNED NOT NULL COMMENT 'API Key ID',
|
||||
`company_permission_id` bigint UNSIGNED NOT NULL COMMENT '公司权限关联ID(org_company_permission.id)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_open_api_key_company_permission`(`api_key_id` ASC, `company_permission_id` ASC) USING BTREE,
|
||||
INDEX `fk_open_api_key_permission_key`(`api_key_id` ASC) USING BTREE,
|
||||
INDEX `fk_open_api_key_permission_company_perm`(`company_permission_id` ASC) USING BTREE,
|
||||
INDEX `fk_open_api_key_permission_creator`(`create_by` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_open_api_key_permission_key` FOREIGN KEY (`api_key_id`) REFERENCES `open_api_key` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_permission_company_perm` FOREIGN KEY (`company_permission_id`) REFERENCES `org_company_permission` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_open_api_key_permission_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '开放接口-API Key 与公司权限关联表' ROW_FORMAT = Dynamic;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 开放接口 Scope 校验(仅用于 /open/** Controller)
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequireOpenScope {
|
||||
|
||||
/** 所需 scope,如 order:import */
|
||||
String value();
|
||||
|
||||
String description() default "";
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.context.OpenApiContextHolder;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiPrincipal;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 开放接口 Scope 校验切面
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class OpenScopeAspect {
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope)")
|
||||
public Object checkScope(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequireOpenScope annotation = method.getAnnotation(RequireOpenScope.class);
|
||||
|
||||
OpenApiPrincipal principal = OpenApiContextHolder.get();
|
||||
if (principal == null) {
|
||||
throw new BusinessException("40301", "Scope 不足:未通过 API Key 认证");
|
||||
}
|
||||
|
||||
Set<String> permissionCodes = principal.permissionCodes();
|
||||
String requiredScope = annotation.value();
|
||||
if (permissionCodes == null || !permissionCodes.contains(requiredScope)) {
|
||||
log.warn("Scope 校验失败 - keyId: {}, required: {}, actual: {}",
|
||||
principal.apiKeyId(), requiredScope, permissionCodes);
|
||||
throw new BusinessException("40301", "Scope 不足: " + annotation.description());
|
||||
}
|
||||
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -16,7 +16,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.filter.ApiKeyAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* Spring Security配置
|
||||
@@ -26,9 +26,12 @@ import top.xyquan.ecomdmbbackend.utils.JwtUtils;
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final ApiKeyAuthenticationFilter apiKeyAuthenticationFilter;
|
||||
|
||||
public SecurityConfig(JwtUtils jwtUtils, JwtAuthenticationFilter jwtAuthenticationFilter) {
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
ApiKeyAuthenticationFilter apiKeyAuthenticationFilter) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.apiKeyAuthenticationFilter = apiKeyAuthenticationFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -50,7 +53,10 @@ public class SecurityConfig {
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
// 两个自定义 Filter 均锚定到 UsernamePasswordAuthenticationFilter;
|
||||
// 后注册的执行更靠前,故先注册 JWT、再注册 ApiKey,保证 /open/** 先走 ApiKey
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(apiKeyAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
+6
@@ -26,6 +26,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
this.jwtUtils = jwtUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
return uri != null && uri.startsWith("/open/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "批量导入推广费 DTO")
|
||||
public class BatchImportPromotionFeeDTO {
|
||||
|
||||
@NotEmpty(message = "推广费记录不能为空")
|
||||
@Valid
|
||||
@Schema(description = "推广费记录列表")
|
||||
private List<CreatePromotionFeeDTO> items;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "推广费批量导入结果")
|
||||
public class BatchImportPromotionFeeResultVO {
|
||||
|
||||
@Schema(description = "总数量")
|
||||
private Integer totalCount;
|
||||
|
||||
@Schema(description = "成功数量")
|
||||
private Integer successCount;
|
||||
|
||||
@Schema(description = "失败数量")
|
||||
private Integer failureCount;
|
||||
|
||||
@Schema(description = "成功创建的记录ID")
|
||||
private List<Long> successIds;
|
||||
|
||||
@Schema(description = "失败记录")
|
||||
private List<ImportFailureRecord> failureRecords;
|
||||
|
||||
@Data
|
||||
@Schema(description = "导入失败记录")
|
||||
public static class ImportFailureRecord {
|
||||
|
||||
@Schema(description = "失败行号")
|
||||
private Integer rowNumber;
|
||||
|
||||
@Schema(description = "店铺ID")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "失败原因")
|
||||
private String failureReason;
|
||||
}
|
||||
}
|
||||
+7
@@ -2,9 +2,11 @@ package top.xyquan.ecomdmbbackend.modules.ecom.promotion.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.BatchImportPromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.CreatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.PromotionFeeFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO;
|
||||
|
||||
/**
|
||||
@@ -36,4 +38,9 @@ public interface PromotionFeeService {
|
||||
* 分页查询推广费记录
|
||||
*/
|
||||
PageResultVO<PromotionFeeVO> getPromotionFeePage(PageQueryDTO<PromotionFeeFilterDTO> pageQueryDTO);
|
||||
|
||||
/**
|
||||
* 批量导入推广费记录
|
||||
*/
|
||||
BatchImportPromotionFeeResultVO batchImportPromotionFees(BatchImportPromotionFeeDTO dto);
|
||||
}
|
||||
|
||||
+38
@@ -11,10 +11,12 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.BatchImportPromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.CreatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.PromotionFeeFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService;
|
||||
@@ -25,6 +27,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -227,6 +230,41 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public BatchImportPromotionFeeResultVO batchImportPromotionFees(BatchImportPromotionFeeDTO dto) {
|
||||
List<CreatePromotionFeeDTO> items = dto.getItems();
|
||||
List<Long> successIds = new ArrayList<>();
|
||||
List<BatchImportPromotionFeeResultVO.ImportFailureRecord> failureRecords = new ArrayList<>();
|
||||
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
for (int i = 0; i < items.size(); i++) {
|
||||
CreatePromotionFeeDTO item = items.get(i);
|
||||
try {
|
||||
Long id = createPromotionFee(item);
|
||||
successIds.add(id);
|
||||
successCount++;
|
||||
} catch (Exception e) {
|
||||
BatchImportPromotionFeeResultVO.ImportFailureRecord record =
|
||||
new BatchImportPromotionFeeResultVO.ImportFailureRecord();
|
||||
record.setRowNumber(i + 1);
|
||||
record.setShopId(item.getShopId());
|
||||
record.setFailureReason(e.getMessage());
|
||||
failureRecords.add(record);
|
||||
failureCount++;
|
||||
}
|
||||
}
|
||||
|
||||
BatchImportPromotionFeeResultVO result = new BatchImportPromotionFeeResultVO();
|
||||
result.setTotalCount(items.size());
|
||||
result.setSuccessCount(successCount);
|
||||
result.setFailureCount(failureCount);
|
||||
result.setSuccessIds(successIds);
|
||||
result.setFailureRecords(failureRecords);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void assertOptionalCategoryInCompany(Long categoryId) {
|
||||
if (categoryId == null) {
|
||||
return;
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.constants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 开放接口权限码常量(对应 sys_permission.code,前缀 open:scope:)
|
||||
*/
|
||||
public final class OpenApiScopeConstants {
|
||||
|
||||
public static final String PREFIX = "open:scope:";
|
||||
|
||||
public static final String ORDER_IMPORT = "open:scope:order:import";
|
||||
public static final String ORDER_READ = "open:scope:order:read";
|
||||
public static final String PROMOTION_FEE_IMPORT = "open:scope:promotion_fee:import";
|
||||
public static final String PROMOTION_FEE_READ = "open:scope:promotion_fee:read";
|
||||
public static final String IMPORT_TASK_READ = "open:scope:import_task:read";
|
||||
public static final String META_READ = "open:scope:meta:read";
|
||||
|
||||
public static final List<String> ALL = List.of(
|
||||
ORDER_IMPORT,
|
||||
ORDER_READ,
|
||||
PROMOTION_FEE_IMPORT,
|
||||
PROMOTION_FEE_READ,
|
||||
IMPORT_TASK_READ,
|
||||
META_READ
|
||||
);
|
||||
|
||||
private OpenApiScopeConstants() {
|
||||
}
|
||||
|
||||
public static boolean isOpenScopeCode(String code) {
|
||||
return code != null && code.startsWith(PREFIX);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.context;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiPrincipal;
|
||||
|
||||
/**
|
||||
* 开放 API 请求上下文(ThreadLocal)
|
||||
*/
|
||||
public final class OpenApiContextHolder {
|
||||
|
||||
private static final ThreadLocal<OpenApiPrincipal> CONTEXT = new ThreadLocal<>();
|
||||
|
||||
private OpenApiContextHolder() {
|
||||
}
|
||||
|
||||
public static void set(OpenApiPrincipal principal) {
|
||||
CONTEXT.set(principal);
|
||||
}
|
||||
|
||||
public static OpenApiPrincipal get() {
|
||||
return CONTEXT.get();
|
||||
}
|
||||
|
||||
public static boolean isOpenApiRequest() {
|
||||
return CONTEXT.get() != null;
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CONTEXT.remove();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.vo.OrderStatusVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeTypeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.dto.ShopFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo.ShopVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/open/v1/ec")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "开放接口-元数据", description = "API Key 认证,Agent 辅助元数据")
|
||||
public class OpenMetaController {
|
||||
|
||||
private final ShopService shopService;
|
||||
private final OrderStatusService orderStatusService;
|
||||
private final PromotionFeeTypeService promotionFeeTypeService;
|
||||
|
||||
@PostMapping("/shop/list")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.META_READ, description = "查询店铺列表")
|
||||
@Operation(summary = "分页查询店铺列表", description = "镜像 POST /ec/shop/list")
|
||||
public ApiResponse<PageResultVO<ShopVO>> getShopPage(
|
||||
@Valid @RequestBody PageQueryDTO<ShopFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<ShopVO> result = shopService.getShopPage(pageQueryDTO);
|
||||
return ApiResponse.success("获取店铺列表成功", result);
|
||||
}
|
||||
|
||||
@GetMapping("/order-status/list")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.META_READ, description = "查询订单状态列表")
|
||||
@Operation(summary = "获取订单状态列表", description = "镜像 GET /ec/order-status/list")
|
||||
public ApiResponse<List<OrderStatusVO>> getAllOrderStatuses() {
|
||||
List<OrderStatusVO> result = orderStatusService.getAllOrderStatuses();
|
||||
return ApiResponse.success("获取订单状态列表成功", result);
|
||||
}
|
||||
|
||||
@GetMapping("/promotion-fee-type/list")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.META_READ, description = "查询推广费类型列表")
|
||||
@Operation(summary = "获取启用的推广费类型列表")
|
||||
public ApiResponse<List<PromotionFeeTypeVO>> getActivePromotionFeeTypeList() {
|
||||
List<PromotionFeeTypeVO> list = promotionFeeTypeService.getActivePromotionFeeTypeList();
|
||||
return ApiResponse.success("获取推广费类型列表成功", list);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.BatchImportOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.BatchImportResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.OrderFieldConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.OrderFieldVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.service.OrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/open/v1/ec/order")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "开放接口-订单", description = "API Key 认证,镜像 /ec/order")
|
||||
public class OpenOrderController {
|
||||
|
||||
private final OrderService orderService;
|
||||
|
||||
@GetMapping("/fields")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.ORDER_READ, description = "查询订单字段")
|
||||
@Operation(summary = "获取订单导入字段定义")
|
||||
public ApiResponse<List<OrderFieldVO>> getOrderFieldDefs() {
|
||||
return ApiResponse.success("获取订单字段成功", OrderFieldConstants.FIELDS);
|
||||
}
|
||||
|
||||
@PostMapping("/batch-import")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.ORDER_IMPORT, description = "批量导入订单")
|
||||
@Operation(summary = "批量导入订单")
|
||||
public ApiResponse<BatchImportResultVO> batchImportOrders(@Valid @RequestBody BatchImportOrderDTO dto) {
|
||||
BatchImportResultVO result = orderService.batchImportOrders(dto);
|
||||
return ApiResponse.success("批量导入订单成功", result);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.BatchImportPromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeFieldConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeFieldVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/open/v1/ec/promotion-fee")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "开放接口-推广费", description = "API Key 认证,镜像 /ec/promotion-fee")
|
||||
public class OpenPromotionFeeController {
|
||||
|
||||
private final PromotionFeeService promotionFeeService;
|
||||
|
||||
@GetMapping("/fields")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.PROMOTION_FEE_READ, description = "查询推广费字段")
|
||||
@Operation(summary = "获取推广费导入字段定义")
|
||||
public ApiResponse<List<PromotionFeeFieldVO>> getPromotionFeeFields() {
|
||||
return ApiResponse.success("获取推广费字段成功", PromotionFeeFieldConstants.FIELDS);
|
||||
}
|
||||
|
||||
@PostMapping("/batch-import")
|
||||
@RequireOpenScope(value = OpenApiScopeConstants.PROMOTION_FEE_IMPORT, description = "批量导入推广费")
|
||||
@Operation(summary = "批量导入推广费")
|
||||
public ApiResponse<BatchImportPromotionFeeResultVO> batchImportPromotionFees(
|
||||
@Valid @RequestBody BatchImportPromotionFeeDTO dto) {
|
||||
BatchImportPromotionFeeResultVO result = promotionFeeService.batchImportPromotionFees(dto);
|
||||
return ApiResponse.success("批量导入推广费成功", result);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.filter;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.context.OpenApiContextHolder;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiAuthentication;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiPrincipal;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.service.OpenApiKeyService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Set;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.util.OpenApiKeyHashUtils;
|
||||
|
||||
/**
|
||||
* API Key 认证过滤器(仅处理 /open/** 路径)
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String OPEN_PATH_PREFIX = "/open/";
|
||||
|
||||
private final OpenApiKeyService openApiKeyService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ApiKeyAuthenticationFilter(OpenApiKeyService openApiKeyService, ObjectMapper objectMapper) {
|
||||
this.openApiKeyService = openApiKeyService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
return uri == null || !uri.startsWith(OPEN_PATH_PREFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String apiKey = extractApiKey(request);
|
||||
if (!StringUtils.hasText(apiKey)) {
|
||||
writeUnauthorized(response, 40101, "API Key 无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
if (apiKey.startsWith("eyJ")) {
|
||||
writeUnauthorized(response, 40101, "开放接口不接受 JWT,请使用 API Key");
|
||||
return;
|
||||
}
|
||||
|
||||
OpenApiKeyPO keyPO = openApiKeyService.findByKeyHash(OpenApiKeyHashUtils.sha256(apiKey));
|
||||
if (keyPO == null) {
|
||||
writeUnauthorized(response, 40101, "API Key 无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
if (keyPO.getStatus() == null || keyPO.getStatus() != 1) {
|
||||
writeUnauthorized(response, 40102, "API Key 已停用");
|
||||
return;
|
||||
}
|
||||
|
||||
if (keyPO.getExpireAt() != null && keyPO.getExpireAt().isBefore(LocalDateTime.now())) {
|
||||
writeUnauthorized(response, 40102, "API Key 已过期");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!openApiKeyService.isIpAllowed(keyPO, resolveClientIp(request))) {
|
||||
writeUnauthorized(response, 40101, "IP 不在白名单内");
|
||||
return;
|
||||
}
|
||||
|
||||
Set<String> permissionCodes = openApiKeyService.getPermissionCodesByKeyId(keyPO.getId());
|
||||
OpenApiPrincipal principal = new OpenApiPrincipal(
|
||||
keyPO.getId(),
|
||||
keyPO.getCompanyId(),
|
||||
keyPO.getCreateBy(),
|
||||
keyPO.getName(),
|
||||
permissionCodes
|
||||
);
|
||||
|
||||
OpenApiContextHolder.set(principal);
|
||||
SecurityContextHolder.getContext().setAuthentication(new OpenApiAuthentication(principal));
|
||||
filterChain.doFilter(request, response);
|
||||
} catch (BusinessException e) {
|
||||
writeUnauthorized(response, 40101, e.getMessage());
|
||||
} finally {
|
||||
OpenApiContextHolder.clear();
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
private String extractApiKey(HttpServletRequest request) {
|
||||
String apiKeyHeader = request.getHeader("X-Api-Key");
|
||||
if (StringUtils.hasText(apiKeyHeader)) {
|
||||
return apiKeyHeader.trim();
|
||||
}
|
||||
|
||||
String bearerToken = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.hasText(forwarded)) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
private void writeUnauthorized(HttpServletResponse response, int code, String message) throws IOException {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(ApiResponse.fail(code, message)));
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.security;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 开放 API 认证主体
|
||||
*/
|
||||
@Getter
|
||||
public class OpenApiAuthentication implements Authentication {
|
||||
|
||||
private final OpenApiPrincipal principal;
|
||||
private boolean authenticated = true;
|
||||
|
||||
public OpenApiAuthentication(OpenApiPrincipal principal) {
|
||||
this.principal = principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return "open-api-key";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDetails() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthenticated() {
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
this.authenticated = isAuthenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return principal.clientName();
|
||||
}
|
||||
|
||||
public Long getCompanyId() {
|
||||
return principal.companyId();
|
||||
}
|
||||
|
||||
public Long getOperatorUserId() {
|
||||
return principal.operatorUserId();
|
||||
}
|
||||
|
||||
public Set<String> getPermissionCodes() {
|
||||
return principal.permissionCodes();
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.api.security;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 开放 API 请求上下文(绑定 API Key)
|
||||
*/
|
||||
public record OpenApiPrincipal(
|
||||
Long apiKeyId,
|
||||
Long companyId,
|
||||
Long operatorUserId,
|
||||
String clientName,
|
||||
Set<String> permissionCodes
|
||||
) {
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.CreateOpenApiKeyDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.OpenApiKeyFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiAvailablePermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.CreateOpenApiKeyResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiKeyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.service.OpenApiKeyService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* API Key 管理(JWT 保护)
|
||||
*/
|
||||
@Tag(name = "开放接口-API Key 管理", description = "公司拥有者管理本公司 API Key")
|
||||
@RestController
|
||||
@RequestMapping("/sys/open-api-key")
|
||||
@RequiredArgsConstructor
|
||||
public class OpenApiKeyController {
|
||||
|
||||
private final OpenApiKeyService openApiKeyService;
|
||||
|
||||
@Operation(summary = "创建 API Key", description = "明文 Key 仅创建时返回一次")
|
||||
@PostMapping("/create")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "创建 API Key", allowSuper = true)
|
||||
public ApiResponse<CreateOpenApiKeyResultVO> createKey(@Valid @RequestBody CreateOpenApiKeyDTO dto) {
|
||||
CreateOpenApiKeyResultVO result = openApiKeyService.createKey(dto);
|
||||
return ApiResponse.success("API Key 创建成功", result);
|
||||
}
|
||||
|
||||
@Operation(summary = "查询 API Key 列表")
|
||||
@GetMapping("/list")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "查询 API Key 列表", allowSuper = true)
|
||||
public ApiResponse<List<OpenApiKeyVO>> listKeys(OpenApiKeyFilterDTO filter) {
|
||||
List<OpenApiKeyVO> list = openApiKeyService.listKeys(filter);
|
||||
return ApiResponse.success("获取 API Key 列表成功", list);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取当前公司可绑定的开放权限")
|
||||
@GetMapping("/available-permissions")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "查询可绑定开放权限", allowSuper = true)
|
||||
public ApiResponse<List<OpenApiAvailablePermissionVO>> getAvailablePermissions() {
|
||||
return ApiResponse.success("获取可绑定权限成功", openApiKeyService.getAvailablePermissions());
|
||||
}
|
||||
|
||||
@Operation(summary = "停用 API Key")
|
||||
@PutMapping("/{id}/disable")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "停用 API Key", allowSuper = true)
|
||||
public ApiResponse<Void> disableKey(@Parameter(description = "Key ID") @PathVariable Long id) {
|
||||
openApiKeyService.disableKey(id);
|
||||
return ApiResponse.success("API Key 已停用");
|
||||
}
|
||||
|
||||
@Operation(summary = "启用 API Key")
|
||||
@PutMapping("/{id}/enable")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "启用 API Key", allowSuper = true)
|
||||
public ApiResponse<Void> enableKey(@Parameter(description = "Key ID") @PathVariable Long id) {
|
||||
openApiKeyService.enableKey(id);
|
||||
return ApiResponse.success("API Key 已启用");
|
||||
}
|
||||
|
||||
@Operation(summary = "删除 API Key")
|
||||
@DeleteMapping("/{id}")
|
||||
@RequirePermission(value = "open:api-key:manage", description = "删除 API Key", allowSuper = true)
|
||||
public ApiResponse<Void> deleteKey(@Parameter(description = "Key ID") @PathVariable Long id) {
|
||||
openApiKeyService.deleteKey(id);
|
||||
return ApiResponse.success("API Key 已删除");
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPO;
|
||||
|
||||
@Mapper
|
||||
public interface OpenApiKeyMapper extends BaseMapper<OpenApiKeyPO> {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPermissionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiAvailablePermissionVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface OpenApiKeyPermissionMapper extends BaseMapper<OpenApiKeyPermissionPO> {
|
||||
|
||||
List<String> selectPermissionCodesByApiKeyId(@Param("apiKeyId") Long apiKeyId);
|
||||
|
||||
List<OpenApiAvailablePermissionVO> selectPermissionsByApiKeyId(@Param("apiKeyId") Long apiKeyId);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "创建 API Key 请求")
|
||||
public class CreateOpenApiKeyDTO {
|
||||
|
||||
@NotBlank(message = "Key名称不能为空")
|
||||
@Size(max = 100, message = "Key名称长度不能超过100")
|
||||
@Schema(description = "Key名称/用途", example = "Agent-订单导入")
|
||||
private String name;
|
||||
|
||||
@NotEmpty(message = "权限不能为空")
|
||||
@Schema(description = "公司权限关联ID列表(org_company_permission.id)")
|
||||
private List<Long> companyPermissionIds;
|
||||
|
||||
@Schema(description = "过期时间,空表示永不过期")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@Schema(description = "IP白名单,空表示不限制")
|
||||
private List<String> ipWhitelist;
|
||||
|
||||
@Schema(description = "每分钟请求上限,默认60")
|
||||
private Integer rateLimit = 60;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "API Key 列表过滤")
|
||||
public class OpenApiKeyFilterDTO {
|
||||
|
||||
@Schema(description = "Key名称(模糊)")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "状态:0=停用 1=正常")
|
||||
private Integer status;
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 开放接口 API Key
|
||||
*/
|
||||
@Data
|
||||
@TableName("open_api_key")
|
||||
public class OpenApiKeyPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
private String name;
|
||||
|
||||
@TableField("key_prefix")
|
||||
private String keyPrefix;
|
||||
|
||||
@TableField("key_hash")
|
||||
private String keyHash;
|
||||
|
||||
private Integer status;
|
||||
|
||||
@TableField("expire_at")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@TableField("ip_whitelist")
|
||||
private String ipWhitelist;
|
||||
|
||||
@TableField("rate_limit")
|
||||
private Integer rateLimit;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("open_api_key_permission")
|
||||
public class OpenApiKeyPermissionPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("api_key_id")
|
||||
private Long apiKeyId;
|
||||
|
||||
@TableField("company_permission_id")
|
||||
private Long companyPermissionId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Schema(description = "创建 API Key 结果(明文 Key 仅返回一次)")
|
||||
public class CreateOpenApiKeyResultVO extends OpenApiKeyVO {
|
||||
|
||||
@Schema(description = "明文 API Key,仅创建时返回一次")
|
||||
private String plainKey;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "Key 可绑定的公司开放权限")
|
||||
public class OpenApiAvailablePermissionVO {
|
||||
|
||||
@Schema(description = "公司权限关联ID(org_company_permission.id)")
|
||||
private Long companyPermissionId;
|
||||
|
||||
@Schema(description = "权限ID")
|
||||
private Long permissionId;
|
||||
|
||||
@Schema(description = "权限码")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "权限名称")
|
||||
private String name;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "API Key 信息")
|
||||
public class OpenApiKeyVO {
|
||||
|
||||
private Long id;
|
||||
private Long companyId;
|
||||
private String name;
|
||||
private String keyPrefix;
|
||||
private List<String> permissionCodes;
|
||||
private List<OpenApiAvailablePermissionVO> permissions;
|
||||
private Integer status;
|
||||
private LocalDateTime expireAt;
|
||||
private List<String> ipWhitelist;
|
||||
private Integer rateLimit;
|
||||
private Long createBy;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.CreateOpenApiKeyDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.OpenApiKeyFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.CreateOpenApiKeyResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiAvailablePermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiKeyVO;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public interface OpenApiKeyService {
|
||||
|
||||
CreateOpenApiKeyResultVO createKey(CreateOpenApiKeyDTO dto);
|
||||
|
||||
List<OpenApiKeyVO> listKeys(OpenApiKeyFilterDTO filter);
|
||||
|
||||
void disableKey(Long id);
|
||||
|
||||
void enableKey(Long id);
|
||||
|
||||
void deleteKey(Long id);
|
||||
|
||||
OpenApiKeyPO findByKeyHash(String keyHash);
|
||||
|
||||
Set<String> getPermissionCodesByKeyId(Long apiKeyId);
|
||||
|
||||
boolean isIpAllowed(OpenApiKeyPO keyPO, String clientIp);
|
||||
|
||||
List<OpenApiAvailablePermissionVO> getAvailablePermissions();
|
||||
}
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.constants.OpenApiScopeConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.mapper.OpenApiKeyMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.mapper.OpenApiKeyPermissionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.CreateOpenApiKeyDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.dto.OpenApiKeyFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.po.OpenApiKeyPermissionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.CreateOpenApiKeyResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiAvailablePermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiKeyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.service.OpenApiKeyService;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.key.util.OpenApiKeyHashUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.permission.mapper.CompanyPermissionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.permission.model.po.CompanyPermissionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.permission.mapper.PermissionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.permission.model.po.PermissionPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpenApiKeyServiceImpl implements OpenApiKeyService {
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final OpenApiKeyMapper openApiKeyMapper;
|
||||
private final OpenApiKeyPermissionMapper openApiKeyPermissionMapper;
|
||||
private final CompanyPermissionMapper companyPermissionMapper;
|
||||
private final PermissionMapper permissionMapper;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CreateOpenApiKeyResultVO createKey(CreateOpenApiKeyDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
List<CompanyPermissionPO> companyPermissions = validateAndLoadCompanyPermissions(
|
||||
companyId, dto.getCompanyPermissionIds());
|
||||
|
||||
String plainKey = generatePlainKey();
|
||||
String keyHash = OpenApiKeyHashUtils.sha256(plainKey);
|
||||
String keyPrefix = plainKey.substring(0, 16) + "****";
|
||||
|
||||
OpenApiKeyPO po = new OpenApiKeyPO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(dto.getName());
|
||||
po.setKeyPrefix(keyPrefix);
|
||||
po.setKeyHash(keyHash);
|
||||
po.setStatus(1);
|
||||
po.setExpireAt(dto.getExpireAt());
|
||||
po.setIpWhitelist(writeJson(dto.getIpWhitelist()));
|
||||
po.setRateLimit(dto.getRateLimit() != null ? dto.getRateLimit() : 60);
|
||||
po.setCreateBy(currentUserContext.getCurrentUserId());
|
||||
po.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
openApiKeyMapper.insert(po);
|
||||
|
||||
Long operatorId = currentUserContext.getCurrentUserId();
|
||||
for (CompanyPermissionPO companyPermission : companyPermissions) {
|
||||
OpenApiKeyPermissionPO keyPermission = new OpenApiKeyPermissionPO();
|
||||
keyPermission.setApiKeyId(po.getId());
|
||||
keyPermission.setCompanyPermissionId(companyPermission.getId());
|
||||
keyPermission.setCreateBy(operatorId);
|
||||
openApiKeyPermissionMapper.insert(keyPermission);
|
||||
}
|
||||
|
||||
CreateOpenApiKeyResultVO result = new CreateOpenApiKeyResultVO();
|
||||
copyToVo(po, result);
|
||||
result.setPlainKey(plainKey);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OpenApiKeyVO> listKeys(OpenApiKeyFilterDTO filter) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
LambdaQueryWrapper<OpenApiKeyPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(OpenApiKeyPO::getCompanyId, companyId);
|
||||
if (filter != null) {
|
||||
if (StringUtils.hasText(filter.getName())) {
|
||||
wrapper.like(OpenApiKeyPO::getName, filter.getName());
|
||||
}
|
||||
if (filter.getStatus() != null) {
|
||||
wrapper.eq(OpenApiKeyPO::getStatus, filter.getStatus());
|
||||
}
|
||||
}
|
||||
wrapper.orderByDesc(OpenApiKeyPO::getCreateTime);
|
||||
return openApiKeyMapper.selectList(wrapper).stream()
|
||||
.map(this::toVo)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void disableKey(Long id) {
|
||||
OpenApiKeyPO po = getOwnedKey(id);
|
||||
po.setStatus(0);
|
||||
po.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
openApiKeyMapper.updateById(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void enableKey(Long id) {
|
||||
OpenApiKeyPO po = getOwnedKey(id);
|
||||
if (po.getStatus() != null && po.getStatus() == 1) {
|
||||
throw new BusinessException("API Key 已是启用状态");
|
||||
}
|
||||
po.setStatus(1);
|
||||
po.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
openApiKeyMapper.updateById(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteKey(Long id) {
|
||||
OpenApiKeyPO po = getOwnedKey(id);
|
||||
openApiKeyMapper.deleteById(po.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OpenApiKeyPO findByKeyHash(String keyHash) {
|
||||
if (!StringUtils.hasText(keyHash)) {
|
||||
return null;
|
||||
}
|
||||
LambdaQueryWrapper<OpenApiKeyPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(OpenApiKeyPO::getKeyHash, keyHash);
|
||||
return openApiKeyMapper.selectOne(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getPermissionCodesByKeyId(Long apiKeyId) {
|
||||
if (apiKeyId == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
List<String> codes = openApiKeyPermissionMapper.selectPermissionCodesByApiKeyId(apiKeyId);
|
||||
return new HashSet<>(codes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIpAllowed(OpenApiKeyPO keyPO, String clientIp) {
|
||||
if (!StringUtils.hasText(keyPO.getIpWhitelist())) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
List<String> whitelist = objectMapper.readValue(keyPO.getIpWhitelist(), new TypeReference<>() {
|
||||
});
|
||||
if (CollectionUtils.isEmpty(whitelist)) {
|
||||
return true;
|
||||
}
|
||||
return whitelist.contains(clientIp);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OpenApiAvailablePermissionVO> getAvailablePermissions() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return companyPermissionMapper.selectPermissionsByCompanyId(companyId).stream()
|
||||
.filter(p -> OpenApiScopeConstants.isOpenScopeCode(p.getCode()))
|
||||
.map(p -> {
|
||||
CompanyPermissionPO cp = getCompanyPermission(companyId, p.getId());
|
||||
OpenApiAvailablePermissionVO vo = new OpenApiAvailablePermissionVO();
|
||||
vo.setCompanyPermissionId(cp.getId());
|
||||
vo.setPermissionId(p.getId());
|
||||
vo.setCode(p.getCode());
|
||||
vo.setName(p.getName());
|
||||
return vo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<CompanyPermissionPO> validateAndLoadCompanyPermissions(Long companyId, List<Long> companyPermissionIds) {
|
||||
if (CollectionUtils.isEmpty(companyPermissionIds)) {
|
||||
throw new BusinessException("权限不能为空");
|
||||
}
|
||||
|
||||
List<CompanyPermissionPO> result = companyPermissionIds.stream()
|
||||
.distinct()
|
||||
.map(id -> {
|
||||
CompanyPermissionPO cp = companyPermissionMapper.selectById(id);
|
||||
if (cp == null || !companyId.equals(cp.getCompanyId())) {
|
||||
throw new BusinessException("存在无效的公司权限: " + id);
|
||||
}
|
||||
PermissionPO permission = permissionMapper.selectById(cp.getPermissionId());
|
||||
if (permission == null || !OpenApiScopeConstants.isOpenScopeCode(permission.getCode())) {
|
||||
throw new BusinessException("仅可绑定开放接口权限");
|
||||
}
|
||||
return cp;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return result;
|
||||
}
|
||||
|
||||
private CompanyPermissionPO getCompanyPermission(Long companyId, Long permissionId) {
|
||||
LambdaQueryWrapper<CompanyPermissionPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(CompanyPermissionPO::getCompanyId, companyId)
|
||||
.eq(CompanyPermissionPO::getPermissionId, permissionId);
|
||||
CompanyPermissionPO cp = companyPermissionMapper.selectOne(wrapper);
|
||||
if (cp == null) {
|
||||
throw new BusinessException("公司未分配该开放权限");
|
||||
}
|
||||
return cp;
|
||||
}
|
||||
|
||||
private OpenApiKeyPO getOwnedKey(Long id) {
|
||||
OpenApiKeyPO po = openApiKeyMapper.selectById(id);
|
||||
if (po == null || !po.getCompanyId().equals(currentUserContext.getCurrentCompanyId())) {
|
||||
throw new BusinessException("API Key 不存在");
|
||||
}
|
||||
return po;
|
||||
}
|
||||
|
||||
private String generatePlainKey() {
|
||||
byte[] bytes = new byte[24];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
StringBuilder sb = new StringBuilder("sk_live_");
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String writeJson(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("JSON 序列化失败");
|
||||
}
|
||||
}
|
||||
|
||||
private OpenApiKeyVO toVo(OpenApiKeyPO po) {
|
||||
OpenApiKeyVO vo = new OpenApiKeyVO();
|
||||
copyToVo(po, vo);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private void copyToVo(OpenApiKeyPO po, OpenApiKeyVO vo) {
|
||||
BeanUtils.copyProperties(po, vo, "ipWhitelist");
|
||||
List<OpenApiAvailablePermissionVO> permissions =
|
||||
openApiKeyPermissionMapper.selectPermissionsByApiKeyId(po.getId());
|
||||
vo.setPermissions(permissions);
|
||||
vo.setPermissionCodes(permissions.stream().map(OpenApiAvailablePermissionVO::getCode).toList());
|
||||
if (StringUtils.hasText(po.getIpWhitelist())) {
|
||||
try {
|
||||
vo.setIpWhitelist(objectMapper.readValue(po.getIpWhitelist(), new TypeReference<>() {
|
||||
}));
|
||||
} catch (Exception e) {
|
||||
vo.setIpWhitelist(Collections.emptyList());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.key.util;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
public final class OpenApiKeyHashUtils {
|
||||
|
||||
private OpenApiKeyHashUtils() {
|
||||
}
|
||||
|
||||
public static String sha256(String input) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(hash);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new BusinessException("哈希计算失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-1
@@ -5,6 +5,9 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.context.OpenApiContextHolder;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiAuthentication;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.api.security.OpenApiPrincipal;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.po.CompanyMemberPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||
|
||||
@@ -30,11 +33,30 @@ public class CurrentUserContext {
|
||||
* @throws BusinessException 如果无法获取用户信息
|
||||
*/
|
||||
public TokenPayload getCurrentUserPayload() {
|
||||
OpenApiPrincipal openPrincipal = OpenApiContextHolder.get();
|
||||
if (openPrincipal != null) {
|
||||
return TokenPayload.builder()
|
||||
.userId(String.valueOf(openPrincipal.operatorUserId()))
|
||||
.companyId(openPrincipal.companyId())
|
||||
.role("user")
|
||||
.companyRole("owner")
|
||||
.build();
|
||||
}
|
||||
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null) {
|
||||
throw new BusinessException("用户未登录 - 认证信息为空");
|
||||
}
|
||||
|
||||
|
||||
if (authentication instanceof OpenApiAuthentication openApiAuthentication) {
|
||||
return TokenPayload.builder()
|
||||
.userId(String.valueOf(openApiAuthentication.getOperatorUserId()))
|
||||
.companyId(openApiAuthentication.getCompanyId())
|
||||
.role("user")
|
||||
.companyRole("owner")
|
||||
.build();
|
||||
}
|
||||
|
||||
if (authentication.getCredentials() == null) {
|
||||
throw new BusinessException("用户未登录 - Token信息为空");
|
||||
}
|
||||
@@ -51,6 +73,10 @@ public class CurrentUserContext {
|
||||
* @throws BusinessException 如果无法获取公司信息
|
||||
*/
|
||||
public Long getCurrentCompanyId() {
|
||||
OpenApiPrincipal openPrincipal = OpenApiContextHolder.get();
|
||||
if (openPrincipal != null) {
|
||||
return openPrincipal.companyId();
|
||||
}
|
||||
TokenPayload payload = getCurrentUserPayload();
|
||||
if (payload.getCompanyId() == null) {
|
||||
throw new BusinessException("无法获取公司信息");
|
||||
@@ -65,6 +91,10 @@ public class CurrentUserContext {
|
||||
* @throws BusinessException 如果无法获取用户信息
|
||||
*/
|
||||
public Long getCurrentUserId() {
|
||||
OpenApiPrincipal openPrincipal = OpenApiContextHolder.get();
|
||||
if (openPrincipal != null) {
|
||||
return openPrincipal.operatorUserId();
|
||||
}
|
||||
TokenPayload payload = getCurrentUserPayload();
|
||||
try {
|
||||
return Long.parseLong(payload.getUserId());
|
||||
@@ -73,6 +103,13 @@ public class CurrentUserContext {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为开放 API 请求(API Key 认证)
|
||||
*/
|
||||
public boolean isOpenApiRequest() {
|
||||
return OpenApiContextHolder.isOpenApiRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户角色
|
||||
*
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="top.xyquan.ecomdmbbackend.modules.open.key.mapper.OpenApiKeyPermissionMapper">
|
||||
|
||||
<select id="selectPermissionCodesByApiKeyId" resultType="java.lang.String">
|
||||
SELECT p.code
|
||||
FROM open_api_key_permission akp
|
||||
JOIN org_company_permission ocp ON ocp.id = akp.company_permission_id
|
||||
JOIN sys_permission p ON p.id = ocp.permission_id
|
||||
WHERE akp.api_key_id = #{apiKeyId}
|
||||
ORDER BY p.sort_order
|
||||
</select>
|
||||
|
||||
<select id="selectPermissionsByApiKeyId"
|
||||
resultType="top.xyquan.ecomdmbbackend.modules.open.key.model.vo.OpenApiAvailablePermissionVO">
|
||||
SELECT akp.company_permission_id AS companyPermissionId,
|
||||
p.id AS permissionId,
|
||||
p.code AS code,
|
||||
p.name AS name
|
||||
FROM open_api_key_permission akp
|
||||
JOIN org_company_permission ocp ON ocp.id = akp.company_permission_id
|
||||
JOIN sys_permission p ON p.id = ocp.permission_id
|
||||
WHERE akp.api_key_id = #{apiKeyId}
|
||||
ORDER BY p.sort_order
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,34 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
import type { OpenApiKeyDTO, OpenApiKeyVO } from './types';
|
||||
|
||||
export async function createOpenApiKeyApi(data: OpenApiKeyDTO.CreateOpenApiKeyDTO) {
|
||||
return requestClient.post<OpenApiKeyVO.CreateOpenApiKeyResultVO>(
|
||||
'/sys/open-api-key/create',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getOpenApiKeyListApi(params?: OpenApiKeyDTO.OpenApiKeyFilterDTO) {
|
||||
return requestClient.get<OpenApiKeyVO.OpenApiKeyInfoVO[]>('/sys/open-api-key/list', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOpenApiKeyAvailablePermissionsApi() {
|
||||
return requestClient.get<OpenApiKeyVO.OpenApiAvailablePermissionVO[]>(
|
||||
'/sys/open-api-key/available-permissions',
|
||||
);
|
||||
}
|
||||
|
||||
export async function disableOpenApiKeyApi(id: number) {
|
||||
return requestClient.put<void>(`/sys/open-api-key/${id}/disable`);
|
||||
}
|
||||
|
||||
export async function enableOpenApiKeyApi(id: number) {
|
||||
return requestClient.put<void>(`/sys/open-api-key/${id}/enable`);
|
||||
}
|
||||
|
||||
export async function deleteOpenApiKeyApi(id: number) {
|
||||
return requestClient.delete<void>(`/sys/open-api-key/${id}`);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -0,0 +1 @@
|
||||
export * from './types.vo';
|
||||
@@ -0,0 +1,43 @@
|
||||
export namespace OpenApiKeyDTO {
|
||||
export interface CreateOpenApiKeyDTO {
|
||||
name: string;
|
||||
companyPermissionIds: number[];
|
||||
expireAt?: string;
|
||||
ipWhitelist?: string[];
|
||||
rateLimit?: number;
|
||||
}
|
||||
|
||||
export interface OpenApiKeyFilterDTO {
|
||||
name?: string;
|
||||
status?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace OpenApiKeyVO {
|
||||
export interface OpenApiAvailablePermissionVO {
|
||||
companyPermissionId: number;
|
||||
permissionId: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface OpenApiKeyInfoVO {
|
||||
id: number;
|
||||
companyId: number;
|
||||
name: string;
|
||||
keyPrefix: string;
|
||||
permissionCodes?: string[];
|
||||
permissions?: OpenApiAvailablePermissionVO[];
|
||||
status: number;
|
||||
expireAt?: string;
|
||||
ipWhitelist?: string[];
|
||||
rateLimit: number;
|
||||
createBy?: number;
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
export interface CreateOpenApiKeyResultVO extends OpenApiKeyInfoVO {
|
||||
plainKey: string;
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
<script lang="ts" setup>
|
||||
import type { OpenApiKeyDTO, OpenApiKeyVO } from '#/api/open/api-key';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Alert,
|
||||
Checkbox,
|
||||
DatePicker,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
message,
|
||||
Select,
|
||||
Tag,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createOpenApiKeyApi,
|
||||
getOpenApiKeyAvailablePermissionsApi,
|
||||
} from '#/api/open/api-key';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success', result: OpenApiKeyVO.CreateOpenApiKeyResultVO): void;
|
||||
}
|
||||
|
||||
defineOptions({ name: 'CreateApiKeyModal' });
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[560px]',
|
||||
onCancel() {
|
||||
handleCancel();
|
||||
},
|
||||
onConfirm() {
|
||||
handleSubmit();
|
||||
},
|
||||
});
|
||||
|
||||
const formRef = ref();
|
||||
const loading = ref(false);
|
||||
const permissionOptions = ref<OpenApiKeyVO.OpenApiAvailablePermissionVO[]>([]);
|
||||
const createdKey = ref<string | null>(null);
|
||||
|
||||
const formData = ref<OpenApiKeyDTO.CreateOpenApiKeyDTO>({
|
||||
name: '',
|
||||
companyPermissionIds: [],
|
||||
expireAt: undefined,
|
||||
rateLimit: 60,
|
||||
ipWhitelist: [],
|
||||
});
|
||||
|
||||
const modalTitle = computed(() => (createdKey.value ? 'API Key 已创建' : '创建 API Key'));
|
||||
|
||||
async function loadPermissions() {
|
||||
permissionOptions.value = await getOpenApiKeyAvailablePermissionsApi();
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
formData.value = {
|
||||
name: '',
|
||||
companyPermissionIds: [],
|
||||
expireAt: undefined,
|
||||
rateLimit: 60,
|
||||
ipWhitelist: [],
|
||||
};
|
||||
createdKey.value = null;
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
resetForm();
|
||||
modalApi.close();
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (createdKey.value) {
|
||||
handleCancel();
|
||||
return;
|
||||
}
|
||||
|
||||
if (permissionOptions.value.length === 0) {
|
||||
message.warning('当前公司尚未分配开放接口权限,请联系平台管理员');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
loading.value = true;
|
||||
const result = await createOpenApiKeyApi(formData.value);
|
||||
createdKey.value = result.plainKey;
|
||||
message.success('API Key 创建成功,请立即保存明文 Key');
|
||||
emit('success', result);
|
||||
} catch {
|
||||
// 校验或请求失败
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
}
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.left = '-9999px';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.focus();
|
||||
textarea.select();
|
||||
try {
|
||||
const ok = document.execCommand('copy');
|
||||
if (!ok) {
|
||||
throw new Error('copy failed');
|
||||
}
|
||||
} finally {
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyKey() {
|
||||
if (!createdKey.value) return;
|
||||
try {
|
||||
await copyText(createdKey.value);
|
||||
message.success('已复制到剪贴板');
|
||||
} catch {
|
||||
message.error('复制失败,请手动选择文本复制');
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
open: async () => {
|
||||
resetForm();
|
||||
await loadPermissions();
|
||||
modalApi.open();
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :title="modalTitle" :confirm-loading="loading" :show-cancel-button="!createdKey">
|
||||
<Alert
|
||||
v-if="createdKey"
|
||||
class="mb-4"
|
||||
message="明文 Key 仅显示一次,关闭后将无法再次查看,请立即复制保存。"
|
||||
show-icon
|
||||
type="warning"
|
||||
/>
|
||||
|
||||
<div v-if="createdKey" class="space-y-3">
|
||||
<Input.TextArea :rows="3" :value="createdKey" readonly />
|
||||
<Tag color="blue" class="cursor-pointer" @click="copyKey">点击复制 Key</Tag>
|
||||
</div>
|
||||
|
||||
<Form v-else ref="formRef" :model="formData" layout="vertical">
|
||||
<Alert
|
||||
v-if="permissionOptions.length === 0"
|
||||
class="mb-4"
|
||||
message="当前公司尚未分配 open:scope:* 开放权限,请先在「公司权限分配」中配置。"
|
||||
show-icon
|
||||
type="info"
|
||||
/>
|
||||
|
||||
<Form.Item
|
||||
label="Key 名称"
|
||||
name="name"
|
||||
:rules="[{ required: true, message: '请输入 Key 名称' }]"
|
||||
>
|
||||
<Input v-model:value="formData.name" placeholder="如:Agent-订单导入" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="开放权限"
|
||||
name="companyPermissionIds"
|
||||
:rules="[{ required: true, type: 'array', min: 1, message: '请选择至少一个权限' }]"
|
||||
>
|
||||
<Checkbox.Group v-model:value="formData.companyPermissionIds" class="flex flex-col gap-2">
|
||||
<Checkbox
|
||||
v-for="item in permissionOptions"
|
||||
:key="item.companyPermissionId"
|
||||
:value="item.companyPermissionId"
|
||||
>
|
||||
{{ item.name }} ({{ item.code }})
|
||||
</Checkbox>
|
||||
</Checkbox.Group>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="每分钟请求上限" name="rateLimit">
|
||||
<InputNumber v-model:value="formData.rateLimit" :min="1" :max="10000" class="w-full" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="过期时间(可选)" name="expireAt">
|
||||
<DatePicker
|
||||
v-model:value="formData.expireAt"
|
||||
show-time
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
format="YYYY-MM-DD HH:mm:ss"
|
||||
placeholder="留空表示永不过期"
|
||||
class="w-full"
|
||||
allow-clear
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="IP 白名单(可选)" name="ipWhitelist">
|
||||
<Select
|
||||
v-model:value="formData.ipWhitelist"
|
||||
mode="tags"
|
||||
placeholder="留空表示不限制,输入 IP 后回车"
|
||||
:token-separators="[',', ' ']"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<template #confirmText>{{ createdKey ? '我已保存,关闭' : '创建' }}</template>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -0,0 +1,193 @@
|
||||
<script lang="ts" setup>
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { OpenApiKeyVO } from '#/api/open/api-key';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, message, Popconfirm, Space, Tag, Tooltip } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteOpenApiKeyApi,
|
||||
disableOpenApiKeyApi,
|
||||
enableOpenApiKeyApi,
|
||||
getOpenApiKeyListApi,
|
||||
} from '#/api/open/api-key';
|
||||
|
||||
import CreateApiKeyModal from './components/CreateApiKeyModal.vue';
|
||||
|
||||
defineOptions({ name: 'OpenApiKeyManagement' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const loading = ref(false);
|
||||
const createModalRef = ref<InstanceType<typeof CreateApiKeyModal>>();
|
||||
|
||||
const permissionLabelMap: Record<string, string> = {
|
||||
'open:scope:order:import': '订单导入',
|
||||
'open:scope:order:read': '订单字段',
|
||||
'open:scope:promotion_fee:import': '推广费导入',
|
||||
'open:scope:promotion_fee:read': '推广费字段',
|
||||
'open:scope:import_task:read': '导入任务',
|
||||
'open:scope:meta:read': '元数据',
|
||||
};
|
||||
|
||||
function formatExpireAt(cellValue?: null | string) {
|
||||
return cellValue ? String(cellValue) : '永不过期';
|
||||
}
|
||||
|
||||
const gridOptions: VxeGridProps<OpenApiKeyVO.OpenApiKeyInfoVO> = {
|
||||
columns: [
|
||||
{ type: 'seq', title: '序号', minWidth: 60 },
|
||||
{ field: 'name', title: '名称', minWidth: 140 },
|
||||
{ field: 'keyPrefix', title: 'Key 前缀', minWidth: 180 },
|
||||
{
|
||||
field: 'permissionCodes',
|
||||
title: '开放权限',
|
||||
minWidth: 100,
|
||||
slots: { default: 'permissions' },
|
||||
},
|
||||
{
|
||||
field: 'status',
|
||||
title: '状态',
|
||||
minWidth: 90,
|
||||
slots: { default: 'status' },
|
||||
},
|
||||
{ field: 'rateLimit', title: '限流/分钟', minWidth: 100 },
|
||||
{
|
||||
field: 'expireAt',
|
||||
title: '过期时间',
|
||||
minWidth: 160,
|
||||
showOverflow: 'tooltip',
|
||||
formatter: ({ cellValue }: { cellValue?: null | string }) =>
|
||||
formatExpireAt(cellValue),
|
||||
},
|
||||
{ field: 'createTime', title: '创建时间', minWidth: 160 },
|
||||
{
|
||||
title: '操作',
|
||||
width: 200,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
},
|
||||
],
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const list = await getOpenApiKeyListApi();
|
||||
return { items: list, total: list.length };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||
|
||||
async function handleDisable(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
await disableOpenApiKeyApi(row.id);
|
||||
message.success('已停用');
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
async function handleEnable(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
await enableOpenApiKeyApi(row.id);
|
||||
message.success('已启用');
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
async function handleDelete(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
await deleteOpenApiKeyApi(row.id);
|
||||
message.success('已删除');
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
function openCreateModal() {
|
||||
createModalRef.value?.open();
|
||||
}
|
||||
|
||||
function getPermissionCount(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
return row.permissionCodes?.length ?? row.permissions?.length ?? 0;
|
||||
}
|
||||
|
||||
function getPermissionTooltip(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
if (row.permissions?.length) {
|
||||
return row.permissions.map((item) => `${item.name} (${item.code})`);
|
||||
}
|
||||
return (row.permissionCodes ?? []).map((code) => {
|
||||
const label = permissionLabelMap[code] || code;
|
||||
return label === code ? code : `${label} (${code})`;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<Button type="primary" @click="openCreateModal">
|
||||
<PlusIcon class="size-4" />
|
||||
创建 API Key
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<template #permissions="{ row }">
|
||||
<Tooltip v-if="getPermissionCount(row) > 0">
|
||||
<template #title>
|
||||
<div v-for="(line, index) in getPermissionTooltip(row)" :key="index">
|
||||
{{ line }}
|
||||
</div>
|
||||
</template>
|
||||
<span class="cursor-default">{{ getPermissionCount(row) }} 项</span>
|
||||
</Tooltip>
|
||||
<span v-else class="text-gray-400">0 项</span>
|
||||
</template>
|
||||
|
||||
<template #status="{ row }">
|
||||
<Tag :color="row.status === 1 ? 'success' : 'default'">
|
||||
{{ row.status === 1 ? '正常' : '停用' }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<template #action="{ row }">
|
||||
<Space>
|
||||
<Popconfirm
|
||||
v-if="row.status === 1"
|
||||
title="确认停用该 API Key?"
|
||||
@confirm="handleDisable(row)"
|
||||
>
|
||||
<Button type="link" size="small">停用</Button>
|
||||
</Popconfirm>
|
||||
<Popconfirm
|
||||
v-else
|
||||
title="确认启用该 API Key?"
|
||||
@confirm="handleEnable(row)"
|
||||
>
|
||||
<Button type="link" size="small">启用</Button>
|
||||
</Popconfirm>
|
||||
<Popconfirm title="确认删除该 API Key?" @confirm="handleDelete(row)">
|
||||
<Button type="link" danger size="small">删除</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<CreateApiKeyModal ref="createModalRef" @success="() => gridApi.reload()" />
|
||||
</Page>
|
||||
</template>
|
||||
Reference in New Issue
Block a user