-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
163 lines (139 loc) · 5.26 KB
/
Copy pathProgram.cs
File metadata and controls
163 lines (139 loc) · 5.26 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
using System.Text;
using EricstermerCom.Components;
using EricstermerCom.Data;
using EricstermerCom.Features.Admin;
using EricstermerCom.Features.Admin.Projects;
using EricstermerCom.Features.Admin.Recommendations;
using EricstermerCom.Features.Admin.Skills;
using EricstermerCom.Features.Experience.Services;
using EricstermerCom.Features.Home.Services;
using EricstermerCom.Features.Projects.Services;
using EricstermerCom.Features.Recommendations.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
var config = sp.GetRequiredService<IConfiguration>();
var connectionString = config.GetConnectionString("Default")
?? "Data Source=ericstermer.db";
if (connectionString.Contains("Host=", StringComparison.OrdinalIgnoreCase)
|| connectionString.Contains("Server=", StringComparison.OrdinalIgnoreCase))
{
options.UseNpgsql(connectionString);
}
else
{
options.UseSqlite(connectionString);
}
});
builder.Services.AddAuthentication("EricstermerCookie")
.AddCookie("EricstermerCookie", options =>
{
options.Cookie.Name = "Ericstermer.Auth";
options.LoginPath = "/admin/login";
options.LogoutPath = "/admin/logout";
options.AccessDeniedPath = "/admin/login";
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Admin", p => p.RequireAuthenticatedUser().RequireClaim("admin", "true"));
});
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<AdminAuthService>();
builder.Services.AddScoped<GetFeaturedProjects>();
builder.Services.AddScoped<GetSkills>();
builder.Services.AddScoped<GetProjects>();
builder.Services.AddScoped<GetRecommendations>();
builder.Services.AddScoped<ProjectAdminService>();
builder.Services.AddScoped<SkillAdminService>();
builder.Services.AddScoped<RecommendationAdminService>();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var config = scope.ServiceProvider.GetRequiredService<IConfiguration>();
var connectionString = config.GetConnectionString("Default")
?? "Data Source=ericstermer.db";
var isPostgres = connectionString.Contains("Host=", StringComparison.OrdinalIgnoreCase)
|| connectionString.Contains("Server=", StringComparison.OrdinalIgnoreCase);
if (isPostgres)
{
db.Database.EnsureCreated();
}
else
{
db.Database.Migrate();
}
await SeedData.RunAsync(scope.ServiceProvider);
}
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/not-found", createScopeForErrors: true);
app.UseHsts();
}
else
{
app.UseDeveloperExceptionPage();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.MapPost("/api/admin/logout", async (HttpContext ctx, AdminAuthService auth) =>
{
await auth.SignOutAsync();
ctx.Response.Redirect("/");
return Results.Empty;
}).DisableAntiforgery();
app.MapGet("/sitemap.xml", (HttpContext ctx) =>
{
var baseUrl = $"{ctx.Request.Scheme}://{ctx.Request.Host.Value}".TrimEnd('/');
var urls = new[]
{
("/", "1.0", "weekly"),
};
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" +
string.Join("\n", urls.Select(u =>
$" <url>\n <loc>{baseUrl}{u.Item1}</loc>\n <changefreq>{u.Item3}</changefreq>\n <priority>{u.Item2}</priority>\n </url>")) +
"\n</urlset>\n";
return Results.Content(xml, "application/xml", Encoding.UTF8);
});
app.MapPost("/api/admin/login", async (HttpContext ctx, AdminAuthService auth) =>
{
var form = await ctx.Request.ReadFormAsync();
var email = form["Email"].ToString();
var password = form["Password"].ToString();
var returnUrl = form["ReturnUrl"].ToString();
var result = await auth.SignInAsync(email, password);
if (result.Success)
{
var dest = !string.IsNullOrWhiteSpace(returnUrl) && Uri.IsWellFormedUriString(returnUrl, UriKind.Relative)
? returnUrl
: "/admin";
ctx.Response.Redirect(dest);
return Results.Empty;
}
var back = "/admin/login?error=" + Uri.EscapeDataString(result.Error ?? "Sign-in failed.");
if (!string.IsNullOrWhiteSpace(email))
back += "&email=" + Uri.EscapeDataString(email);
if (!string.IsNullOrWhiteSpace(returnUrl))
back += "&returnUrl=" + Uri.EscapeDataString(returnUrl);
ctx.Response.Redirect(back);
return Results.Empty;
}).DisableAntiforgery();
app.Run();