Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using Autofac;
- using Autofac.Extensions.DependencyInjection;
- using AutoMapper;
- using Core;
- using Core.BackgroundJobs;
- using Core.Domain.Entities;
- using Core.Interfaces;
- using Infrastructure;
- using Infrastructure.Auth;
- using Infrastructure.Data;
- using Infrastructure.Helpers;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Diagnostics;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Http.Features;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.IdentityModel.Tokens;
- using Swashbuckle.AspNetCore.Swagger;
- using Web.Extensions;
- using Web.Hubs;
- using Web.Models.Settings;
- using Web.Service;
- using Web.Utils;
- namespace Legal
- {
- public class Startup
- {
- public IConfiguration Configuration { get; }
- public IWebHostEnvironment Env { get; }
- public Startup(IConfiguration configuration, IWebHostEnvironment env) => (Configuration, Env) = (configuration, env);
- public IServiceProvider ConfigureServices(IServiceCollection services)
- {
- ConfigureContext(services);
- var appSettings = ConfigureAppSettings(services);
- ConfigureAuth(services, appSettings);
- ConfigureWeb(services);
- ConfigureBackgroundJobs(services);
- ConfigureSwagger(services);
- return ConfigureContainer(services, appSettings);
- }
- public void Configure(
- IApplicationBuilder app,
- IWebHostEnvironment env,
- UserManager<User> userManager,
- RoleManager<Role> roleManager)
- {
- app.UseExceptionHandler(
- builder =>
- {
- builder.Run(
- async context =>
- {
- context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
- context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
- var error = context.Features.Get<IExceptionHandlerFeature>();
- if (error != null)
- {
- context.Response.AddApplicationError(error.Error.Message);
- await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
- }
- });
- });
- if (env.IsDevelopment())
- {
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("v1/swagger.json", "LegalAPI v1");
- });
- }
- else
- {
- app.UseHsts();
- }
- if (env.IsProduction())
- {
- app.UseHttpsRedirection();
- }
- app.UseAuthorization();
- app.UseAuthentication();
- app.UseResponseCompression();
- var webSocketOptions = new WebSocketOptions()
- {
- KeepAliveInterval = TimeSpan.FromSeconds(120),
- ReceiveBufferSize = 4 * 1024
- };
- app.UseWebSockets(webSocketOptions);
- app.UseFileServer();
- app.UseSpaStaticFiles();
- app.UseRouting();
- // IdentityDataInitializer.SeedData(userManager, roleManager);
- app.UseEndpoints(routes =>
- {
- routes.MapControllerRoute(
- name: "default",
- pattern: "{controller}/{action=Index}/{id?}");
- routes.MapHub<NotificationHub>("/hub/notification");
- });
- app.UseSpa(spa =>
- {
- spa.Options.SourcePath = "wwwroot";
- if (env.IsDevelopment())
- {
- spa.UseReactDevelopmentServer(npmScript: "start");
- }
- });
- }
- private void ConfigureContext(IServiceCollection services)
- {
- services.AddDbContextPool<AppDbContext>(options =>
- options.UseSqlServer(Configuration["TestConnection"],
- b =>
- {
- b.MigrationsAssembly("Infrastructure");
- b.EnableRetryOnFailure();
- }));
- services.AddIdentity<User, Role>(o =>
- {
- o.Stores.MaxLengthForKeys = 128;
- o.Password.RequireDigit = false;
- o.Password.RequireLowercase = false;
- o.Password.RequireUppercase = false;
- o.Password.RequireNonAlphanumeric = false;
- o.Password.RequiredLength = 6;
- }).AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
- }
- private AppSettings ConfigureAppSettings(IServiceCollection services)
- {
- var appSettings = new AppSettings
- {
- SecretKey = Configuration["JwtKey"],
- SendGridApiKey = Configuration["SendGridApiKey"],
- EmailSenderAddress = Configuration["EmailSenderAddress"],
- EmailSenderName = Configuration["EmailSenderName"],
- Country = Configuration["Legal:Country"],
- BaseUrl = Configuration["BaseUrl"],
- SupportEmail = Configuration["SupportEmail"]
- };
- services.AddSingleton(appSettings);
- return appSettings;
- }
- private void ConfigureAuth(IServiceCollection services, AppSettings appSettings)
- {
- var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appSettings.SecretKey));
- var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
- services.Configure<JwtIssuerOptions>(options =>
- {
- options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
- options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
- options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
- });
- var tokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = true,
- ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
- ValidateAudience = true,
- ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = signingKey,
- RequireExpirationTime = false,
- ValidateLifetime = true,
- ClockSkew = TimeSpan.Zero
- };
- services.AddAuthentication(options =>
- {
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- }).AddJwtBearer(configureOptions =>
- {
- configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
- configureOptions.TokenValidationParameters = tokenValidationParameters;
- configureOptions.SaveToken = true;
- configureOptions.Events = new JwtBearerEvents
- {
- OnMessageReceived = context =>
- {
- var accessToken = context.Request.Query["access_token"];
- var path = context.HttpContext.Request.Path;
- if (!string.IsNullOrEmpty(accessToken) &&
- (path.StartsWithSegments("/hub")))
- {
- context.Token = accessToken;
- }
- return Task.CompletedTask;
- },
- OnAuthenticationFailed = context =>
- {
- if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
- {
- context.Response.Headers.Add("Token-Expired", "true");
- }
- return Task.CompletedTask;
- }
- };
- });
- services.AddAuthorization(options =>
- {
- options.AddPolicy("EmailConfirmed", policy => policy.RequireClaim(Constants.Strings.JwtClaims.EmailConfirmed, "true"));
- });
- }
- private void ConfigureWeb(IServiceCollection services)
- {
- if (Env.IsProduction())
- {
- services.AddHsts(options =>
- {
- options.Preload = true;
- options.IncludeSubDomains = true;
- options.MaxAge = TimeSpan.FromDays(60);
- });
- services.AddHttpsRedirection(options =>
- {
- options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
- });
- }
- services.AddMemoryCache();
- services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
- services.AddSignalR();
- services.AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Latest);
- .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
- services.Configure<FormOptions>(x =>
- {
- x.ValueLengthLimit = int.MaxValue;
- x.MultipartBodyLengthLimit = int.MaxValue;
- });
- services.AddSpaStaticFiles(configuration =>
- {
- configuration.RootPath = "wwwroot/build";
- });
- services.AddResponseCompression();
- }
- private void ConfigureSwagger(IServiceCollection services)
- {
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info { Title = "LegalAPI", Version = "v1" });
- });
- }
- private AutofacServiceProvider ConfigureContainer(IServiceCollection services, AppSettings appSettings)
- {
- services.AddScoped<IRazorViewToStringRenderer, RazorViewToStringRenderer>();
- var builder = new ContainerBuilder();
- builder.RegisterInstance(appSettings).As<IAppSettings>().SingleInstance();
- builder.RegisterModule(new CoreModule());
- builder.RegisterModule(new InfrastructureModule());
- builder.RegisterType<ConnectionManager>().As<ConnectionManager>().InstancePerLifetimeScope();
- builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Presenter")).SingleInstance();
- builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).InstancePerLifetimeScope();
- builder.Populate(services);
- var container = builder.Build();
- return new AutofacServiceProvider(container);
- }
- private void ConfigureBackgroundJobs(IServiceCollection services)
- {
- services.AddHostedService<QueuedHostedService>();
- services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement