forked from Se7enseads/OnlineVotingSystem.api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
150 lines (126 loc) · 4.39 KB
/
Program.cs
File metadata and controls
150 lines (126 loc) · 4.39 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
// Imports
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OnlineVotingSystem.api.Data;
using OnlineVotingSystem.api.Endpoints;
using OnlineVotingSystem.api.Services;
var builder = WebApplication.CreateBuilder(args);
// Load connection string based on environment
var env = builder.Environment.EnvironmentName;
var connString = env == "Development"
? builder.Configuration.GetConnectionString("Development")
: builder.Configuration.GetConnectionString("Production");
if (string.IsNullOrEmpty(connString))
{
throw new InvalidOperationException("Database connection string is missing.");
}
// Configure Database (SQLite for Dev, PostgreSQL for Prod)
if (env == "Development")
{
builder.Services.AddSqlite<OnlineVotingSystemContext>(connString);
}
else
{
builder.Services.AddNpgsql<OnlineVotingSystemContext>(connString);
}
// Add JWT authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var jwtSettings = builder.Configuration.GetSection("JwtConfig"); // JWT settings from appsettings.json
var key = Convert.FromBase64String(jwtSettings["Key"]!); // Convert the key from base64 string to byte array
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtSettings["Issuer"],
ValidateIssuer = true,
ValidAudience = jwtSettings["Audience"],
ValidateAudience = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
};
});
builder.Services.AddAuthorization();
builder.Services.AddScoped<JwtService>();
builder.Services.AddScoped<ViewManagerService>();
// Define authorization policies
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AdminOnly", policy => policy.RequireClaim("IsAdmin", "true"));
// Enable CORS (for Swagger & frontend requests)
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
policy => policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
// Add Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Online Voting System API",
Version = "v1",
Description = "API for managing elections, candidates, and votes."
});
// Configure Swagger to use JWT Authentication
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Enter 'Bearer {your JWT token}'",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
Array.Empty<string>()
}
});
});
var app = builder.Build();
// Enable Swagger only in development
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Online Voting System API v1");
c.RoutePrefix = string.Empty; // Make Swagger available at root (`/`)
c.DocumentTitle = "Online Voting System API";
});
}
// Enable CORS
app.UseCors("AllowAll");
// Enable authentication & authorization
app.UseAuthentication();
app.UseAuthorization();
// Map endpoints
app.MapAuthEndpoints();
app.MapCandidateEndpoints();
app.MapElectionEndpoints();
app.MapPositionEndpoints();
app.MapUsersEndpoints();
app.MapVoteEndpoints();
// Apply pending migrations
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<OnlineVotingSystemContext>();
var viewManager = scope.ServiceProvider.GetRequiredService<ViewManagerService>();
dbContext.Database.EnsureCreated(); // Ensure DB exists
viewManager.EnsureViewsCreated(); // Create views
}
app.Run();