-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
118 lines (99 loc) · 4.04 KB
/
Program.cs
File metadata and controls
118 lines (99 loc) · 4.04 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
using System.Text;
using Leafy_Library.Components;
using Leafy_Library.Models;
using Leafy_Library.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// MongoDB settings
builder.Services.Configure<MongoDbSettings>(
builder.Configuration.GetSection("MongoDb"));
// JWT settings
builder.Services.Configure<JwtSettings>(
builder.Configuration.GetSection("Jwt"));
// Embedding settings
builder.Services.Configure<EmbeddingSettings>(
builder.Configuration.GetSection("Embedding"));
// Services
builder.Services.AddHttpClient<EmbeddingService>();
builder.Services.AddSingleton<DatabaseService>();
builder.Services.AddSingleton<BookService>();
builder.Services.AddSingleton<AuthorService>();
builder.Services.AddSingleton<ReviewService>();
builder.Services.AddSingleton<IssueDetailService>();
builder.Services.AddSingleton<ReservationService>();
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<TokenService>();
builder.Services.AddScoped<JwtAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(
provider => provider.GetRequiredService<JwtAuthenticationStateProvider>());
// Authentication with JWT Bearer (for API endpoints / middleware)
var jwtSecret = builder.Configuration["Jwt:Secret"]
?? throw new InvalidOperationException("JWT Secret must be configured");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? "LeafyLibrary",
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt:Audience"] ?? "LeafyLibraryUsers",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy =>
policy.RequireRole("Admin"));
});
builder.Services.AddCascadingAuthenticationState();
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapControllers();
// Login API endpoint — matches GET /users/login/:username from the Express app.
// If the user exists, logs them in; if not, creates a new user automatically.
app.MapGet("/api/users/login/{username}", async (string username, UserService userService, TokenService tokenService) =>
{
if (string.IsNullOrWhiteSpace(username))
{
return Results.BadRequest(new { message = "Username is required" });
}
var user = await userService.GetOrCreateUserAsync(username);
var token = tokenService.CreateToken(user);
return Results.Ok(new
{
user.Id,
user.Name,
user.IsAdmin,
Token = token
});
});
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// Ensure the Atlas Search index exists before accepting requests
var dbService = app.Services.GetRequiredService<DatabaseService>();
await dbService.EnsureSearchIndexAsync();
var embeddingService = app.Services.GetRequiredService<EmbeddingService>();
await dbService.EnsureVectorSearchIndexAsync();
await dbService.GenerateEmbeddingsAsync(embeddingService);
app.Run();