Startup.cs 7.6 KB

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