SPMS_API/SPMS.API/Middlewares/ServiceCodeMiddleware.cs
SEAN f798b290ec fix: X-Service-Code 미들웨어 경로 제외 수정 (#59)
auth, account, public, service 경로를 X-Service-Code 검증 대상에서 제외.
device, message, push, stats, file 경로만 X-Service-Code 헤더 필요.
Swagger OperationFilter도 동일하게 수정.
2026-02-10 10:20:43 +09:00

61 lines
2.2 KiB
C#

using SPMS.Domain.Common;
using SPMS.Domain.Enums;
using SPMS.Domain.Interfaces;
namespace SPMS.API.Middlewares;
public class ServiceCodeMiddleware
{
private readonly RequestDelegate _next;
public ServiceCodeMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context, IServiceRepository serviceRepository)
{
if (context.Request.Path.StartsWithSegments("/v1/out") ||
context.Request.Path.StartsWithSegments("/v1/in/auth") ||
context.Request.Path.StartsWithSegments("/v1/in/account") ||
context.Request.Path.StartsWithSegments("/v1/in/public") ||
context.Request.Path.StartsWithSegments("/v1/in/service") ||
context.Request.Path.StartsWithSegments("/swagger") ||
context.Request.Path.StartsWithSegments("/health"))
{
await _next(context);
return;
}
if (!context.Request.Headers.TryGetValue("X-Service-Code", out var serviceCode) ||
string.IsNullOrWhiteSpace(serviceCode))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.BadRequest, "X-Service-Code 헤더가 필요합니다."));
return;
}
var service = await serviceRepository.GetByServiceCodeAsync(serviceCode!);
if (service == null)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.NotFound, "존재하지 않는 서비스입니다."));
return;
}
if (service.Status != ServiceStatus.Active)
{
context.Response.StatusCode = 503;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
ApiResponse.Fail(ErrorCodes.Unauthorized, "비활성 상태의 서비스입니다."));
return;
}
context.Items["Service"] = service;
context.Items["ServiceId"] = service.Id;
await _next(context);
}
}