Startup.cs 7.1 KB

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