SPMS_API/SPMS.API/Middlewares/ServiceCodeMiddleware.cs

63 lines
2.4 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("/v1/in/device") &&
!context.Request.Path.StartsWithSegments("/v1/in/device/list")) ||
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);
}
}