roadie/Roadie.Api/Startup.cs

274 lines
12 KiB
C#
Raw Normal View History

2018-11-02 21:04:49 +00:00
using Mapster;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
2018-12-15 16:53:14 +00:00
using Microsoft.AspNetCore.Identity;
2019-01-08 15:51:26 +00:00
using Microsoft.AspNetCore.Identity.UI.Services;
2018-11-02 21:04:49 +00:00
using Microsoft.AspNetCore.Mvc;
2018-11-06 21:55:31 +00:00
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
2018-11-02 21:04:49 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
2018-11-17 02:44:08 +00:00
using Roadie.Api.Hubs;
2018-11-23 04:18:48 +00:00
using Roadie.Api.ModelBinding;
2018-11-02 21:04:49 +00:00
using Roadie.Api.Services;
using Roadie.Library.Caching;
2018-11-06 21:55:31 +00:00
using Roadie.Library.Configuration;
2018-11-02 21:04:49 +00:00
using Roadie.Library.Data;
2018-11-05 00:08:37 +00:00
using Roadie.Library.Encoding;
2018-11-02 21:04:49 +00:00
using Roadie.Library.Identity;
2018-11-11 16:20:33 +00:00
using Roadie.Library.Imaging;
2018-11-06 21:55:31 +00:00
using Roadie.Library.Utility;
2018-11-02 21:04:49 +00:00
using System;
2019-01-08 15:51:26 +00:00
using System.Diagnostics;
2018-11-02 21:04:49 +00:00
namespace Roadie.Api
{
public class Startup
{
private readonly IConfiguration _configuration;
private readonly ILoggerFactory _loggerFactory;
2019-01-12 00:27:49 +00:00
private ILogger Logger { get; }
2018-11-02 21:04:49 +00:00
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
{
this._configuration = configuration;
this._loggerFactory = loggerFactory;
2018-11-06 21:55:31 +00:00
2019-01-12 00:27:49 +00:00
this.Logger = this._loggerFactory.CreateLogger<Startup>();
2018-11-11 01:11:58 +00:00
TypeAdapterConfig<Roadie.Library.Data.Image, Roadie.Library.Models.Image>
.NewConfig()
.Map(i => i.ArtistId,
src => src.Artist == null ? null : (Guid?)src.Artist.RoadieId)
.Map(i => i.ReleaseId,
src => src.Release == null ? null : (Guid?)src.Release.RoadieId)
.Compile();
2018-11-06 21:55:31 +00:00
2018-11-11 01:11:58 +00:00
TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
2018-11-02 21:04:49 +00:00
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CORSPolicy");
2018-11-02 21:04:49 +00:00
app.UseAuthentication();
//app.UseSwagger();
//app.UseSwaggerUI(c =>
//{
// c.SwaggerEndpoint("/swagger/swagger.json", "Roadie API");
2018-11-02 21:04:49 +00:00
// c.RoutePrefix = string.Empty;
//});
app.UseStaticFiles();
2018-11-17 02:44:08 +00:00
app.UseSignalR(routes =>
{
routes.MapHub<PlayActivityHub>("/playActivityHub");
2018-12-14 03:52:14 +00:00
routes.MapHub<ScanActivityHub>("/scanActivityHub");
2018-11-17 02:44:08 +00:00
});
2018-12-03 04:12:47 +00:00
app.UseMvc();
2018-11-02 21:04:49 +00:00
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITokenService, TokenService>();
2018-11-03 21:21:36 +00:00
services.AddSingleton<IHttpEncoder, HttpEncoder>();
2019-01-08 15:51:26 +00:00
services.AddSingleton<IEmailSender, EmailSenderService>();
2018-11-03 21:21:36 +00:00
2018-11-11 14:46:09 +00:00
var cacheManager = new DictionaryCacheManager(this._loggerFactory.CreateLogger<DictionaryCacheManager>(), new CachePolicy(TimeSpan.FromHours(4)));
2018-11-02 21:04:49 +00:00
services.AddSingleton<ICacheManager>(cacheManager);
services.AddDbContextPool<ApplicationUserDbContext>(
2018-12-02 15:51:54 +00:00
options => options.UseMySql(this._configuration.GetConnectionString("RoadieDatabaseConnection"),
mySqlOptions =>
{
mySqlOptions.ServerVersion(new Version(5, 5), Pomelo.EntityFrameworkCore.MySql.Infrastructure.ServerType.MariaDb);
2019-02-12 02:17:24 +00:00
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
2018-12-02 15:51:54 +00:00
}
));
2018-11-02 21:04:49 +00:00
2018-11-11 01:11:58 +00:00
services.AddDbContextPool<IRoadieDbContext, RoadieDbContext>(
2018-12-02 15:51:54 +00:00
options => options.UseMySql(this._configuration.GetConnectionString("RoadieDatabaseConnection"),
mySqlOptions =>
{
mySqlOptions.ServerVersion(new Version(5, 5), Pomelo.EntityFrameworkCore.MySql.Infrastructure.ServerType.MariaDb);
2019-02-12 02:17:24 +00:00
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
2018-12-02 15:51:54 +00:00
}
));
2018-11-02 21:04:49 +00:00
services.AddIdentity<ApplicationUser, ApplicationRole>()
2018-11-10 23:26:04 +00:00
.AddRoles<ApplicationRole>()
2019-01-08 15:51:26 +00:00
.AddEntityFrameworkStores<ApplicationUserDbContext>()
.AddDefaultTokenProviders();
2018-11-02 21:04:49 +00:00
services.AddAuthorization(options =>
{
2018-11-10 23:26:04 +00:00
options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
2018-12-14 03:52:14 +00:00
options.AddPolicy("Editor", policy => policy.RequireRole("Admin", "Editor"));
2018-11-02 21:04:49 +00:00
});
services.Configure<IConfiguration>(this._configuration);
2019-01-12 00:27:49 +00:00
var corsOrigins = (this._configuration["CORSOrigins"] ?? "http://localhost:8080").Split('|');
this.Logger.LogDebug("Setting Up CORS Policy [{0}]", string.Join(", ", corsOrigins));
services.AddCors(options => options.AddPolicy("CORSPolicy", builder =>
{
builder
.WithOrigins(corsOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
2018-11-02 21:04:49 +00:00
2018-11-06 21:55:31 +00:00
services.AddSingleton<IRoadieSettings, RoadieSettings>(ctx =>
{
var settings = new RoadieSettings();
var configuration = ctx.GetService<IConfiguration>();
configuration.GetSection("RoadieSettings").Bind(settings);
var hostingEnvironment = ctx.GetService<IHostingEnvironment>();
settings.ContentPath = hostingEnvironment.WebRootPath;
2018-11-12 00:28:37 +00:00
settings.ConnectionString = this._configuration.GetConnectionString("RoadieDatabaseConnection");
2018-12-14 03:52:14 +00:00
2019-02-03 17:50:17 +00:00
// This is so 'User Secrets' can be used in Debugging
2018-12-14 03:52:14 +00:00
var integrationKeys = this._configuration.GetSection("IntegrationKeys")
.Get<IntegrationKey>();
2019-02-03 17:50:17 +00:00
if (integrationKeys != null)
2019-01-08 15:51:26 +00:00
{
settings.Integrations.ApiKeys = new System.Collections.Generic.List<ApiKey>
{
new ApiKey
{
ApiName = "LastFMApiKey",
Key = integrationKeys.LastFMApiKey,
KeySecret = integrationKeys.LastFMSecret
},
new ApiKey
2018-12-14 03:52:14 +00:00
{
ApiName = "DiscogsConsumerKey",
Key = integrationKeys.DiscogsConsumerKey,
KeySecret = integrationKeys.DiscogsConsumerSecret
},
new ApiKey
{
ApiName = "BingImageSearch",
Key = integrationKeys.BingImageSearch
}
};
2019-01-08 15:51:26 +00:00
}
2018-11-06 21:55:31 +00:00
return settings;
});
2018-12-03 04:12:47 +00:00
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
2018-11-11 16:20:33 +00:00
services.AddSingleton<IDefaultNotFoundImages, DefaultNotFoundImages>();
2018-11-12 00:28:37 +00:00
services.AddScoped<IStatisticsService, StatisticsService>();
2018-11-07 04:33:22 +00:00
services.AddScoped<ICollectionService, CollectionService>();
services.AddScoped<IPlaylistService, PlaylistService>();
services.AddScoped<IBookmarkService, BookmarkService>();
2018-11-06 21:55:31 +00:00
services.AddScoped<IArtistService, ArtistService>();
2018-11-11 01:11:58 +00:00
services.AddScoped<IImageService, ImageService>();
2018-11-12 00:28:37 +00:00
services.AddScoped<IReleaseService, ReleaseService>();
services.AddScoped<ITrackService, TrackService>();
services.AddScoped<ILabelService, LabelService>();
2018-11-15 00:16:25 +00:00
services.AddScoped<IPlaylistService, PlaylistService>();
services.AddScoped<IPlayActivityService, PlayActivityService>();
2018-11-15 04:25:40 +00:00
services.AddScoped<IGenreService, GenreService>();
services.AddScoped<ISubsonicService, SubsonicService>();
services.AddScoped<IUserService, UserService>();
2018-12-14 03:52:14 +00:00
services.AddScoped<IAdminService, AdminService>();
2018-12-22 20:33:23 +00:00
services.AddScoped<ILookupService, LookupService>();
2018-11-06 21:55:31 +00:00
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(this._configuration["Tokens:PrivateKey"]));
2018-12-02 15:51:54 +00:00
2018-11-02 21:04:49 +00:00
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
config.RequireHttpsMetadata = false;
config.SaveToken = true;
config.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = securityKey,
2018-12-01 03:22:35 +00:00
2018-11-02 21:04:49 +00:00
ValidateAudience = true,
ValidAudience = this._configuration["Tokens:Audience"],
ValidateIssuer = true,
ValidIssuer = this._configuration["Tokens:Issuer"],
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
//services.AddSwaggerGen(c =>
//{
// c.SwaggerDoc("v1", new Info
// {
// Title = "Roadie API",
// Version = "v1"
// });
//});
2018-11-17 02:44:08 +00:00
services.AddSignalR();
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
2018-11-22 23:12:57 +00:00
options.ModelBinderProviders.Insert(0, new SubsonicRequestBinderProvider());
})
2018-11-23 04:18:48 +00:00
.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
2019-01-06 21:45:52 +00:00
.AddXmlSerializerFormatters()
2018-12-04 23:26:27 +00:00
.SetCompatibilityVersion(CompatibilityVersion.Latest);
2018-11-06 21:55:31 +00:00
2018-12-15 16:53:14 +00:00
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
});
services.AddHttpContextAccessor();
2018-11-06 21:55:31 +00:00
services.AddScoped<IHttpContext>(factory =>
{
var actionContext = factory.GetService<IActionContextAccessor>()
2018-11-10 23:26:04 +00:00
.ActionContext;
2019-01-12 00:27:49 +00:00
return new HttpContext(factory.GetService<IRoadieSettings>(), new UrlHelper(actionContext));
2018-11-06 21:55:31 +00:00
});
2018-11-02 21:04:49 +00:00
}
2018-12-14 03:52:14 +00:00
private class IntegrationKey
{
public string BingImageSearch { get; set; }
public string DiscogsConsumerKey { get; set; }
public string DiscogsConsumerSecret { get; set; }
2019-01-06 21:45:52 +00:00
public string LastFMApiKey { get; set; }
public string LastFMSecret { get; set; }
2018-12-14 03:52:14 +00:00
}
2018-11-02 21:04:49 +00:00
}
}