-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
183 lines (157 loc) · 6.13 KB
/
Copy pathProgram.cs
File metadata and controls
183 lines (157 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using PulseData.API.Configuration;
using PulseData.API.Middleware;
using PulseData.API.Services;
using PulseData.Core.Interfaces;
using PulseData.Infrastructure.Data;
using PulseData.Infrastructure.Repositories;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add configuration from appsettings files
builder.Configuration
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>(optional: true);
// ---------------------------------------------------------------------------
// Services
// ---------------------------------------------------------------------------
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMemoryCache();
// Configuration Options (bind from appsettings)
builder.Services.Configure<CorsOptions>(builder.Configuration.GetSection(CorsOptions.SectionName));
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.SectionName));
builder.Services.Configure<LoggingOptions>(builder.Configuration.GetSection(LoggingOptions.SectionName));
builder.Services
.AddOptions<HealthCheckOptions>()
.Bind(builder.Configuration.GetSection(HealthCheckOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
// Swagger/OpenAPI with JWT support
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new()
{
Title = "PulseData API",
Version = "v1",
Description = "E-Commerce Analytics Platform — exposes sales, product, and customer data.",
Contact = new()
{
Name = "PulseData Team",
Url = new Uri("https://github.com/kill74/PulseData")
}
});
// Add JWT authorization to Swagger
options.AddSecurityDefinition("Bearer", new()
{
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
Description = "Enter your JWT token in the format: Bearer {token}"
});
options.AddSecurityRequirement(new()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
[]
}
});
// Include XML comments from source code
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
options.IncludeXmlComments(xmlPath);
});
// Database
builder.Services.AddSingleton<DbConnectionFactory>();
// Repositories
builder.Services.AddScoped<IAnalyticsRepository, AnalyticsRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
// Services
builder.Services.AddScoped<IHealthCheckService, HealthCheckService>();
// CORS — configuration-driven, defaults to secure setup
var corsOptions = builder.Configuration.GetSection(CorsOptions.SectionName).Get<CorsOptions>() ?? new();
builder.Services.AddCors(options =>
{
if (builder.Environment.IsDevelopment() && corsOptions.AllowedOrigins.Length == 0)
{
// Development: allow localhost
options.AddDefaultPolicy(policy =>
policy.WithOrigins("http://localhost:3000", "http://localhost:5173", "http://localhost:5174")
.AllowAnyHeader()
.AllowAnyMethod());
}
else if (corsOptions.AllowedOrigins.Length > 0)
{
// Production: use configured origins
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(corsOptions.AllowedOrigins)
.WithMethods(corsOptions.AllowedMethods)
.WithHeaders(corsOptions.AllowedHeaders)
.WithExposedHeaders("Content-Disposition")
.SetPreflightMaxAge(TimeSpan.FromSeconds(corsOptions.MaxAge));
if (corsOptions.AllowCredentials)
policy.AllowCredentials();
});
}
else
{
// Fallback: restrict to HTTPS origins only (very safe)
options.AddDefaultPolicy(policy =>
policy.WithOrigins("https://localhost")
.AllowAnyHeader()
.WithMethods("GET", "POST", "PUT", "DELETE"));
}
});
// Authentication (JWT) — optional; add only if issuer is configured
if (!string.IsNullOrEmpty(builder.Configuration.GetSection(JwtOptions.SectionName)["Issuer"]))
{
builder.Services
.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration[$"{JwtOptions.SectionName}:Issuer"];
options.Audience = builder.Configuration[$"{JwtOptions.SectionName}:Audience"];
options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
});
builder.Services.AddAuthorization();
}
// ---------------------------------------------------------------------------
// Middleware pipeline
// ---------------------------------------------------------------------------
var app = builder.Build();
// Exception handling (MUST be first!)
app.UseMiddleware<GlobalExceptionMiddleware>();
// Request logging
if (builder.Environment.IsDevelopment())
app.UseMiddleware<RequestLoggingMiddleware>();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "PulseData API v1");
options.RoutePrefix = string.Empty; // Swagger at root
options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
});
}
app.UseHttpsRedirection();
app.UseCors();
// Authentication & Authorization (if enabled)
if (!string.IsNullOrEmpty(builder.Configuration.GetSection(JwtOptions.SectionName)["Issuer"]))
{
app.UseAuthentication();
app.UseAuthorization();
}
app.MapControllers();
app.Run();
public partial class Program
{
}