roadie/RoadieApi/Startup.cs

197 lines
7.5 KiB
C#
Raw Normal View History

2018-11-02 21:04:49 +00:00
using Mapster;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
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 Microsoft.OData.Edm;
using Newtonsoft.Json;
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-06 21:55:31 +00:00
using Roadie.Library.Utility;
2018-11-02 21:04:49 +00:00
using System;
using System.IO;
using System.Reflection;
2018-11-06 02:41:51 +00:00
using models = Roadie.Library.Models;
2018-11-02 21:04:49 +00:00
namespace Roadie.Api
{
public class Startup
{
private readonly IConfiguration _configuration;
private readonly ILoggerFactory _loggerFactory;
2018-11-10 23:26:04 +00:00
//public static string AssemblyDirectory
//{
// get
// {
// string codeBase = Assembly.GetExecutingAssembly().CodeBase;
// var uri = new UriBuilder(codeBase);
// string path = Uri.UnescapeDataString(uri.Path);
// return Path.GetDirectoryName(path);
// }
//}
2018-11-05 00:08:37 +00:00
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
2018-11-06 22:59:48 +00:00
TypeAdapterConfig<Roadie.Library.Data.Release, Roadie.Library.Models.Releases.ReleaseList>
.NewConfig()
.Map(rml => rml.ArtistId,
src => src.Artist.RoadieId)
.Compile();
TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
2018-11-06 21:55:31 +00:00
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();
}
loggerFactory.AddConsole(LogLevel.Trace);
app.UseCors("Cors");
app.UseAuthentication();
//app.UseSwagger();
//app.UseSwaggerUI(c =>
//{
// c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyComics API v1");
// c.RoutePrefix = string.Empty;
//});
app.UseMvc(b =>
{
b.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("Cors", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddSingleton<ITokenService, TokenService>();
2018-11-03 21:21:36 +00:00
services.AddSingleton<IHttpEncoder, HttpEncoder>();
var cacheManager = new MemoryCacheManager(this._loggerFactory.CreateLogger<MemoryCacheManager>(), new CachePolicy(TimeSpan.FromHours(4)));
2018-11-02 21:04:49 +00:00
services.AddSingleton<ICacheManager>(cacheManager);
services.AddDbContextPool<ApplicationUserDbContext>(
options => options.UseMySql(this._configuration.GetConnectionString("RoadieDatabaseConnection")
));
2018-11-02 21:04:49 +00:00
services.AddDbContextPool<IRoadieDbContext, RoadieDbContext>(
options => options.UseMySql(this._configuration.GetConnectionString("RoadieDatabaseConnection")
));
2018-11-02 21:04:49 +00:00
services.AddIdentity<ApplicationUser, ApplicationRole>()
2018-11-10 23:26:04 +00:00
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationUserDbContext>();
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"));
options.AddPolicy("Editor", policy => policy.RequireRole("Editor"));
2018-11-02 21:04:49 +00:00
});
services.Configure<IConfiguration>(this._configuration);
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;
return settings;
});
2018-11-07 04:33:22 +00:00
services.AddScoped<ICollectionService, CollectionService>();
services.AddScoped<IPlaylistService, PlaylistService>();
2018-11-06 21:55:31 +00:00
services.AddScoped<IArtistService, ArtistService>();
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(this._configuration["Tokens:PrivateKey"]));
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,
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"
// });
//});
services.AddOData();
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
2018-11-05 00:08:37 +00:00
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
2018-11-02 21:04:49 +00:00
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
2018-11-06 21:55:31 +00:00
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;
2018-11-06 21:55:31 +00:00
return new HttpContext(new UrlHelper(actionContext));
});
2018-11-02 21:04:49 +00:00
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<models.Artist>("Artist");
builder.EntitySet<models.Label>("Label");
2018-11-06 02:41:51 +00:00
builder.EntitySet<models.Releases.Release>("Release");
2018-11-02 21:04:49 +00:00
return builder.GetEdmModel();
}
}
}