yavsc/Yavsc/Startup/Startup.cs

393 lines
18 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;
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;
namespace Yavsc
{
2017-09-23 02:20:38 +02:00
using System.Collections.Generic;
2017-05-24 23:36:49 +02:00
using System.Net;
using Formatters;
2017-07-05 11:29:15 +02:00
using Google.Apis.Util.Store;
2017-05-30 23:42:04 +02:00
using Microsoft.Extensions.Localization;
using Models;
2017-05-24 23:36:49 +02:00
using PayPal.Manager;
using Services;
using ViewModels.Auth.Handlers;
2018-03-26 19:27:29 +02:00
using Yavsc.Abstract.FileSystem;
2018-03-26 21:31:20 +02:00
using Yavsc.Server.Helpers;
2017-06-27 03:48:54 +02:00
using static System.Environment;
2017-06-14 12:28:08 +02:00
public partial class Startup
2016-05-17 18:22:18 +02:00
{
2016-12-01 17:34:29 +01:00
public static string AvatarsDirName { private set; get; }
2018-06-10 20:40:11 +02:00
public static string GitDirName { private set; get; }
2016-11-03 14:52:17 +01:00
public static string Authority { 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
2017-12-19 11:44:34 +01:00
public static string HostingFullName { get; set; }
2017-05-16 20:58:52 +02:00
public static PayPalSettings PayPalSettings { get; private set; }
private static ILogger logger;
2018-03-26 23:18:48 +02:00
2016-05-17 18:22:18 +02:00
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
2017-12-19 11:44:34 +01:00
var devtag = env.IsDevelopment()?"D":"";
var prodtag = env.IsProduction()?"P":"";
var stagetag = env.IsStaging()?"S":"";
HostingFullName = $"{appEnv.RuntimeFramework.FullName} [{env.EnvironmentName}:{prodtag}{devtag}{stagetag}]";
2016-05-17 18:22:18 +02:00
// 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();
2018-03-26 21:31:20 +02:00
var auth = Configuration["Site:Authority"];
var cxstr = Configuration["Data:DefaultConnection:ConnectionString"];
DbHelpers.ConnectionString = cxstr;
2016-05-17 18:22:18 +02:00
}
2017-06-01 21:28:17 +02:00
public static GoogleAuthSettings GoogleSettings { get; set; }
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)
{
2018-03-26 21:31:20 +02:00
// Database connection
2016-05-17 18:22:18 +02:00
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 oauthFacebookSettings = Configuration.GetSection("Authentication").GetSection("Facebook");
services.Configure<FacebookOAuth2AppSettings>(oauthFacebookSettings);
2017-05-05 23:37:07 +02:00
var paypalSettings = Configuration.GetSection("Authentication").GetSection("PayPal");
services.Configure<PayPalSettings>(paypalSettings);
2016-05-17 18:22:18 +02:00
2018-04-12 13:23:47 +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>)));
services.Add(ServiceDescriptor.Singleton(typeof(IOptions<RequestLocalizationOptions>), typeof(OptionsManager<RequestLocalizationOptions>)));
2016-05-17 18:22:18 +02:00
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
2017-03-13 16:44:07 +01:00
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
2017-03-29 01:55:25 +02:00
2016-05-17 18:22:18 +02:00
//options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
//{
// // My custom request culture logic
2017-03-29 01:55:25 +02:00
// return new ProviderCultureResult("fr");
2016-05-17 18:22:18 +02:00
//}));
2017-03-29 01:55:25 +02:00
2017-09-23 02:20:38 +02:00
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider { Options = options },
new CookieRequestCultureProvider { Options = options, CookieName="ASPNET_CULTURE" },
new AcceptLanguageHeaderRequestCultureProvider { Options = options }
};
2016-05-17 18:22:18 +02:00
});
2016-11-03 14:52:17 +01:00
// DataProtection
ConfigureProtectionServices(services);
2018-03-26 21:31:20 +02:00
2016-05-17 18:22:18 +02:00
// Add framework services.
services.AddEntityFramework()
2018-06-10 20:40:11 +02:00
.AddNpgsql()
.AddDbContext<ApplicationDbContext>(
db => db.UseNpgsql(DbHelpers.ConnectionString)
);
2016-11-03 14:52:17 +01:00
ConfigureOAuthServices(services);
2016-05-17 18:22:18 +02:00
services.AddCors(
2017-05-05 23:37:07 +02:00
2016-05-17 18:22:18 +02:00
options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
2017-05-05 23:37:07 +02:00
builder.WithOrigins("*");
2016-05-17 18:22:18 +02:00
});
}
2017-05-05 23:37:07 +02:00
2016-05-17 18:22:18 +02:00
);
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()));
2018-03-09 04:25:52 +01: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>();
2017-06-08 00:26:29 +02:00
services.AddSingleton<IAuthorizationHandler, BillEditHandler>();
services.AddSingleton<IAuthorizationHandler, BillViewHandler>();
2016-05-30 18:30:35 +02:00
services.AddSingleton<IAuthorizationHandler, PostUserFileHandler>();
services.AddSingleton<IAuthorizationHandler, ViewFileHandler>();
2017-03-29 01:55:25 +02:00
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"));
2017-07-09 04:05:06 +02:00
// config.ModelBinders.Insert(0,new MyDateTimeModelBinder());
// config.ModelBinders.Insert(0,new MyDecimalModelBinder());
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
2017-03-29 01:55:25 +02:00
// services.AddScoped<LanguageActionFilter>();
2016-05-17 18:22:18 +02:00
// 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.
2018-03-09 04:25:52 +01:00
services.AddTransient<IEmailSender, MessageSender>();
services.AddTransient<IGoogleCloudMessageSender, MessageSender>();
2017-06-14 12:28:08 +02:00
services.AddTransient<IBillingService, BillingService>();
2017-07-05 11:29:15 +02:00
services.AddTransient<IDataStore, FileDataStore>( (sp) => new FileDataStore("googledatastore",false) );
2017-06-14 12:28:08 +02:00
services.AddTransient<ICalendarManager, CalendarManager>();
2016-05-17 18:22:18 +02:00
// TODO for SMS: services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
2017-06-27 03:48:54 +02:00
CheckServices(services);
2016-05-17 18:22:18 +02:00
}
2017-06-01 21:28:17 +02:00
2016-05-17 18:22:18 +02:00
// 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,
IAuthorizationService authorizationService,
2017-05-16 20:58:52 +02:00
IOptions<PayPalSettings> payPalSettings,
2017-06-01 21:28:17 +02:00
IOptions<GoogleAuthSettings> googleSettings,
2017-05-30 23:42:04 +02:00
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
2016-05-17 18:22:18 +02:00
ILoggerFactory loggerFactory)
{
2018-04-12 13:23:47 +02:00
2017-06-01 21:28:17 +02:00
GoogleSettings = googleSettings.Value;
2018-03-26 23:18:48 +02:00
ResourcesHelpers.GlobalLocalizer = localizer;
2016-11-07 19:34:56 +01:00
SiteSetup = siteSettings.Value;
Authority = siteSettings.Value.Authority;
2018-06-10 20:40:11 +02:00
var blogsDir = siteSettings.Value.Blog;
2018-03-26 21:31:20 +02:00
if (blogsDir==null) throw new Exception ("blogsDir==null");
2018-06-10 20:40:11 +02:00
var billsDir = siteSettings.Value.Bills;
2018-03-26 21:31:20 +02:00
if (billsDir==null) throw new Exception ("billsDir==null");
AbstractFileSystemHelpers.UserFilesDirName = new DirectoryInfo(blogsDir).FullName;
AbstractFileSystemHelpers.UserBillsDirName = new DirectoryInfo(billsDir).FullName;
Temp = siteSettings.Value.TempDir;
2017-05-16 20:58:52 +02:00
PayPalSettings = payPalSettings.Value;
2017-07-03 20:30:00 +02:00
// TODO implement an installation & upgrade procedure
// Create required directories
2018-03-26 21:31:20 +02:00
foreach (string dir in new string[] { AbstractFileSystemHelpers.UserFilesDirName, AbstractFileSystemHelpers.UserBillsDirName, SiteSetup.TempDir })
{
2018-03-26 21:31:20 +02:00
if (dir==null) throw new Exception (nameof(dir));
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())
{
var logenvvar = Environment.GetEnvironmentVariable("ASPNET_LOG_LEVEL");
if (logenvvar!=null)
switch (logenvvar) {
case "info":
loggerFactory.MinimumLevel = LogLevel.Information;
break;
case "warn":
loggerFactory.MinimumLevel = LogLevel.Warning;
break;
case "err":
loggerFactory.MinimumLevel = LogLevel.Error;
break;
default:
loggerFactory.MinimumLevel = LogLevel.Information;
break;
}
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;
}
}
2017-05-24 23:36:49 +02:00
// before fixing the security protocol, let beleive our lib it's done with it.
var cxmgr = ConnectionManager.Instance;
// then, fix it.
2017-06-08 00:26:29 +02:00
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 0xC00; // Tls12, required by PayPal
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
2017-07-05 11:29:15 +02:00
ConfigureOAuthApp(app, SiteSetup, logger);
ConfigureFileServerApp(app, SiteSetup, env, authorizationService);
ConfigureWebSocketsApp(app, SiteSetup, env);
2017-03-05 13:48:11 +01:00
ConfigureWorkflow(app, SiteSetup, logger);
2017-07-09 04:05:06 +02:00
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"en-US"));
2017-02-21 03:18:21 +01:00
app.UseSession();
2017-03-29 01:55:25 +02:00
2016-05-17 18:22:18 +02:00
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
2017-06-27 03:48:54 +02:00
logger.LogInformation("LocalApplicationData: "+Environment.GetFolderPath(SpecialFolder.LocalApplicationData, SpecialFolderOption.DoNotVerify));
CheckApp(app, SiteSetup, env, loggerFactory);
2016-05-17 18:22:18 +02:00
}
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);
}
}
2017-03-29 01:55:25 +02:00
//