Selector/Selector.Web/Startup.cs

258 lines
9.9 KiB
C#
Raw Normal View History

using System;
2023-01-21 16:17:46 +00:00
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
2023-01-21 16:17:46 +00:00
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
2023-01-21 16:17:46 +00:00
using Microsoft.IdentityModel.Tokens;
using Selector.Cache.Extensions;
using Selector.Events;
2021-11-29 21:48:00 +00:00
using Selector.Extensions;
2021-10-23 22:16:37 +01:00
using Selector.Model;
using Selector.Model.Extensions;
2023-01-21 16:17:46 +00:00
using Selector.Web.Auth;
using Selector.Web.Extensions;
using Selector.Web.Hubs;
2021-10-23 22:16:37 +01:00
namespace Selector.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RootOptions>(options =>
{
OptionsHelper.ConfigureOptions(options, Configuration);
});
2022-06-28 07:30:27 +01:00
services.Configure<RedisOptions>(options =>
{
Configuration.GetSection(string.Join(':', RootOptions.Key, RedisOptions.Key)).Bind(options);
});
services.Configure<NowPlayingOptions>(options =>
{
Configuration.GetSection(string.Join(':', RootOptions.Key, NowPlayingOptions.Key)).Bind(options);
});
2023-01-21 16:17:46 +00:00
services.Configure<JwtOptions>(options =>
{
Configuration.GetSection(JwtOptions._Key).Bind(options);
});
2022-06-28 07:30:27 +01:00
var config = OptionsHelper.ConfigureOptions(Configuration);
services.Configure<SpotifyAppCredentials>(options =>
{
options.ClientId = config.ClientId;
options.ClientSecret = config.ClientSecret;
});
services.AddRazorPages(o =>
{
o.Conventions.AllowAnonymousToPage("/");
o.Conventions.AuthorizePage("/Now", AuthConstants.CookieAuthentication);
o.Conventions.AuthorizePage("/Past", AuthConstants.CookieAuthentication);
o.Conventions.AllowAnonymousToPage("/Privacy");
o.Conventions.AllowAnonymousToPage("/Error");
o.Conventions.AllowAnonymousToAreaPage("Identity", "/Login");
o.Conventions.AllowAnonymousToAreaPage("Identity", "/Logout");
o.Conventions.AllowAnonymousToAreaPage("Identity", "/Register");
o.Conventions.AllowAnonymousToAreaPage("Identity", "/AccessDenied");
o.Conventions.AllowAnonymousToAreaPage("Identity", "/Lockout");
o.Conventions.AuthorizeAreaPage("Identity", "/Manage", AuthConstants.CookieAuthentication);
})
.AddRazorRuntimeCompilation();
2021-10-23 12:49:42 +01:00
services.AddControllers();
services.AddSignalR(o => o.EnableDetailedErrors = true);
services.AddHttpClient();
2021-10-23 22:16:37 +01:00
2023-01-21 16:17:46 +00:00
ConfigureDB(services, config);
ConfigureIdentity(services, config);
ConfigureAuth(services, config);
services.AddEvents();
services.AddSpotify();
ConfigureLastFm(config, services);
ConfigureRedis(services, config);
}
public void ConfigureDB(IServiceCollection services, RootOptions config)
{
services.AddDbContext<ApplicationDbContext>(options =>
2021-10-23 22:16:37 +01:00
options.UseNpgsql(Configuration.GetConnectionString("Default"))
);
2022-06-22 08:01:59 +01:00
services.AddDBPlayCountPuller();
2022-10-07 23:33:54 +01:00
services.AddTransient<IScrobbleRepository, ScrobbleRepository>()
.AddTransient<ISpotifyListenRepository, SpotifyListenRepository>();
2022-10-08 17:07:50 +01:00
services.AddTransient<IListenRepository, MetaListenRepository>();
//services.AddTransient<IListenRepository, SpotifyListenRepository>();
2023-01-21 16:17:46 +00:00
}
2021-10-24 00:23:45 +01:00
2023-01-21 16:17:46 +00:00
public void ConfigureIdentity(IServiceCollection services, RootOptions config)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
2021-10-24 00:23:45 +01:00
.AddDefaultUI()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
2021-10-24 00:23:45 +01:00
options.Password.RequiredLength = 3;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
options.SignIn.RequireConfirmedEmail = false;
});
2023-01-21 16:17:46 +00:00
}
2021-10-24 00:23:45 +01:00
2023-01-21 16:17:46 +00:00
public void ConfigureAuth(IServiceCollection services, RootOptions config)
{
2021-10-24 00:23:45 +01:00
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
2022-09-29 20:37:06 +01:00
options.ExpireTimeSpan = config.CookieExpiry;
2021-10-24 00:23:45 +01:00
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
2023-01-21 16:17:46 +00:00
var jwtConfig = Configuration.GetSection(JwtOptions._Key).Get<JwtOptions>();
services.AddAuthentication()
.AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
ValidIssuer = jwtConfig.Issuer,
ValidAudience = jwtConfig.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key))
};
});
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme, JwtBearerDefaults.AuthenticationScheme)
.Build();
options.AddPolicy(AuthConstants.CookieAuthentication, new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme)
.Build());
2023-01-21 16:17:46 +00:00
});
2023-01-21 16:17:46 +00:00
services.AddTransient<JwtTokenService>();
2021-11-03 22:27:50 +00:00
2023-01-21 16:17:46 +00:00
services.AddAuthorisationHandlers();
}
2023-01-21 16:17:46 +00:00
public void ConfigureRedis(IServiceCollection services, RootOptions config)
{
if (config.RedisOptions.Enabled)
{
Console.WriteLine("> Adding Redis...");
services.AddRedisServices(config.RedisOptions.ConnectionString);
Console.WriteLine("> Adding cache event maps...");
2021-12-20 23:04:53 +00:00
services.AddTransient<IEventMapping, ToPubSub.SpotifyLink>();
services.AddTransient<IEventMapping, ToPubSub.Lastfm>();
services.AddTransient<IEventMapping, FromPubSub.NowPlaying>();
services.AddCacheHubProxy();
Console.WriteLine("> Adding caching Spotify consumers...");
services.AddCachingSpotify();
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
2022-02-26 21:50:49 +00:00
// app.UseHttpsRedirection();
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
//app.UseHsts();
}
app.UseStaticFiles();
app.UseRouting();
2021-10-24 00:23:45 +01:00
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
2021-10-23 12:49:42 +01:00
endpoints.MapControllers();
2022-10-10 11:44:47 +01:00
endpoints.MapHub<NowPlayingHub>("/nowhub");
endpoints.MapHub<PastHub>("/pasthub");
});
}
public static void ConfigureLastFm(RootOptions config, IServiceCollection services)
{
if (config.LastfmClient is not null)
{
Console.WriteLine("> Adding Last.fm credentials...");
services.AddLastFm(config.LastfmClient, config.LastfmSecret);
if (config.RedisOptions.Enabled)
{
Console.WriteLine("> Adding caching Last.fm consumers...");
services.AddCachingLastFm();
}
}
else
{
Console.WriteLine("> No Last.fm credentials, skipping init...");
}
}
}
}