using SPMS.Domain.Common; using SPMS.Domain.Interfaces; namespace SPMS.API.Middlewares; public class ApiKeyMiddleware { private readonly RequestDelegate _next; public ApiKeyMiddleware(RequestDelegate next) => _next = next; public async Task InvokeAsync(HttpContext context, IServiceRepository serviceRepository) { if (!RequiresApiKey(context.Request.Path)) { await _next(context); return; } if (!context.Request.Headers.TryGetValue("X-API-KEY", out var apiKey) || string.IsNullOrWhiteSpace(apiKey)) { context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; await context.Response.WriteAsJsonAsync( ApiResponse.Fail(ErrorCodes.Unauthorized, "API Key가 필요합니다.")); return; } var service = await serviceRepository.GetByApiKeyAsync(apiKey!); if (service == null) { context.Response.StatusCode = 403; context.Response.ContentType = "application/json"; await context.Response.WriteAsJsonAsync( ApiResponse.Fail(ErrorCodes.Unauthorized, "유효하지 않은 API Key입니다.")); return; } context.Items["Service"] = service; context.Items["ServiceId"] = service.Id; await _next(context); } private static bool RequiresApiKey(PathString path) { return path.StartsWithSegments("/v1/in/device") && !path.StartsWithSegments("/v1/in/device/list"); } }