-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
177 lines (153 loc) · 5.83 KB
/
Program.cs
File metadata and controls
177 lines (153 loc) · 5.83 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
using ev_station_booking_system_api.Repositories;
using ev_station_booking_system_api.Services;
using ev_station_booking_system_api.Auth;
using ev_station_booking_system_api.Utils;
using ev_station_booking_system_api.Data;
using ev_station_booking_system_api.Database;
using Microsoft.OpenApi.Models;
using MongoDB.Driver;
using DotNetEnv;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// ------------------ Load Environment ------------------
Env.Load();
// ------------------ MongoDB Safe Setup ------------------
var connectionString = Environment.GetEnvironmentVariable("MONGODB_CONNECTION_STRING")
?? builder.Configuration.GetConnectionString("MongoDB")
?? builder.Configuration["MongoDB:ConnectionString"]
?? "mongodb://localhost:27017";
var databaseName = Environment.GetEnvironmentVariable("MONGODB_DATABASE")
?? builder.Configuration["MongoDB:DatabaseName"]
?? "ev_station_booking_db";
try
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase(databaseName);
builder.Services.AddSingleton<IMongoDatabase>(database);
Console.WriteLine($"✅ Connected to MongoDB database: {databaseName}");
}
catch (Exception ex)
{
Console.WriteLine($"⚠️ MongoDB connection failed: {ex.Message}");
Console.WriteLine("Running in Swagger-only mode (no database).");
}
// ------------------ Service Registrations ------------------
builder.Services.AddScoped<IUserAccountRepository, UserAccountRepository>();
builder.Services.AddScoped<UserAccountService>();
builder.Services.AddScoped<JwtTokenGenerator>();
builder.Services.AddSingleton<MongoDbConnectionChecker>();
builder.Services.AddScoped<IChargingStationRepository, ChargingStationRepository>();
builder.Services.AddScoped<IChargingStationService, ChargingStationService>();
builder.Services.AddScoped<IBookingRepository, BookingRepository>();
builder.Services.AddScoped<IBookingService, BookingService>();
builder.Services.AddScoped<DatabaseInitializer>();
builder.Services.AddScoped<IEVOwnerRepository, EVOwnerRepository>();
builder.Services.AddScoped<IEVOwnerService, EVOwnerService>();
builder.Services.AddSingleton<BookingContext>();
// ------------------ Authentication ------------------
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidAudience = builder.Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"] ?? "default_jwt_secret_key")
)
};
});
// ------------------ Controllers ------------------
builder.Services.AddControllers();
// ------------------ Swagger / OpenAPI ------------------
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "EV Station Booking System API",
Description = "An ASP.NET Core Web API for managing electric vehicle charging station bookings",
Contact = new OpenApiContact
{
Name = "EV Booking Support",
Email = "support@evbooking.com"
},
License = new OpenApiLicense
{
Name = "MIT License",
Url = new Uri("https://opensource.org/licenses/MIT")
}
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFilename);
if (File.Exists(xmlPath))
options.IncludeXmlComments(xmlPath);
options.EnableAnnotations();
options.SchemaFilter<ev_station_booking_system_api.EnumSchemaFilter>();
// ✅ JWT Auth support in Swagger
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid JWT token with 'Bearer' prefix",
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
// ------------------ CORS ------------------
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// ------------------ Build App ------------------
var app = builder.Build();
// ------------------ Middleware ------------------
// ✅ 1. Swagger must come before HTTPS redirection
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "EV Station Booking API v1");
options.RoutePrefix = "swagger"; // ensure swagger runs under /swagger
options.DocumentTitle = "EV Station Booking System API";
options.DefaultModelsExpandDepth(-1);
options.DisplayRequestDuration();
options.EnableDeepLinking();
options.EnableFilter();
options.ShowExtensions();
options.EnableValidator();
});
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();