Startup.cs 9.0 KB

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