-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
195 lines (166 loc) · 7.51 KB
/
Copy pathProgram.cs
File metadata and controls
195 lines (166 loc) · 7.51 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
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using progect_DEPI.Models;
using Rotativa.AspNetCore;
namespace progect_DEPI
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new InvalidOperationException("ConnectionStrings:DefaultConnection must be configured before starting the application.");
}
// Add services to the container.
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(connectionString);
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
options.AddPolicy("UserOnly", policy => policy.RequireRole("User"));
});
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
//.AddDefaultTokenProviders();
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
RotativaConfiguration.Setup(app.Environment.WebRootPath, "Rotativa");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var roles = new[] { "Admin", "User" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
await roleManager.CreateAsync(new IdentityRole(role));
}
}
var bootstrapAdminEnabled = builder.Configuration.GetValue<bool>("BootstrapAdmin:Enabled");
if (bootstrapAdminEnabled)
{
using var scope = app.Services.CreateScope();
await EnsureBootstrapAdminAsync(scope.ServiceProvider, builder.Configuration);
}
app.Run();
}
private static async Task EnsureBootstrapAdminAsync(IServiceProvider services, IConfiguration configuration)
{
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
var dbContext = services.GetRequiredService<ApplicationDbContext>();
var email = configuration["BootstrapAdmin:Email"];
var fullName = configuration["BootstrapAdmin:FullName"];
var password = configuration["BootstrapAdmin:Password"];
if (string.IsNullOrWhiteSpace(email)
|| string.IsNullOrWhiteSpace(fullName)
|| string.IsNullOrWhiteSpace(password))
{
throw new InvalidOperationException("BootstrapAdmin:Email, BootstrapAdmin:FullName and BootstrapAdmin:Password are required when BootstrapAdmin:Enabled is true.");
}
await using var transaction = await dbContext.Database.BeginTransactionAsync();
try
{
var identityUser = await userManager.FindByEmailAsync(email);
if (identityUser == null)
{
identityUser = new IdentityUser
{
UserName = email,
Email = email
};
var createResult = await userManager.CreateAsync(identityUser, password);
if (!createResult.Succeeded)
{
throw new InvalidOperationException("Bootstrap administrator creation failed.");
}
}
var linkedProfiles = await dbContext.Users
.Where(user => user.IdentityId == identityUser.Id)
.ToListAsync();
if (linkedProfiles.Count > 1)
{
throw new InvalidOperationException("Bootstrap administrator has duplicate domain profiles.");
}
var domainUser = linkedProfiles.SingleOrDefault();
if (domainUser == null)
{
var matchingProfiles = await dbContext.Users
.Where(user => user.Email == email)
.ToListAsync();
if (matchingProfiles.Count > 1)
{
throw new InvalidOperationException("Bootstrap administrator has duplicate email profiles.");
}
domainUser = matchingProfiles.SingleOrDefault();
if (domainUser != null)
{
if (!string.IsNullOrWhiteSpace(domainUser.IdentityId)
&& domainUser.IdentityId != identityUser.Id)
{
throw new InvalidOperationException("Bootstrap administrator email is already linked to another profile.");
}
domainUser.IdentityId = identityUser.Id;
}
else
{
domainUser = new User
{
FullName = fullName,
Email = email,
Picture = null,
CreatedAt = DateTime.Now,
UpdateAt = DateTime.Now,
IdentityId = identityUser.Id
};
dbContext.Users.Add(domainUser);
}
}
if (!await userManager.IsInRoleAsync(identityUser, "Admin"))
{
var roleResult = await userManager.AddToRoleAsync(identityUser, "Admin");
if (!roleResult.Succeeded)
{
throw new InvalidOperationException("Bootstrap administrator role assignment failed.");
}
}
await dbContext.SaveChangesAsync();
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
}
}