-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
232 lines (195 loc) · 7.87 KB
/
Program.cs
File metadata and controls
232 lines (195 loc) · 7.87 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using System.Text;
using System.Threading.Channels;
using AspNetCoreEcommerce.Domain.Entities;
using AspNetCoreEcommerce.Infrastructure.Data;
using AspNetCoreEcommerce.Infrastructure.Data.Seeders;
using AspNetCoreEcommerce.Infrastructure.EmailInfrastructure;
using AspNetCoreEcommerce.Infrastructure.PaymentChannel;
using AspNetCoreEcommerce.Infrastructure.Repositories;
using AspNetCoreEcommerce.Services;
using AspNetCoreEcommerce.Services.Interfaces.Repositories;
using AspNetCoreEcommerce.Services.Interfaces.Services;
using AspNetCoreEcommerce.Shared;
using AspNetCoreEcommerce.Shared.ErrorHandling;
using AspNetCoreEcommerce.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using Scalar.AspNetCore;
using Serilog;
// Logging
string logPath = Path.Combine(Directory.GetCurrentDirectory(), "logs");
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File($"{logPath}/log-.txt", rollingInterval: RollingInterval.Hour)
.CreateLogger();
Log.Information("Starting web host...");
var builder = WebApplication.CreateBuilder(args);
// Load dotnetenv for database connections
// Load dotnev
DotNetEnv.Env.Load();
// Load environment variables from .env file
//Db Config
string? dbHost = Environment.GetEnvironmentVariable("DATABASE_HOST");
string? dbUser = Environment.GetEnvironmentVariable("DATABASE_USER");
string? dbName = Environment.GetEnvironmentVariable("DATABASE_NAME");
string? dbPassword = Environment.GetEnvironmentVariable("DATABASE_PASSWORD");
string? dbPort = Environment.GetEnvironmentVariable("DATABASE_PORT");
// Check if environment variables are set
if (
string.IsNullOrWhiteSpace(dbHost) ||
string.IsNullOrWhiteSpace(dbUser) ||
string.IsNullOrWhiteSpace(dbName) ||
string.IsNullOrWhiteSpace(dbPassword) ||
string.IsNullOrWhiteSpace(dbPort)
) throw new ArgumentException("Database environment variables are not set.");
// Construct connection string
// var environment = builder.Environment;
string dbConnectionString = $"Host={dbHost};Port={dbPort};Username={dbUser};Password={dbPassword};Database={dbName}";
//Register Application context with postgresql connection
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(dbConnectionString));
// Register Identity services with PostgreSQL
builder.Services.AddIdentity<User, UserRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.Password.RequireDigit = false;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.SignIn.RequireConfirmedEmail = true; // Require email confirmation for sign-in
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// InMemory Cache
builder.Services.AddMemoryCache();
// Paystack options
builder.Services.AddOptions<PayStackOptions>()
.Bind(builder.Configuration.GetSection(nameof(PayStackOptions)))
.ValidateDataAnnotations()
.ValidateOnStart();
// Register the token provider
builder.Services.AddSingleton<TokenProvider>();
// Register JWT
string? jwtSecret = Environment.GetEnvironmentVariable("JWT_SECRET_KEY");
string? jwtIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER");
if (
string.IsNullOrWhiteSpace(jwtSecret)
|| string.IsNullOrWhiteSpace(jwtIssuer)
) throw new ArgumentException("JWT environment variables are not set.");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.RequireHttpsMetadata = builder.Environment.IsProduction();
options.SaveToken = true; // Save the token in the authentication properties
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["X-Access-Token"];
return Task.CompletedTask;
}
};
});
// --- Authorization Configuration ---
builder.Services.AddAuthorization();
// --- CORS Configuration ---
string? fronendUrl = Environment.GetEnvironmentVariable("FrontendUrl");
if (string.IsNullOrEmpty(fronendUrl))
throw new ArgumentException("Frontend url is not set");
const string CorsPolicyName = "AllowFrontEnd";
builder.Services.AddCors(options =>
{
options.AddPolicy(CorsPolicyName, policy =>
{
policy.WithOrigins(fronendUrl)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
// --- Dependency Injection (Repositories & Services) ---
// Repositories
builder.Services.AddScoped<ICartRepository, CartRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IShippingAddressRespository, ShippingAddressRespository>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IPaymentRepository, PaymentRepository>();
builder.Services.AddScoped<IVendorRepository, VendorRepository>();
// Services
builder.Services.AddScoped<AuthServices>();
builder.Services.AddScoped<IShippingAddressService, ShippingAddressService>();
builder.Services.AddScoped<IVendorService, VendorService>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IPaymentService, PaymentService>();
builder.Services.AddScoped<ICartService, CartService>();
builder.Services.AddScoped<IOrderSevice, OrderSevice>();
// Payment channel service
builder.Services.AddScoped<ErcasPay>();
builder.Services.AddScoped<PayStack>();
// Payment channel service
builder.Services.AddSingleton<EmailService>(); // Email service
builder.Services.AddSingleton(Channel.CreateBounded<EmailDto>(100));
builder.Services.AddHostedService<EmailService.EmailBackgroundService>();
// --- API Controllers & OpenAPI ---
builder.Services.AddControllers();
builder.Services.AddOpenApi();
// --- Build the Application ---
var app = builder.Build();
// Custom ExceptionHandling Middleware
app.UseMiddleware<ExceptionHandlingMiddleware>();
// Scalar Config
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
// Seed db
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
try
{
// Seed the database with roles
await SeedDatabase.SeedRoleAsync(services, db);
}
catch (Exception ex)
{
Log.Error(ex, "An error occurred while seeding the database.");
}
}
}
// Image folder storage setup
var imageFilePath = Path.Combine(builder.Environment.ContentRootPath, GlobalConstants.uploadPath);
if (!Directory.Exists(imageFilePath))
Directory.CreateDirectory(imageFilePath);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(imageFilePath),
RequestPath = $"/{GlobalConstants.uploadPath}"
});
app.UseRouting(); // Determines endpoint
app.UseCors(CorsPolicyName); // Cors policy name
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();