using System.Text.Json.Serialization; using StopShopping.AdminApi.Middlewares; using StopShopping.Services; using StopShopping.Services.Extensions; namespace StopShopping.AdminApi.Extensions; public static class CommonServiceCollections { public static IServiceCollection AddCommonServices( this IServiceCollection services, string corsPolicy, IConfigurationSection jwtConfiguration, IConfigurationSection appConfiguration, bool isDevelopment) { var appOptions = appConfiguration.Get(); services.AddCors(options => { options.AddPolicy(corsPolicy, policy => { policy.AllowAnyHeader(); policy.AllowAnyMethod(); policy.WithOrigins(appOptions!.CorsAllowedOrigins); policy.AllowCredentials(); }); }); services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.Converters.Add( new JsonStringEnumConverter(namingPolicy: null, allowIntegerValues: true)); }); services.AddHttpContextAccessor(); services.AddOpenApi(options => { options.AddDocumentTransformer(); options.AddSchemaTransformer(); }); services.AddProblemDetails(options => { options.CustomizeProblemDetails = (context) => { if (context.ProblemDetails is HttpValidationProblemDetails problemDetails) { problemDetails.AddErrorCode(ProblemDetailsCodes.ParametersValidationFailed); var errors = problemDetails.Errors.Select(e => string.Join(',', e.Value)); if (null != errors) problemDetails.Detail = string.Join(',', errors); } }; }); services.AddValidation(); services.AddDistributedMemoryCache(); services.AddAuthServices(jwtConfiguration); services.AddAntiforgery(options => { var jwtOptions = jwtConfiguration.Get(); options.HeaderName = appOptions!.CSRFHeaderName; options.Cookie.MaxAge = TimeSpan.FromSeconds(jwtOptions!.RefreshTokenExpiresIn); options.Cookie.HttpOnly = true; options.Cookie.Name = appOptions.CSRFCookieName; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.Domain = appOptions.CookieDomain; if (!isDevelopment) { options.Cookie.SecurePolicy = CookieSecurePolicy.Always; } }); return services; } }