yavsc/src/Yavsc/Startup/Startup.cs

427 lines
19 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;
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.OptionsModel;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Net.Http.Headers;
2018-12-24 03:07:05 +00:00
using Newtonsoft.Json;
2016-05-17 18:22:18 +02:00
namespace Yavsc
{
2017-09-23 02:20:38 +02:00
using System.Collections.Generic;
2020-10-09 19:35:39 +01:00
using System.Linq;
2017-05-24 23:36:49 +02:00
using System.Net;
2019-02-08 10:22:52 +00:00
using System.Security.Claims;
using Formatters;
2017-07-05 11:29:15 +02:00
using Google.Apis.Util.Store;
2019-02-08 10:22:52 +00:00
using Microsoft.AspNet.Http;
2018-07-25 02:12:13 +02:00
using Microsoft.AspNet.Identity;
2020-10-09 19:35:39 +01:00
using Microsoft.AspNet.SignalR;
2017-05-30 23:42:04 +02:00
using Microsoft.Extensions.Localization;
2019-02-08 10:22:52 +00:00
using Microsoft.Extensions.Logging;
using Models;
using Services;
2018-03-26 19:27:29 +02:00
using Yavsc.Abstract.FileSystem;
2019-01-26 14:23:53 +00:00
using Yavsc.AuthorizationHandlers;
2019-08-21 17:23:58 +01:00
using Yavsc.Helpers;
2020-10-09 19:35:39 +01:00
using Yavsc.Models.Messaging;
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; }
2019-05-14 21:22:44 +01:00
public static string Temp { get; set; }
2016-11-14 12:17:07 +01:00
public static SiteSettings SiteSetup { get; private set; }
2018-12-24 03:07:05 +00:00
public static GoogleServiceAccount GServiceAccount { get; private set; }
2016-11-07 19:34:56 +01:00
2019-05-14 21:22:44 +01:00
public static string HostingFullName { get; set; }
2017-12-19 11:44:34 +01:00
2017-05-16 20:58:52 +02:00
public static PayPalSettings PayPalSettings { get; private set; }
2019-06-27 10:30:28 +01:00
private static ILogger _logger;
2019-07-13 16:12:39 +02:00
/// <summary>
/// generating reset password and confirmation tokens
/// </summary>
public IUserTokenProvider<ApplicationUser> UserTokenProvider { get; set; }
2020-10-09 19:35:39 +01:00
2019-02-08 10:22:52 +00:00
2016-05-17 18:22:18 +02:00
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
2019-06-25 02:57:56 +01:00
AppDomain.CurrentDomain.UnhandledException += OnUnHandledException;
2020-10-09 19:35:39 +01:00
2019-05-14 21:22:44 +01:00
var devtag = env.IsDevelopment() ? "D" : "";
var prodtag = env.IsProduction() ? "P" : "";
var stagetag = env.IsStaging() ? "S" : "";
2017-12-19 11:44:34 +01:00
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();
2019-05-14 21:22:44 +01:00
2018-03-26 21:31:20 +02:00
var auth = Configuration["Site:Authority"];
2019-01-05 13:24:24 +00:00
var cxstr = Configuration["ConnectionStrings:Default"];
ConnectionString = cxstr;
2018-12-24 03:07:05 +00:00
2018-06-29 10:30:04 +02:00
AppDomain.CurrentDomain.SetData(Constants.YavscConnectionStringEnvName, ConnectionString);
2018-12-24 03:07:05 +00:00
2019-05-14 21:22:44 +01:00
var googleClientFile = Configuration["Authentication:Google:GoogleWebClientJson"];
var googleServiceAccountJsonFile = Configuration["Authentication:Google:GoogleServiceAccountJson"];
if (googleClientFile != null)
GoogleWebClientConfiguration = new ConfigurationBuilder().AddJsonFile(googleClientFile).Build();
if (googleServiceAccountJsonFile != null)
{
var safile = new FileInfo(googleServiceAccountJsonFile);
GServiceAccount = JsonConvert.DeserializeObject<GoogleServiceAccount>(safile.OpenText().ReadToEnd());
}
2016-05-17 18:22:18 +02:00
}
2020-10-09 19:35:39 +01:00
2019-06-25 02:57:56 +01:00
// never hit ...
private void OnUnHandledException(object sender, UnhandledExceptionEventArgs e)
{
2019-06-27 10:30:28 +01:00
_logger.LogError(sender.ToString());
_logger.LogError(JsonConvert.SerializeObject(e.ExceptionObject));
2019-06-25 02:57:56 +01:00
}
2018-12-24 03:07:05 +00:00
public static string ConnectionString { get; set; }
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; }
2018-12-24 03:07:05 +00:00
public static IConfigurationRoot GoogleWebClientConfiguration { get; set; }
2016-05-17 18:22:18 +02:00
// 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
2019-05-14 21:22:44 +01:00
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>)));
2020-10-09 19:35:39 +01:00
services.Add(ServiceDescriptor.Singleton(typeof(IDiskUsageTracker), typeof(DiskUsageTracker)));
2019-06-14 10:03:51 +01:00
2016-05-17 18:22:18 +02:00
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en"),
new CultureInfo("fr"),
new CultureInfo("pt")
};
2019-05-14 21:22:44 +01:00
var supportedUICultures = new[]
{
new CultureInfo("fr"),
new CultureInfo("en"),
new CultureInfo("pt")
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
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);
2019-05-14 21:22:44 +01:00
2016-05-17 18:22:18 +02:00
// Add framework services.
services.AddEntityFramework()
2019-05-14 21:22:44 +01:00
.AddNpgsql()
.AddDbContext<ApplicationDbContext>();
2019-05-14 21:22:44 +01:00
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>();
2019-01-26 14:23:53 +00:00
services.AddSingleton<IAuthorizationHandler, SendMessageHandler>();
2019-06-14 10:03:51 +01:00
services.AddSingleton<IConnexionManager, HubConnectionManager>();
2019-06-27 10:30:28 +01:00
services.AddSingleton<ILiveProcessor, LiveProcessor>();
2019-08-04 11:45:00 +02:00
services.AddSingleton<IFileSystemAuthManager, FileSystemAuthManager>();
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"));
2019-05-14 21:22:44 +01: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.
services.AddTransient<IEmailSender, MailSender>();
2019-05-08 16:33:29 +01:00
services.AddTransient<IYavscMessageSender, YavscMessageSender>();
2017-06-14 12:28:08 +02:00
services.AddTransient<IBillingService, BillingService>();
2019-05-14 21:22:44 +01:00
services.AddTransient<IDataStore, FileDataStore>((sp) => new FileDataStore("googledatastore", false));
2017-06-14 12:28:08 +02:00
services.AddTransient<ICalendarManager, CalendarManager>();
2019-05-14 21:22:44 +01:00
2016-05-17 18:22:18 +02:00
// TODO for SMS: services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
}
2018-08-03 02:59:37 +02:00
static ApplicationDbContext _dbContext;
2019-01-26 14:23:53 +00:00
public static IServiceProvider Services { get; private set; }
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.
2018-08-03 02:59:37 +02:00
public void Configure(
IApplicationBuilder app, IHostingEnvironment env,
ApplicationDbContext dbContext, IOptions<SiteSettings> siteSettings,
2016-06-06 12:38:11 +02:00
IOptions<RequestLocalizationOptions> localizationOptions,
IAuthorizationService authorizationService,
2017-05-16 20:58:52 +02:00
IOptions<PayPalSettings> payPalSettings,
2017-06-01 21:28:17 +02:00
IOptions<GoogleAuthSettings> googleSettings,
2019-06-17 20:52:51 +01:00
IStringLocalizer<Yavsc.YavscLocalisation> localizer,
2018-07-25 02:12:13 +02:00
UserManager<ApplicationUser> usermanager,
2016-05-17 18:22:18 +02:00
ILoggerFactory loggerFactory)
{
2019-01-26 14:23:53 +00:00
Services = app.ApplicationServices;
2018-08-03 02:59:37 +02:00
_dbContext = dbContext;
2018-07-25 02:12:13 +02:00
_usermanager = usermanager;
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;
2019-05-14 21:22:44 +01:00
if (blogsDir == null) throw new Exception("blogsDir is not set.");
2018-06-10 20:40:11 +02:00
var billsDir = siteSettings.Value.Bills;
2019-05-14 21:22:44 +01:00
if (billsDir == null) throw new Exception("billsDir is not set.");
2018-03-26 21:31:20 +02:00
2019-05-14 21:22:44 +01:00
AbstractFileSystemHelpers.UserFilesDirName = new DirectoryInfo(blogsDir).FullName;
AbstractFileSystemHelpers.UserBillsDirName = new DirectoryInfo(billsDir).FullName;
2018-03-26 21:31:20 +02:00
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 })
{
2019-05-14 21:22:44 +01:00
if (dir == null) throw new Exception(nameof(dir));
2018-03-26 21:31:20 +02:00
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();
2019-06-27 10:30:28 +01:00
_logger = loggerFactory.CreateLogger<Startup>();
2021-08-07 13:14:30 +01:00
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");
2016-05-17 18:22:18 +02:00
if (env.IsDevelopment())
{
var logenvvar = Environment.GetEnvironmentVariable("ASPNET_LOG_LEVEL");
2019-05-14 21:22:44 +01:00
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;
case "debug":
default:
loggerFactory.MinimumLevel = LogLevel.Debug;
break;
}
2016-05-17 18:22:18 +02:00
app.UseRuntimeInfoPage();
2020-09-12 01:11:30 +01:00
var epo = new ErrorPageOptions
{
SourceCodeLineCount = 20
};
2016-05-17 18:22:18 +02:00
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.
2019-06-14 10:03:51 +01:00
var cxmgr = PayPal.Manager.ConnectionManager.Instance;
2017-05-24 23:36:49 +02:00
// then, fix it.
2019-05-14 21:22:44 +01: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;
2019-05-14 21:22:44 +01:00
});
2019-01-30 11:14:32 +00:00
app.UseSession();
2016-11-03 14:52:17 +01:00
2020-09-12 01:11:30 +01:00
ConfigureOAuthApp(app);
ConfigureFileServerApp(app, SiteSetup, env, authorizationService);
2019-05-14 21:22:44 +01:00
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture)new RequestCulture((string)"en-US"));
2017-03-29 01:55:25 +02:00
2020-09-12 01:11:30 +01:00
ConfigureWorkflow();
ConfigureWebSocketsApp(app);
2019-05-14 21:22:44 +01:00
2016-05-17 18:22:18 +02:00
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
2019-06-27 10:30:28 +01:00
_logger.LogInformation("LocalApplicationData: " + Environment.GetFolderPath(SpecialFolder.LocalApplicationData, SpecialFolderOption.DoNotVerify));
2021-01-03 21:54:10 +00:00
2020-10-09 19:35:39 +01:00
CheckApp(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
//