Startup.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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.Strohrmann.ERP.Core.Helper;
  9. using GreenTree.Strohrmann.ERP.Domain.Model;
  10. using GreenTree.Strohrmann.ERP.Services.Authentication;
  11. using GreenTree.Strohrmann.ERP.Services.Authorization;
  12. using GreenTree.Strohrmann.ERP.Services.Geolocator;
  13. using GreenTree.Strohrmann.ERP.Services.Localization;
  14. using GreenTree.Strohrmann.ERP.Services.Notification;
  15. using GreenTree.Strohrmann.ERP.Web.Configuration;
  16. using GreenTree.Strohrmann.ERP.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.Strohrmann.ERP.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. "Craft-View",
  46. "Craft-Change",
  47. "Craft-Delete",
  48. "Customer-View",
  49. "Customer-Change",
  50. "Customer-Delete",
  51. "Employee-View",
  52. "Employee-Change",
  53. "Employee-Delete",
  54. "Material-View",
  55. "Material-Change",
  56. "Material-Delete",
  57. "Supplier-View",
  58. "Supplier-Change",
  59. "Supplier-Delete"
  60. };
  61. #endregion
  62. public Startup(IConfiguration configuration)
  63. {
  64. Configuration = configuration;
  65. }
  66. public IConfiguration Configuration { get; }
  67. // This method gets called by the runtime. Use this method to add services to the container.
  68. public void ConfigureServices(IServiceCollection services)
  69. {
  70. // Add MVC controller and views
  71. services.AddControllersWithViews(options =>
  72. {
  73. //options.ModelBinderProviders.Insert(0, new CustomerModelBinderProvider());
  74. });
  75. // Add option handling
  76. services.AddOptions();
  77. services.AddSingleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>));
  78. // Add the HttpContextAccessor as Singleton
  79. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  80. // Add global administration notification options
  81. var administrationOptions = Configuration.GetSection("AdministrationOptions").Get<AdministrationOptions>();
  82. if (administrationOptions == null)
  83. throw new Exception("The appsettings.json does not contain administration options.");
  84. services.AddSingleton(administrationOptions);
  85. // Add MailConfigurationOptions monitor
  86. if (!Configuration.SectionExists("MailNotificationOptions"))
  87. throw new Exception("The appsettings.json does not contain mail notification options.");
  88. services.Configure<MailNotificationOptions>(Configuration.GetSection("MailNotificationOptions"));
  89. // Add the mail notification service
  90. services.AddSingleton<INotificationService, MailNotificationService>();
  91. // Add global Google API options
  92. var geocodingOptions = Configuration.GetSection("GoogleApiOptions").Get<GoogleApiOptions>();
  93. if (geocodingOptions == null)
  94. throw new Exception("The appsettings.json does not contain Google API options.");
  95. services.AddSingleton(geocodingOptions);
  96. // Add the Google Geocoding service
  97. services.AddSingleton<IGeocodingService, GoogleGeocodingService>();
  98. // Add global culture options
  99. services.Configure<CultureOptions>(Configuration.GetSection("CultureOptions"));
  100. // Add localization
  101. services.Configure<RequestLocalizationOptions>(options =>
  102. {
  103. // Add global culture options
  104. var cultureOptions = Configuration.GetSection("CultureOptions").Get<CultureOptions>();
  105. var culture = cultureOptions == null || (cultureOptions.DefaultCulture != null && String.IsNullOrEmpty(cultureOptions.DefaultCulture))
  106. ? CultureInfo.CurrentCulture.Name
  107. : cultureOptions.DefaultCulture;
  108. options.DefaultRequestCulture = new RequestCulture(culture);
  109. options.RequestCultureProviders = new List<IRequestCultureProvider>
  110. {
  111. new QueryStringRequestCultureProvider(),
  112. new CookieRequestCultureProvider()
  113. };
  114. });
  115. // Add sessioning
  116. services.AddSession(options =>
  117. {
  118. var sessionOptions = Configuration.GetSection("SessionOptions").Get<SessionOptions>();
  119. options.IdleTimeout = sessionOptions.IdleTimeout;
  120. options.Cookie.Name = sessionOptions.Cookie.Name;
  121. });
  122. // Add Counter DbContext
  123. services.AddDbContextPool<ERPDbContext>(options =>
  124. {
  125. options.UseMySql(Configuration.GetConnectionString("ERPDatabase"));
  126. options.UseLazyLoadingProxies();
  127. });
  128. // Add user helper service
  129. services.AddScoped<IUserHelper, UserHelper>();
  130. // Add MVC with FluentValidation reference
  131. services.AddMvc()
  132. .AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()));
  133. // Add authentication
  134. services.AddAuthentication(options =>
  135. {
  136. options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  137. })
  138. .AddCookie(options =>
  139. {
  140. options.Cookie.HttpOnly = true;
  141. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  142. options.Cookie.SameSite = SameSiteMode.Strict;
  143. options.LoginPath = "/Account/Login";
  144. options.LogoutPath = "/Account/Logoff";
  145. options.ExpireTimeSpan = new TimeSpan(0, 24, 0, 0);
  146. });
  147. // Add the default custom authentication service
  148. services.AddScoped<Services.Authentication.IAuthenticationService, DbContextAuthenticationService>();
  149. // Add the default authorization handler
  150. services.AddScoped<IAuthorizationHandler, DefaultAuthorizationHandler>();
  151. services.AddAuthorization(options =>
  152. {
  153. options.DefaultPolicy = new AuthorizationPolicy(
  154. new[] { new DefaultAuthorizationPolicy(String.Empty) },
  155. new[] { CookieAuthenticationDefaults.AuthenticationScheme });
  156. foreach (var policy in _availablePolicies)
  157. {
  158. options.AddPolicy(policy, a =>
  159. {
  160. a.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
  161. a.RequireAuthenticatedUser();
  162. a.AddRequirements(new DefaultAuthorizationPolicy(policy));
  163. });
  164. }
  165. });
  166. // Add the DbContext custom authorization service
  167. services.AddScoped<Services.Authorization.IAuthorizationService, CookieAuthorizationService>();
  168. // Add the option monitoring service
  169. services.AddSingleton<IOptionMonitoringService, DefaultOptionMonitoringService>();
  170. }
  171. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  172. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  173. {
  174. if (env.IsDevelopment())
  175. {
  176. app.UseDeveloperExceptionPage();
  177. }
  178. else
  179. {
  180. app.UseExceptionHandler("/Home/Error");
  181. }
  182. app.UseStaticFiles();
  183. app.UseRequestLocalization();
  184. app.UseRouting();
  185. app.UseAuthorization();
  186. app.UseAuthentication();
  187. app.UseCookiePolicy();
  188. app.UseEndpoints(endpoints =>
  189. {
  190. endpoints.MapControllerRoute(
  191. name: "default",
  192. pattern: "{controller=Home}/{action=Index}/{id?}");
  193. });
  194. using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
  195. {
  196. using (var context = scope.ServiceProvider.GetService<ERPDbContext>())
  197. {
  198. context.Database.Migrate();
  199. }
  200. }
  201. }
  202. }
  203. }