-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
333 lines (295 loc) · 13.2 KB
/
Copy pathProgram.cs
File metadata and controls
333 lines (295 loc) · 13.2 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using System.Reflection;
using AutoMapper;
using AutoMapper.EquivalencyExpression;
using FluentStorage;
using FluentStorage.Blobs;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi;
using Resend;
using Scalar.AspNetCore;
using SplitzBackend.Models;
using SplitzBackend.OpenAPIGen.Filter;
using SplitzBackend.Services;
namespace SplitzBackend;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var emailOptions = builder.Configuration.GetSection(EmailOptions.SectionName).Get<EmailOptions>() ?? new EmailOptions();
// configure database
builder.Services.AddDbContext<SplitzDbContext>(options =>
{
options.UseSqlite(builder.Configuration.GetConnectionString("Sqlite"));
});
// configure identity
builder.Services.AddAuthorization();
builder.Services.AddIdentityApiEndpoints<SplitzUser>(option => ConfigureIdentityOptions(option, emailOptions))
.AddEntityFrameworkStores<SplitzDbContext>();
// configure routing and controllers
builder.Services.AddControllers();
builder.Services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
// configure default cors policy to allow all origins
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyMethod();
policy.AllowAnyHeader();
});
});
// configure swashbuckle (old but work well)
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
options.SupportNonNullableReferenceTypes();
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Bearer token authentication",
Type = SecuritySchemeType.Http,
In = ParameterLocation.Header,
Scheme = "bearer"
});
options.OperationFilter<SwaggerSecurityOperationFilter>();
options.SchemaFilter<DecimalAsStringSchemaFilter>();
options.DocumentFilter<EnumAsStringDocumentFilter>();
});
// configure microsoft openapi (aspnet 10 recommended, but cannot change decimal type to string & set allow anonymous for auth)
// currently it is disabled in routing
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, _, _) =>
{
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
document.Components.SecuritySchemes.Add("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Bearer token authentication",
Type = SecuritySchemeType.Http,
In = ParameterLocation.Header,
Scheme = "bearer"
});
document.SetReferenceHostDocument();
return Task.CompletedTask;
});
options.AddOperationTransformer((operation, context, _) =>
{
operation.Security ??= new List<OpenApiSecurityRequirement>();
var bearerRequirement = new OpenApiSecuritySchemeReference("Bearer");
operation.Security.Add(new OpenApiSecurityRequirement
{
[bearerRequirement] = []
});
return Task.CompletedTask;
});
});
// configure object storage (S3 via FluentStorage.AWS)
builder.Services.AddOptions<StorageOptions>()
.Bind(builder.Configuration.GetSection(StorageOptions.SectionName))
.Validate(o => !string.IsNullOrWhiteSpace(o.Bucket), "Storage:Bucket is required")
.Validate(o => !string.IsNullOrWhiteSpace(o.Region), "Storage:Region is required")
.ValidateOnStart();
builder.Services.AddSingleton<IBlobStorage>(sp =>
{
StorageFactory.Modules.UseAwsStorage();
var options = sp.GetRequiredService<IOptions<StorageOptions>>().Value;
if (!options.Provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Unsupported storage provider '{options.Provider}'.");
if (string.IsNullOrWhiteSpace(options.Endpoint))
throw new InvalidOperationException("Storage:Endpoint is required for S3.");
return StorageFactory.Blobs.AwsS3(
options.AccessKeyId,
options.SecretAccessKey,
null,
options.Bucket,
options.Region,
options.Endpoint);
});
builder.Services.AddSingleton<IObjectStorage, S3ObjectStorage>();
// configure email service (Resend)
builder.Services.AddOptions<EmailOptions>()
.Bind(builder.Configuration.GetSection(EmailOptions.SectionName))
.Validate(options =>
{
if (!builder.Environment.IsProduction())
return true;
try
{
EmailOptions.ValidateForProduction(options);
return true;
}
catch (OptionsValidationException)
{
return false;
}
}, "Email configuration is incomplete for production.")
.ValidateOnStart();
builder.Services.AddHttpClient<ResendClient>();
builder.Services.Configure<ResendClientOptions>(options =>
{
options.ApiToken = builder.Configuration[$"{EmailOptions.SectionName}:ApiKey"] ?? string.Empty;
});
builder.Services.AddTransient<IResend, ResendClient>();
builder.Services.AddTransient<IEmailSender<SplitzUser>, ResendIdentityEmailSender>();
builder.Services.AddScoped<AccountRecoveryService>();
// configure automapper
builder.Services.AddAutoMapper((serviceProvider, cfg) =>
{
cfg.AddCollectionMappers();
cfg.UseEntityFrameworkCoreModel<SplitzDbContext>(serviceProvider);
// Allow AutoMapper to construct profiles/value resolvers via DI.
cfg.ConstructServicesUsing(serviceProvider.GetRequiredService);
}, typeof(SplitzDbContext), typeof(MapperProfile));
builder.Services.AddSingleton<IImageProcessingService, NetVipsImageProcessingService>();
builder.Services.AddSingleton<IImageStorageService, ImageStorageService>();
builder.Services.AddScoped<IInvoiceDebtService, InvoiceDebtService>();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<SplitzDbContext>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<SplitzUser>>();
// Apply pending migrations (creates database if it doesn't exist)
await db.Database.MigrateAsync();
// Seed test data in development environment
if (app.Environment.IsDevelopment()) await SeedTestData(db, userManager);
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
// disable microsoft openapi for now
//app.MapOpenApi();
app.UseSwagger(options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
options.RouteTemplate = "/openapi/{documentName}.json";
});
app.MapScalarApiReference();
}
app.UseCors();
app.UseAuthorization();
var accountGroup = app.MapGroup("/account");
accountGroup.MapIdentityApi<SplitzUser>();
accountGroup.MapAccountRecoveryEndpoints();
app.MapControllers();
app.Run();
}
private static async Task SeedTestData(SplitzDbContext db, UserManager<SplitzUser> userManager)
{
// Check if test data already exists
if (await db.Users.AnyAsync()) return; // Test data already seeded
// Create test users
var testUsers = new List<SplitzUser>
{
new()
{
Id = Guid.NewGuid().ToString(),
UserName = "alice@example.com",
Email = "alice@example.com",
EmailConfirmed = true,
Photo = "https://i.pravatar.cc/150?img=1"
},
new()
{
Id = Guid.NewGuid().ToString(),
UserName = "bob@example.com",
Email = "bob@example.com",
EmailConfirmed = true,
Photo = "https://i.pravatar.cc/150?img=2"
},
new()
{
Id = Guid.NewGuid().ToString(),
UserName = "charlie@example.com",
Email = "charlie@example.com",
EmailConfirmed = true,
Photo = "https://i.pravatar.cc/150?img=3"
},
new()
{
Id = Guid.NewGuid().ToString(),
UserName = "diana@example.com",
Email = "diana@example.com",
EmailConfirmed = true,
Photo = "https://i.pravatar.cc/150?img=4"
}
};
// Create users with password
const string defaultPassword = "TestPassword123!";
foreach (var user in testUsers)
{
var result = await userManager.CreateAsync(user, defaultPassword);
if (!result.Succeeded)
throw new Exception(
$"Failed to create user {user.UserName}: {string.Join(", ", result.Errors.Select(e => e.Description))}");
}
// Refresh users from database to get the created IDs
var alice = await userManager.FindByEmailAsync("alice@example.com");
var bob = await userManager.FindByEmailAsync("bob@example.com");
var charlie = await userManager.FindByEmailAsync("charlie@example.com");
var diana = await userManager.FindByEmailAsync("diana@example.com");
if (alice == null || bob == null || charlie == null || diana == null)
throw new Exception("Failed to retrieve created test users");
// Create test groups
var testGroups = new List<Group>
{
new()
{
GroupId = Guid.NewGuid(),
Name = "Weekend Trip",
Photo = "https://picsum.photos/200/200?random=1",
Members = new List<SplitzUser> { alice, bob, charlie },
MembersIdHash = "",
TransactionCount = 0,
LastActivityTime = DateTime.UtcNow.AddDays(-1)
},
new()
{
GroupId = Guid.NewGuid(),
Name = "House Expenses",
Photo = "https://picsum.photos/200/200?random=2",
Members = new List<SplitzUser> { alice, bob },
MembersIdHash = "",
TransactionCount = 0,
LastActivityTime = DateTime.UtcNow.AddDays(-3)
},
new()
{
GroupId = Guid.NewGuid(),
Name = "Dinner Club",
Photo = "https://picsum.photos/200/200?random=3",
Members = new List<SplitzUser> { alice, bob, charlie, diana },
MembersIdHash = "",
TransactionCount = 0,
LastActivityTime = DateTime.UtcNow.AddDays(-7)
}
};
// Update members hash for each group
foreach (var group in testGroups) group.UpdateMembersIdHash();
// Add groups to database
db.Groups.AddRange(testGroups);
await db.SaveChangesAsync();
Console.WriteLine("Test data seeded successfully!");
Console.WriteLine($"Created {testUsers.Count} test users and {testGroups.Count} test groups");
Console.WriteLine("Test user credentials:");
Console.WriteLine($" Email: alice@example.com, Password: {defaultPassword}");
Console.WriteLine($" Email: bob@example.com, Password: {defaultPassword}");
Console.WriteLine($" Email: charlie@example.com, Password: {defaultPassword}");
Console.WriteLine($" Email: diana@example.com, Password: {defaultPassword}");
}
public static void ConfigureIdentityOptions(IdentityOptions option, EmailOptions emailOptions)
{
option.User.RequireUniqueEmail = true;
option.SignIn.RequireConfirmedEmail = emailOptions.IsAvailable;
option.Password.RequiredLength = 12;
option.Password.RequireDigit = true;
option.Password.RequireLowercase = true;
option.Password.RequireUppercase = false;
option.Password.RequireNonAlphanumeric = false;
}
}