Startup.cs 6.7 KB

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