mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:09:21 +08:00
wip: 可能基本完成的开放模块
This commit is contained in:
+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>
|
||||
Reference in New Issue
Block a user