Startup.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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(CookieAuthenticationDefaults.AuthenticationScheme)
  86. .AddCookie(options =>
  87. {
  88. options.Cookie.HttpOnly = true;
  89. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  90. options.Cookie.SameSite = SameSiteMode.Strict;
  91. options.LoginPath = "/Account/Login";
  92. options.LogoutPath = "/Account/Logoff";
  93. options.ExpireTimeSpan = new TimeSpan(0, 24, 0, 0);
  94. });
  95. // Add the default custom authentication service
  96. services.AddScoped<Services.Authentication.IAuthenticationService, DbContextAuthenticationService>();
  97. // Add the default authorization handler
  98. services.AddScoped<IAuthorizationHandler, DefaultAuthorizationHandler>();
  99. services.AddAuthorization(options =>
  100. {
  101. foreach (var policy in _availablePolicies)
  102. {
  103. options.AddPolicy(policy, a =>
  104. {
  105. a.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
  106. a.RequireAuthenticatedUser();
  107. a.AddRequirements(new DefaultAuthorizationPolicy(policy));
  108. });
  109. }
  110. });
  111. // Add the DbContext custom authorization service
  112. services.AddScoped<Services.Authorization.IAuthorizationService, CookieAuthorizationService>();
  113. }
  114. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  115. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  116. {
  117. if (env.IsDevelopment())
  118. {
  119. app.UseDeveloperExceptionPage();
  120. }
  121. else
  122. {
  123. app.UseExceptionHandler("/Home/Error");
  124. }
  125. app.UseStaticFiles();
  126. app.UseRouting();
  127. app.UseAuthorization();
  128. app.UseAuthentication();
  129. app.UseCookiePolicy();
  130. app.UseEndpoints(endpoints =>
  131. {
  132. endpoints.MapControllerRoute(
  133. name: "default",
  134. pattern: "{controller=Home}/{action=Index}/{id?}");
  135. });
  136. using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
  137. {
  138. using (var context = scope.ServiceProvider.GetService<ERPDbContext>())
  139. {
  140. context.Database.Migrate();
  141. }
  142. }
  143. }
  144. }
  145. }