yavsc/Yavsc/Startup/Startup.cs

354 lines
16 KiB
C#
Raw Normal View History

2016-05-17 18:22:18 +02:00
using System;
using System.Globalization;
2016-11-07 19:34:56 +01:00
using System.IO;
2016-05-17 18:22:18 +02:00
using System.Reflection;
2016-08-04 13:40:39 +02:00
using System.Threading.Tasks;
2016-05-17 18:22:18 +02:00
using System.Web.Optimization;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
2016-08-04 13:40:39 +02:00
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
2016-05-17 18:22:18 +02:00
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Net.Http.Headers;
using Yavsc.Formatters;
using Yavsc.Models;
using Yavsc.Services;
2017-01-19 12:59:49 +01:00
using Yavsc.ViewModels.Auth.Handlers;
2016-05-17 18:22:18 +02:00
namespace Yavsc
{
public partial class Startup
2016-05-17 18:22:18 +02:00
{
2016-11-03 14:52:17 +01:00
public static string ConnectionString { get; private set; }
2016-11-14 12:17:07 +01:00
public static string UserBillsDirName { private set; get; }
2016-12-01 17:34:29 +01:00
public static string AvatarsDirName { private set; get; }
2016-11-03 14:52:17 +01:00
public static string Authority { get; private set; }
public static string Audience { get; private set; }
public static string Temp { get; set; }
2016-11-14 12:17:07 +01:00
public static SiteSettings SiteSetup { get; private set; }
2016-11-07 19:34:56 +01:00
private static ILogger logger;
2016-05-17 18:22:18 +02:00
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
BundleTable.EnableOptimizations = false;
}
BundleConfig.RegisterBundles(BundleTable.Bundles);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];
2016-05-17 18:22:18 +02:00
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
var siteSettings = Configuration.GetSection("Site");
services.Configure<SiteSettings>(siteSettings);
var smtpSettings = Configuration.GetSection("Smtp");
services.Configure<SmtpSettings>(smtpSettings);
var googleSettings = Configuration.GetSection("Authentication").GetSection("Google");
services.Configure<GoogleAuthSettings>(googleSettings);
var cinfoSettings = Configuration.GetSection("Authentication").GetSection("Societeinfo");
services.Configure<CompanyInfoSettings>(cinfoSettings);
2016-05-26 14:52:11 +02:00
var oauthLocalAppSettings = Configuration.GetSection("Authentication").GetSection("OAuth2LocalApp");
services.Configure<OAuth2AppSettings>(oauthLocalAppSettings);
var oauthFacebookSettings = Configuration.GetSection("Authentication").GetSection("Facebook");
services.Configure<FacebookOAuth2AppSettings>(oauthFacebookSettings);
2016-05-17 18:22:18 +02:00
2016-11-03 14:52:17 +01:00
/* services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new ProducesAttribute("text/x-tex"));
options.Filters.Add(new ProducesAttribute("text/pdf"));
});*/
2016-05-17 18:22:18 +02:00
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en")
};
var supportedUICultures = new[]
{
new CultureInfo("fr"),
new CultureInfo("en")
2016-05-17 18:22:18 +02:00
};
// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedUICultures;
2016-05-17 18:22:18 +02:00
// You can change which providers are configured to determine the culture for requests, or even add a custom
// provider with your own logic. The providers will be asked in order to provide a culture for each request,
// and the first to provide a non-null result that is in the configured supported cultures list will be used.
// By default, the following built-in providers are configured:
// - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
// - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
// - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
//options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
//{
// // My custom request culture logic
// return new ProviderCultureResult("en");
//}));
});
2016-11-03 14:52:17 +01:00
2016-05-17 18:22:18 +02:00
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SiteSettings>), typeof(OptionsManager<SiteSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<SmtpSettings>), typeof(OptionsManager<SmtpSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<GoogleAuthSettings>), typeof(OptionsManager<GoogleAuthSettings>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<CompanyInfoSettings>), typeof(OptionsManager<CompanyInfoSettings>)));
2016-06-06 12:38:11 +02:00
2016-11-03 14:52:17 +01:00
// DataProtection
ConfigureProtectionServices(services);
2016-05-17 18:22:18 +02:00
// Add framework services.
services.AddEntityFramework()
.AddNpgsql()
.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(ConnectionString))
2016-05-17 18:22:18 +02:00
;
2016-11-03 14:52:17 +01:00
ConfigureOAuthServices(services);
2016-05-17 18:22:18 +02:00
services.AddCors(
/*
options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins("http://lua.pschneider.fr");
});
}
*/
);
2016-05-20 12:56:42 +02:00
// Add memory cache services
services.AddCaching();
2016-05-17 18:22:18 +02:00
2016-05-20 12:56:42 +02:00
// Add session related services.
services.AddSession();
// Add the system clock service
services.AddSingleton<ISystemClock, SystemClock>();
2016-05-29 03:11:38 +02:00
2016-05-17 18:22:18 +02:00
services.AddAuthorization(options =>
{
options.AddPolicy("AdministratorOnly", policy =>
{
policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Constants.AdminGroupName);
});
2016-05-17 18:22:18 +02:00
options.AddPolicy("FrontOffice", policy => policy.RequireRole(Constants.FrontOfficeGroupName));
options.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("yavsc")
2016-06-06 12:38:11 +02:00
.RequireAuthenticatedUser().Build());
2016-05-17 18:22:18 +02:00
// options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
// options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement()));
2016-06-01 23:47:06 +02:00
// options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
2016-05-17 18:22:18 +02:00
});
services.AddSingleton<IAuthorizationHandler, HasBadgeHandler>();
services.AddSingleton<IAuthorizationHandler, HasTemporaryPassHandler>();
services.AddSingleton<IAuthorizationHandler, BlogEditHandler>();
services.AddSingleton<IAuthorizationHandler, BlogViewHandler>();
services.AddSingleton<IAuthorizationHandler, CommandEditHandler>();
services.AddSingleton<IAuthorizationHandler, CommandViewHandler>();
2016-05-30 18:30:35 +02:00
services.AddSingleton<IAuthorizationHandler, PostUserFileHandler>();
services.AddSingleton<IAuthorizationHandler, EstimateViewHandler>();
services.AddSingleton<IAuthorizationHandler, ViewFileHandler>();
2016-05-17 18:22:18 +02:00
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
config.Filters.Add(new ProducesAttribute("application/json"));
2016-05-17 18:22:18 +02:00
config.OutputFormatters.Add(new PdfFormatter());
}).AddFormatterMappings(
config => config.SetMediaTypeMappingForFormat("text/pdf",
new MediaTypeHeaderValue("text/pdf"))
).AddFormatterMappings(
config => config.SetMediaTypeMappingForFormat("text/x-tex",
new MediaTypeHeaderValue("text/x-tex"))
)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
options =>
{
options.ResourcesPath = "Resources";
2016-05-27 23:48:55 +02:00
}).AddDataAnnotationsLocalization();
2016-05-17 18:22:18 +02:00
services.AddScoped<LanguageActionFilter>();
// Inject ticket formatting
2016-05-17 18:22:18 +02:00
services.AddTransient(typeof(ISecureDataFormat<>), typeof(SecureDataFormat<>));
services.AddTransient<Microsoft.AspNet.Authentication.ISecureDataFormat<AuthenticationTicket>, Microsoft.AspNet.Authentication.SecureDataFormat<AuthenticationTicket>>();
services.AddTransient<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<IGoogleCloudMessageSender, AuthMessageSender>();
// TODO for SMS: services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
IOptions<SiteSettings> siteSettings,
2016-06-06 12:38:11 +02:00
IOptions<RequestLocalizationOptions> localizationOptions,
IOptions<OAuth2AppSettings> oauth2SettingsContainer,
2016-11-02 11:27:12 +01:00
RoleManager<IdentityRole> roleManager,
IAuthorizationService authorizationService,
2016-05-17 18:22:18 +02:00
ILoggerFactory loggerFactory)
{
2016-11-07 19:34:56 +01:00
SiteSetup = siteSettings.Value;
Authority = siteSettings.Value.Authority;
Audience = siteSettings.Value.Audience;
2016-12-01 17:34:29 +01:00
Startup.UserFilesDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Blog).FullName;
Startup.UserBillsDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Bills).FullName;
Startup.Temp = siteSettings.Value.TempDir;
// TODO implement an installation & upgrade procedure
// Create required directories
2016-11-10 12:11:39 +01:00
foreach (string dir in new string[] { UserFilesDirName, UserBillsDirName, SiteSetup.TempDir })
{
DirectoryInfo di = new DirectoryInfo(dir);
if (!di.Exists) di.Create();
}
2016-05-17 18:22:18 +02:00
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>();
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
2016-05-17 18:22:18 +02:00
if (env.IsDevelopment())
{
2016-07-21 12:25:57 +02:00
loggerFactory.MinimumLevel = LogLevel.Verbose;
2016-05-17 18:22:18 +02:00
app.UseDeveloperExceptionPage();
app.UseRuntimeInfoPage();
var epo = new ErrorPageOptions();
epo.SourceCodeLineCount = 20;
app.UseDeveloperExceptionPage(epo);
app.UseDatabaseErrorPage(
x =>
{
x.EnableAll();
x.ShowExceptionDetails = true;
}
);
app.UseWelcomePage("/welcome");
}
else
{
// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
2016-05-29 03:11:38 +02:00
app.UseExceptionHandler("/Home/Error");
2016-05-17 18:22:18 +02:00
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch (TargetInvocationException ex)
{
if (ex.InnerException is InvalidOperationException)
// nothing to do ?
2016-05-26 14:52:11 +02:00
{
// TODO (or not) Hit the developper
2016-05-29 03:11:38 +02:00
}
2016-05-17 18:22:18 +02:00
else throw ex;
}
}
2016-11-03 14:52:17 +01:00
Task.Run(async () =>
{
// Creates roles when they don't exist
2016-08-04 13:40:39 +02:00
foreach (string roleName in new string[] {Constants.AdminGroupName,
2016-11-03 14:52:17 +01:00
Constants.StarGroupName, Constants.PerformerGroupName,
Constants.FrontOfficeGroupName,
2016-08-04 13:40:39 +02:00
Constants.StarHunterGroupName
})
2016-11-03 14:52:17 +01:00
if (!await roleManager.RoleExistsAsync(roleName))
{
var role = new IdentityRole { Name = roleName };
var resultCreate = await roleManager.CreateAsync(role);
if (!resultCreate.Succeeded)
{
throw new Exception("The role '{roleName}' does not exist and could not be created.");
}
}
// FIXME In a perfect world, connection records should be dropped at shutdown, but:
using (var db = new ApplicationDbContext())
2016-08-04 13:40:39 +02:00
{
2016-11-03 14:52:17 +01:00
foreach (var c in db.Connections)
db.Connections.Remove(c);
db.SaveChanges();
2016-08-04 13:40:39 +02:00
}
});
2016-11-03 14:52:17 +01:00
2016-06-06 14:00:05 +02:00
app.UseIISPlatformHandler(options =>
{
options.AuthenticationDescriptions.Clear();
options.AutomaticAuthentication = false;
2016-06-06 14:00:05 +02:00
});
2016-11-03 14:52:17 +01:00
2016-06-13 13:33:32 +02:00
2016-11-03 14:52:17 +01:00
ConfigureOAuthApp(app, SiteSetup);
ConfigureFileServerApp(app, SiteSetup, env, authorizationService);
ConfigureWebSocketsApp(app, SiteSetup, env);
ConfigureWorkflow(app, SiteSetup);
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"en"));
2016-05-17 18:22:18 +02:00
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
2016-11-03 14:52:17 +01:00
2016-05-17 18:22:18 +02:00
// Entry point for the application.
public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args);
}
}
//