Startup.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using FluentValidation.AspNetCore;
  8. using GreenTree.Maschinenbestellungen.Core.Helper;
  9. using GreenTree.Maschinenbestellungen.Domain.Model;
  10. using GreenTree.Maschinenbestellungen.Services.Authentication;
  11. using GreenTree.Maschinenbestellungen.Services.Authorization;
  12. using GreenTree.Maschinenbestellungen.Services.Geolocator;
  13. using GreenTree.Maschinenbestellungen.Services.Localization;
  14. using GreenTree.Maschinenbestellungen.Services.Notification;
  15. using GreenTree.Maschinenbestellungen.Web.Configuration;
  16. using GreenTree.Maschinenbestellungen.Web.Models;
  17. using Microsoft.AspNetCore.Authentication;
  18. using Microsoft.AspNetCore.Authentication.Cookies;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Builder;
  21. using Microsoft.AspNetCore.Hosting;
  22. using Microsoft.AspNetCore.Http;
  23. using Microsoft.AspNetCore.HttpsPolicy;
  24. using Microsoft.AspNetCore.Localization;
  25. using Microsoft.AspNetCore.Mvc.Razor;
  26. using Microsoft.EntityFrameworkCore;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.DependencyInjection;
  29. using Microsoft.Extensions.Hosting;
  30. using Microsoft.Extensions.Options;
  31. using Porta.Kundenzähler.Services.Extension;
  32. namespace GreenTree.Maschinenbestellungen.Web
  33. {
  34. public class Startup
  35. {
  36. #region Policies
  37. /// <summary>
  38. /// All available policies in the application
  39. /// </summary>
  40. public static readonly string[] _availablePolicies =
  41. {
  42. "User-View",
  43. "User-Change",
  44. "User-Delete"
  45. };
  46. #endregion
  47. public Startup(IConfiguration configuration)
  48. {
  49. Configuration = configuration;
  50. }
  51. public IConfiguration Configuration { get; }
  52. // This method gets called by the runtime. Use this method to add services to the container.
  53. public void ConfigureServices(IServiceCollection services)
  54. {
  55. // Add MVC controller and views
  56. services.AddControllersWithViews(options =>
  57. {
  58. //options.ModelBinderProviders.Insert(0, new CustomerModelBinderProvider());
  59. });
  60. // Add option handling
  61. services.AddOptions();
  62. services.AddSingleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>));
  63. // Add the HttpContextAccessor as Singleton
  64. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  65. // Add global administration notification options
  66. var administrationOptions = Configuration.GetSection("AdministrationOptions").Get<AdministrationOptions>();
  67. if (administrationOptions == null)
  68. throw new Exception("The appsettings.json does not contain administration options.");
  69. services.AddSingleton(administrationOptions);
  70. // Add MailConfigurationOptions monitor
  71. if (!Configuration.SectionExists("MailNotificationOptions"))
  72. throw new Exception("The appsettings.json does not contain mail notification options.");
  73. services.Configure<MailNotificationOptions>(Configuration.GetSection("MailNotificationOptions"));
  74. // Add the mail notification service
  75. services.AddSingleton<INotificationService, MailNotificationService>();
  76. // Add global Google API options
  77. var geocodingOptions = Configuration.GetSection("GoogleApiOptions").Get<GoogleApiOptions>();
  78. if (geocodingOptions == null)
  79. throw new Exception("The appsettings.json does not contain Google API options.");
  80. services.AddSingleton(geocodingOptions);
  81. // Add the Google Geocoding service
  82. services.AddSingleton<IGeocodingService, GoogleGeocodingService>();
  83. // Add global culture options
  84. services.Configure<CultureOptions>(Configuration.GetSection("CultureOptions"));
  85. // Add localization
  86. services.Configure<RequestLocalizationOptions>(options =>
  87. {
  88. // Add global culture options
  89. var cultureOptions = Configuration.GetSection("CultureOptions").Get<CultureOptions>();
  90. var culture = cultureOptions == null || (cultureOptions.DefaultCulture != null && String.IsNullOrEmpty(cultureOptions.DefaultCulture))
  91. ? CultureInfo.CurrentCulture.Name
  92. : cultureOptions.DefaultCulture;
  93. options.DefaultRequestCulture = new RequestCulture(culture);
  94. options.RequestCultureProviders = new List<IRequestCultureProvider>
  95. {
  96. new QueryStringRequestCultureProvider(),
  97. new CookieRequestCultureProvider()
  98. };
  99. });
  100. // Add sessioning
  101. services.AddSession(options =>
  102. {
  103. var sessionOptions = Configuration.GetSection("SessionOptions").Get<SessionOptions>();
  104. options.IdleTimeout = sessionOptions.IdleTimeout;
  105. options.Cookie.Name = sessionOptions.Cookie.Name;
  106. });
  107. // Add Counter DbContext
  108. services.AddDbContextPool<OrderDbContext>(options =>
  109. {
  110. options.UseMySql(Configuration.GetConnectionString("ERPDatabase"));
  111. options.UseLazyLoadingProxies();
  112. });
  113. // Add user helper service
  114. services.AddScoped<IUserHelper, UserHelper>();
  115. // Add MVC with FluentValidation reference
  116. services.AddMvc()
  117. .AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()));
  118. // Add authentication
  119. services.AddAuthentication(options =>
  120. {
  121. options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  122. })
  123. .AddCookie(options =>
  124. {
  125. options.Cookie.HttpOnly = true;
  126. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  127. options.Cookie.SameSite = SameSiteMode.Strict;
  128. options.LoginPath = "/Account/Login";
  129. options.LogoutPath = "/Account/Logoff";
  130. options.ExpireTimeSpan = new TimeSpan(0, 24, 0, 0);
  131. });
  132. // Add the default custom authentication service
  133. services.AddScoped<Services.Authentication.IAuthenticationService, DbContextAuthenticationService>();
  134. // Add the default authorization handler
  135. services.AddScoped<IAuthorizationHandler, DefaultAuthorizationHandler>();
  136. services.AddAuthorization(options =>
  137. {
  138. options.DefaultPolicy = new AuthorizationPolicy(
  139. new[] { new DefaultAuthorizationPolicy(String.Empty) },
  140. new[] { CookieAuthenticationDefaults.AuthenticationScheme });
  141. foreach (var policy in _availablePolicies)
  142. {
  143. options.AddPolicy(policy, a =>
  144. {
  145. a.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
  146. a.RequireAuthenticatedUser();
  147. a.AddRequirements(new DefaultAuthorizationPolicy(policy));
  148. });
  149. }
  150. });
  151. // Add the DbContext custom authorization service
  152. services.AddScoped<Services.Authorization.IAuthorizationService, CookieAuthorizationService>();
  153. // Add the option monitoring service
  154. services.AddSingleton<IOptionMonitoringService, DefaultOptionMonitoringService>();
  155. }
  156. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  157. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  158. {
  159. if (env.IsDevelopment())
  160. {
  161. app.UseDeveloperExceptionPage();
  162. }
  163. else
  164. {
  165. app.UseExceptionHandler("/Home/Error");
  166. }
  167. app.UseStaticFiles();
  168. app.UseRequestLocalization();
  169. app.UseRouting();
  170. app.UseAuthorization();
  171. app.UseAuthentication();
  172. app.UseCookiePolicy();
  173. app.UseEndpoints(endpoints =>
  174. {
  175. endpoints.MapControllerRoute(
  176. name: "default",
  177. pattern: "{controller=Home}/{action=Index}/{id?}");
  178. });
  179. using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
  180. {
  181. using (var context = scope.ServiceProvider.GetService<OrderDbContext>())
  182. {
  183. context.Database.Migrate();
  184. }
  185. }
  186. }
  187. }
  188. }