Wave/Wave/Program.cs

239 lines
9.3 KiB
C#
Raw Normal View History

2024-01-11 12:54:29 +00:00
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
2024-01-21 20:03:06 +00:00
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
2024-01-11 12:54:29 +00:00
using Microsoft.AspNetCore.Identity;
2024-02-08 14:44:37 +00:00
using Microsoft.AspNetCore.Identity.UI.Services;
2024-02-02 15:51:56 +00:00
using Microsoft.AspNetCore.StaticFiles;
2024-01-11 12:54:29 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
2024-01-21 20:03:06 +00:00
using StackExchange.Redis;
using System.Text;
using Tomlyn.Extensions.Configuration;
2024-01-11 12:54:29 +00:00
using Wave.Components;
using Wave.Components.Account;
using Wave.Data;
using Wave.Services;
2024-02-03 14:54:16 +00:00
using Wave.Utilities;
2024-01-11 12:54:29 +00:00
2024-02-07 11:19:33 +00:00
var logMessages = new List<string>();
2024-01-11 12:54:29 +00:00
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddJsonFile(Path.Combine(FileSystemService.ConfigurationDirectory, "config.json"), true, false)
.AddYamlFile(Path.Combine(FileSystemService.ConfigurationDirectory, "config.yml"), true, false)
.AddTomlFile(Path.Combine(FileSystemService.ConfigurationDirectory, "config.toml"), true, false)
.AddIniFile( Path.Combine(FileSystemService.ConfigurationDirectory, "config.ini"), true, false)
.AddXmlFile( Path.Combine(FileSystemService.ConfigurationDirectory, "config.xml"), true, false)
2024-02-07 11:19:33 +00:00
.AddEnvironmentVariables("WAVE_");
2024-01-11 12:54:29 +00:00
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
2024-02-03 14:54:16 +00:00
builder.Services.AddControllers(options => {
2024-02-07 11:19:33 +00:00
options.OutputFormatters.Add(new SyndicationFeedFormatter());
2024-02-03 14:54:16 +00:00
});
builder.Services.AddOutputCache();
2024-01-11 12:54:29 +00:00
2024-01-21 20:03:06 +00:00
#region Data Protection & Redis
if (builder.Configuration.GetConnectionString("Redis") is { } redisUri) {
2024-02-07 11:19:33 +00:00
var redis = ConnectionMultiplexer.Connect(redisUri);
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis)
.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration() {
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
});
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = redisUri;
options.InstanceName = "WaveDistributedCache";
});
builder.Services.AddStackExchangeRedisOutputCache(options => {
options.Configuration = redisUri;
options.InstanceName = "WaveOutputCache";
});
2024-01-21 20:03:06 +00:00
} else {
2024-02-07 11:19:33 +00:00
builder.Services.AddDataProtection()
.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration() {
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
});
logMessages.Add("No Redis connection string found.");
2024-01-21 20:03:06 +00:00
}
#endregion
2024-01-11 14:39:09 +00:00
#region Authentication & Authorization
2024-01-11 12:54:29 +00:00
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
2024-01-16 12:52:24 +00:00
// Authors: Can create Articles, require them to be reviewed
// Reviewers: Can review Articles, but cannot create them themselves
// Moderators: Can delete Articles / take them Offline
// Admins: Can do anything, and assign roles to other users
builder.Services.AddAuthorizationBuilder()
2024-02-07 11:19:33 +00:00
.AddPolicy("ArticleEditPermissions", p => p.RequireRole("Author", "Admin"))
.AddPolicy("ArticleReviewPermissions", p => p.RequireRole("Reviewer", "Admin"))
.AddPolicy("ArticleDeletePermissions", p => p.RequireRole("Moderator", "Admin"))
.AddPolicy("CategoryManagePermissions", p => p.RequireRole("Admin"))
.AddPolicy("RoleAssignPermissions", p => p.RequireRole("Admin"))
2024-02-07 11:19:33 +00:00
.AddPolicy("ArticleEditOrReviewPermissions", p => p.RequireRole("Author", "Reviewer", "Admin"));
2024-01-16 12:52:24 +00:00
builder.Services.AddAuthentication(options => {
2024-02-07 11:19:33 +00:00
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
}).AddIdentityCookies();
2024-01-11 12:54:29 +00:00
2024-01-11 14:39:09 +00:00
#endregion
#region Identity
string connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
2024-02-07 11:19:33 +00:00
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
2024-01-14 18:04:06 +00:00
builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
2024-02-07 11:19:33 +00:00
options.UseNpgsql(connectionString));
2024-01-11 12:54:29 +00:00
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
2024-02-07 11:19:33 +00:00
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<UserClaimsFactory>();
2024-01-11 12:54:29 +00:00
2024-01-11 14:39:09 +00:00
#endregion
#region Services
builder.Services.AddHealthChecks();
2024-01-11 14:39:09 +00:00
builder.Services.AddLocalization(options => {
2024-02-07 11:19:33 +00:00
options.ResourcesPath = "Resources";
2024-01-11 14:39:09 +00:00
});
builder.Services.AddScoped<ImageService>();
2024-02-03 18:45:46 +00:00
builder.Services.AddHttpClient();
2024-01-11 14:39:09 +00:00
builder.Services.Configure<Features>(builder.Configuration.GetSection(nameof(Features)));
builder.Services.Configure<Customization>(builder.Configuration.GetSection(nameof(Customization)));
builder.Services.AddCascadingValue("TitlePrefix",
2024-02-07 11:19:33 +00:00
sf => (sf.GetService<IOptions<Customization>>()?.Value.AppName ?? "Wave") + " - ");
2024-02-18 14:06:31 +00:00
var emailConfig = builder.Configuration.GetSection("Email").Get<EmailConfiguration>();
builder.Services.Configure<EmailConfiguration>(builder.Configuration.GetSection("Email"));
if (emailConfig?.Smtp.Count > 0) {
if (string.IsNullOrWhiteSpace(emailConfig.SenderEmail)) {
throw new ApplicationException(
"Email providers have been configured, but no SenderEmail. " +
"Please provider the sender email address used for email distribution.");
}
foreach (var smtp in emailConfig.Smtp) {
builder.Services.AddKeyedScoped<IEmailService, LiveEmailService>(smtp.Key.ToLower(), (provider, key) =>
ActivatorUtilities.CreateInstance<LiveEmailService>(provider,
provider.GetRequiredService<IOptions<EmailConfiguration>>().Value.Smtp[(string)key]));
}
if (emailConfig.Smtp.Keys.Any(k => k.Equals("live", StringComparison.CurrentCultureIgnoreCase))) {
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IAdvancedEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IEmailSender<ApplicationUser>, SmtpEmailSender>();
} else {
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
logMessages.Add("No 'live' email provider configured.");
}
if (emailConfig.Smtp.Keys.Any(k => k.Equals("bulk", StringComparison.CurrentCultureIgnoreCase))) {
builder.Services.AddScoped<NewsletterBackgroundService>();
} else if (builder.Configuration.GetSection(nameof(Features)).Get<Features>()?.EmailSubscriptions is not true) {
throw new ApplicationException(
"Email subscriptions have been enabled, but no 'bulk' email provider was configured. " +
"Disable email subscriptions or provide the mail provider for bulk sending");
}
} else {
2024-02-07 11:19:33 +00:00
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
2024-02-18 14:06:31 +00:00
logMessages.Add("No email provider configured.");
}
2024-02-18 12:06:09 +00:00
builder.Services.AddScoped<EmailFactory>();
builder.Services.AddSingleton<IMessageDisplay, MessageService>();
builder.Services.AddSingleton<FileSystemService>();
2024-02-12 15:34:56 +00:00
builder.Services.AddSingleton<EmailTemplateService>();
2024-02-07 23:50:24 +00:00
builder.Services.AddHostedService<EmailBackgroundWorker>();
2024-01-11 14:39:09 +00:00
#endregion
2024-01-22 15:08:47 +00:00
string[] cultures = ["en-US", "en-GB", "de-DE"];
builder.Services.Configure<RequestLocalizationOptions>(options => {
2024-02-07 11:19:33 +00:00
options.ApplyCurrentCultureToResponseHeaders = true;
options.FallBackToParentCultures = true;
options.FallBackToParentUICultures = true;
options.SetDefaultCulture(cultures[0])
.AddSupportedCultures(cultures)
.AddSupportedUICultures(cultures);
2024-01-22 15:08:47 +00:00
});
2024-01-11 12:54:29 +00:00
var app = builder.Build();
// Configure the HTTP request pipeline.
2024-01-11 14:39:09 +00:00
if (app.Environment.IsDevelopment()) {
2024-02-07 11:19:33 +00:00
app.UseMigrationsEndPoint();
2024-01-11 14:39:09 +00:00
} else {
2024-02-07 11:19:33 +00:00
app.UseExceptionHandler("/Error", createScopeForErrors: true);
2024-01-11 12:54:29 +00:00
}
2024-02-02 15:51:56 +00:00
app.UseStaticFiles(new StaticFileOptions {
2024-02-07 11:19:33 +00:00
ContentTypeProvider = new FileExtensionContentTypeProvider {
Mappings = {
[".jxl"] = "image/jxl"
}
}
2024-02-02 15:51:56 +00:00
});
2024-01-11 12:54:29 +00:00
app.UseAntiforgery();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
2024-01-11 12:54:29 +00:00
// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();
app.MapHealthChecks("/health");
app.MapControllers();
app.UseOutputCache();
2024-01-22 15:08:47 +00:00
app.UseRequestLocalization();
2024-01-11 14:39:09 +00:00
2024-02-07 11:19:33 +00:00
foreach (string message in logMessages) {
app.Logger.LogInformation("{message}", message);
}
2024-01-15 19:47:10 +00:00
{
2024-02-07 11:19:33 +00:00
using var scope = app.Services.CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (userManager.GetUsersInRoleAsync("Admin").Result.Any() is false) {
IDistributedCache cache = app.Services.GetRequiredService<IDistributedCache>();
// Check first wheter the password exists already
string admin = await cache.GetStringAsync("admin_promote_key");
// If it does not exist, create a new one and save it to redis
if (string.IsNullOrWhiteSpace(admin)){
admin = Guid.NewGuid().ToString("N")[..16];
await cache.SetAsync("admin_promote_key", Encoding.UTF8.GetBytes(admin), new DistributedCacheEntryOptions{});
}
2024-02-07 11:19:33 +00:00
app.Logger.LogWarning("There is currently no user in your installation with the admin role, " +
"go to /Admin and use the following password to self promote your account: {admin}", admin);
}
2024-01-15 19:47:10 +00:00
}
2024-01-11 12:54:29 +00:00
app.Run();