Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Globalization;
- using System.Text;
- using System.Threading.Tasks;
- using AutoMapper;
- using Microsoft.AspNetCore.Authentication.Cookies;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Cors.Infrastructure;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Localization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.Razor;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using Microsoft.IdentityModel.Tokens;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Serialization;
- using SednaCloud.Data;
- using SednaCloud.Data.Models;
- using SednaCloud.API.Services;
- using SednaCloud.Data.Repository;
- using SednaCloud.Services;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Swashbuckle.AspNetCore.Swagger;
- using DevExpress.AspNetCore;
- using DevExpress.AspNetCore.Reporting;
- using SednaCloud.Data.Helper;
- using Microsoft.ApplicationInsights.Extensibility;
- using Microsoft.ApplicationInsights.DependencyCollector;
- using System.Linq;
- using System;
- using System.IO;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Migrations;
- using ElectronNET.API;
- using ElectronNET.API.Entities;
- using Microsoft.AspNetCore.Rewrite;
- using System.Net;
- using Microsoft.AspNetCore.Http;
- namespace SednaCloud.API
- {
- public class Startup
- {
- public IConfigurationRoot _config { get; }
- private IHostingEnvironment _env;
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
- // .AddJsonFile("certificate.json", optional: true, reloadOnChange: true)
- // .AddJsonFile($"certificate.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
- if (env.IsEnvironment("Development"))
- {
- // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
- builder.AddApplicationInsightsSettings(developerMode: true);
- }
- builder.AddEnvironmentVariables();
- _env = env;
- _config = builder.Build();
- //var certificateSettings = _config.GetSection("certificateSettings");
- //string certificateFileName = certificateSettings.GetValue<string>("filename");
- //string certificatePassword = certificateSettings.GetValue<string>("password");
- //var certificate = new X509Certificate2(certificateFileName, certificatePassword);
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton(_config);
- services.AddTransient<AdminContextInitializer>();
- services.AddTransient<AccountIdentityInitializer>();
- services.AddSingleton(_config);
- services.AddDbContext<AdminContext>(ServiceLifetime.Scoped);
- services.AddDbContext<PortaleContext>(ServiceLifetime.Scoped);
- services.AddScoped<IListiniRepository, ListiniRepository>();
- services.AddScoped<IImpostazioniFornitoriRepository, ImpostazioniFornitoriRepository>();
- services.AddScoped<ICausaliContabiliRepository, CausaliContabiliRepository>();
- services.AddScoped<IScadenziarioRepository, ScadenziarioRepository>();
- services.AddScoped<IModalitaPagamentoRepository, ModalitaPagamentoRepository>();
- services.AddScoped<ITenantRepository, TenantRepository>();
- services.AddScoped<ILicenzeRepository, LicenzeRepository>();
- services.AddScoped<IUtenteLicenzaRepository, UtenteLicenzaRepository>();
- services.AddScoped(typeof(IRepositoryBase<>), typeof(RepositoryBase<>));
- //services.AddScoped<IClientiRepository, ClientiRepository>();
- services.AddScoped<IRicezioneMerceRepository, RicezioneMerceRepository>();
- services.AddScoped<IMerceProduttoriRepository, MerceProduttoriRepository>();
- services.AddScoped<IFornitoriRepository, FornitoriRepository>();
- services.AddScoped<IRegistroIvaSezionaliRepository, RegistroIvaSezionaliRepository>();
- services.AddScoped<ITestataDocumentoRepository, TestataDocumentoRepository>();
- services.AddScoped<ITestataContabilitaRepository, TestataContabilitaRepository>();
- services.AddScoped<IVenditaBancoRepository, VenditaBancoRepository>();
- services.AddScoped<IFatturaElettronicaService, FatturaElettronicaService>();
- //services.AddScoped<IArticoliGruppoRepository, ArticoliGruppoRepository>();
- // services.AddScoped<IUserManagerRepository, UserManagerRepository>();
- services.AddTransient<AdminContextInitializer>();
- services.AddTransient<AccountIdentityInitializer>();
- services.AddTransient<IEmailSender, AuthMessageSender>();
- // Add framework services.
- services.AddApplicationInsightsTelemetry(_config);
- // Multi-Tenant
- services.AddMultitenancy<AppTenant, CachingAppTenantResolver>();
- services.AddAutoMapper();
- services.AddIdentity<ApplicationUser, IdentityRole>(config =>
- {
- config.User.RequireUniqueEmail = true;
- config.Password.RequiredLength = 8;
- config.Password.RequireNonAlphanumeric = false;
- config.Password.RequireUppercase = false;
- // config.Cookies.ApplicationCookie.LoginPath = "/App/Login";
- config.SignIn.RequireConfirmedEmail = false;
- config.SignIn.RequireConfirmedPhoneNumber = false;
- })
- .AddEntityFrameworkStores<AdminContext>()
- .AddEntityFrameworkStores<PortaleContext>()
- .AddUserManager<ApplicationUserManager>()
- .AddDefaultTokenProviders();
- //services.AddIdentity<ApplicationUser, IdentityRole>(config =>
- // {
- // config.User.RequireUniqueEmail = true;
- // config.Password.RequiredLength = 8;
- // config.Password.RequireNonAlphanumeric = false;
- // config.Password.RequireUppercase = false;
- // // config.Cookies.ApplicationCookie.LoginPath = "/App/Login";
- // config.SignIn.RequireConfirmedEmail = false;
- // config.SignIn.RequireConfirmedPhoneNumber = false;
- // })
- //.AddEntityFrameworkStores<PortaleContext>()
- //.AddUserManager<ApplicationUserManager>()
- //.AddDefaultTokenProviders();
- //services.Configure<IdentityOptions>(config =>
- //{
- // config.Cookies.ApplicationCookie.Events =
- // new CookieAuthenticationEvents()
- // {
- // OnRedirectToLogin = (ctx) =>
- // {
- // if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
- // {
- // ctx.Response.StatusCode = 401;
- // }
- // return Task.CompletedTask;
- // },
- // OnRedirectToAccessDenied = (ctx) =>
- // {
- // if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
- // {
- // ctx.Response.StatusCode = 403;
- // }
- // return Task.CompletedTask;
- // }
- // };
- //});
- services.AddApiVersioning(cfg =>
- {
- cfg.DefaultApiVersion = new ApiVersion(1, 0);
- cfg.AssumeDefaultVersionWhenUnspecified = true;
- cfg.ReportApiVersions = true;
- //var rdr = new QueryStringOrHeaderApiVersionReader("ver");
- //rdr.HeaderNames.Add("X-SednaCloud-Version");
- //cfg.ApiVersionReader = rdr;
- //cfg.Conventions.Controller<TalksController>()
- // .HasApiVersion(new ApiVersion(1, 0))
- // .HasApiVersion(new ApiVersion(1, 1))
- // .HasApiVersion(new ApiVersion(2, 0))
- // .Action(m => m.Post(default(string), default(int), default(TalkModel)))
- // .MapToApiVersion(new ApiVersion(1, 1));
- });
- services.Add(ServiceDescriptor.Transient<ICorsService, WildCardCorsService>());
- services.AddCors(cfg =>
- {
- // Func<string, bool> func = x => x.Contains(".mysedna.com");
- cfg.AddPolicy("SednaCloud", bldr =>
- {
- // bldr.SetIsOriginAllowedToAllowWildcardSubdomains()
- bldr.AllowAnyHeader()
- .AllowAnyMethod()
- // .AllowAnyOrigin();
- //.SetIsOriginAllowed(func)
- //.SetIsOriginAllowedToAllowWildcardSubdomains()
- .WithOrigins(
- "http://*.mysedna.com",
- "http://www.apimysedna.com",
- "http://apimysedna.com",
- "http://www.mysedna.com",
- "http://mysedna.com",
- "http://localhost:4200",
- "http://5.249.137.216:8091");
- });
- cfg.AddPolicy("AnyGET", bldr =>
- {
- bldr.AllowAnyHeader()
- .WithMethods("GET")
- .AllowAnyOrigin();
- });
- cfg.AddPolicy("AnyOrigin", builder =>
- {
- builder
- .AllowAnyOrigin()
- .AllowAnyMethod();
- });
- });
- services.AddAuthorization(cfg =>
- {
- cfg.AddPolicy("SuperUsers", p => p.RequireClaim("SuperUser", "True"));
- cfg.AddPolicy("Admin", p => p.RequireClaim("Admin", "True"));
- cfg.AddPolicy("CanAccessTenant", p => p.AddRequirements(new IsTenantRequirement()));
- cfg.AddPolicy("AccessOnlyAdminDb", p => p.AddRequirements(new OnlyAdminTenantRequirement()));
- cfg.AddPolicy("AccessOnlySednaUsers", p => p.AddRequirements(new OnlySednaUsersRequirement()));
- });
- services.AddScoped<IAuthorizationHandler, HasTenantAuthorizationHandler>();
- services.AddScoped<IAuthorizationHandler, OnlyTenantAdminDbHandler>();
- services.AddScoped<IAuthorizationHandler, OnlySednaUsersHandler>();
- services.AddDevExpressControls();
- /* services.AddDbContext<AdminContext>(options =>
- options.UseMySql("server = localhost; uid = root; pwd = Pippo1211; database = SednaCloud.AdminDb;")
- );
- services.AddDbContext<PortaleContext>(options =>
- options.UseMySql("server = localhost; uid = root; pwd = Pippo1211; database = SednaCloud.test10;")
- );*/
- /* services.AddScoped<IMigrationsSqlGenerator, CustomMySqlMigrationsSqlGenerator>();
- services.AddEntityFrameworkMySql().AddDbContext<PortaleContext>((sp,options) =>
- options.UseInternalServiceProvider(sp)
- );
- */
- services.AddHsts(options =>
- {
- options.MaxAge = TimeSpan.FromDays(100);
- options.IncludeSubDomains = true;
- options.Preload = true;
- });
- services.AddHttpsRedirection(options => { });
- services.AddMvc(opts =>
- {
- // opts.Filters.Add(new CorsAuthorizationFilterFactory("SednaCloud"));
- // opts.Conventions.Insert(0, new ApiPrefixConvention());
- //if (!_env.IsProduction())
- //{
- // opts.SslPort = 44388;
- //}
- // opts.Filters.Add(new RequireHttpsAttribute());
- }).AddJsonOptions(o =>
- {
- if (o.SerializerSettings.ContractResolver != null)
- {
- var castedResolver = o.SerializerSettings.ContractResolver as DefaultContractResolver;
- castedResolver.NamingStrategy = new CamelCaseNamingStrategy();
- }
- o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- })
- .AddViewLocalization(
- LanguageViewLocationExpanderFormat.Suffix,
- opts => {
- opts.ResourcesPath = "Resources";
- })
- .AddDataAnnotationsLocalization(options =>
- {
- options.DataAnnotationLocalizerProvider = (type, factory) =>
- factory.Create(typeof(SharedResource));
- }).AddDefaultReportingControllers();
- services.ConfigureReportingServices(configurator => {
- configurator.ConfigureReportDesigner(designerConfigurator => {
- designerConfigurator.RegisterDataSourceWizardConfigFileConnectionStringsProvider();
- });
- });
- // Register the Swagger generator, defining one or more Swagger documents
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info { Title = "MySedna API", Version = "v1" });
- });
- services.Configure<RequestLocalizationOptions>(
- opts =>
- {
- var supportedCultures = new[]
- {
- new CultureInfo("it-IT"),
- new CultureInfo("en-US"),
- new CultureInfo("fr-FR"),
- new CultureInfo("es-ES")
- };
- opts.DefaultRequestCulture = new RequestCulture("it-IT", "it-IT");
- // Formatting numbers, dates, etc.
- opts.SupportedCultures = supportedCultures;
- // UI strings that we have localized.
- opts.SupportedUICultures = supportedCultures;
- opts.RequestCultureProviders.Insert(0, new UrlRequestCultureProvider());
- });
- services.AddAuthentication(o =>
- {
- o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
- })
- .AddCookie(o => o.Events =
- new CookieAuthenticationEvents()
- {
- OnRedirectToLogin = (ctx) =>
- {
- if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
- {
- ctx.Response.StatusCode = 401;
- }
- return Task.CompletedTask;
- },
- OnRedirectToAccessDenied = (ctx) =>
- {
- if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
- {
- ctx.Response.StatusCode = 403;
- }
- return Task.CompletedTask;
- }
- })
- .AddJwtBearer(cfg =>
- {
- cfg.SaveToken = true;
- // AutomaticAuthenticate = true,
- // AutomaticChallenge = true,
- cfg.TokenValidationParameters = new TokenValidationParameters()
- {
- ValidIssuer = _config["Tokens:Issuer"],
- ValidAudience = _config["Tokens:Audience"],
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
- ValidateLifetime = true
- };
- });
- DisableCorrelationIdHeaders(services);
- }
- private void DisableCorrelationIdHeaders(IServiceCollection services)
- {
- var module = services.FirstOrDefault(t => t.ImplementationFactory?.GetType() == typeof(Func<IServiceProvider, DependencyTrackingTelemetryModule>));
- if (module != null)
- {
- services.Remove(module);
- services.AddSingleton<ITelemetryModule>(provider => new DependencyTrackingTelemetryModule { SetComponentCorrelationHttpHeaders = false });
- }
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
- public void Configure(IApplicationBuilder app,
- IHostingEnvironment env,
- ILoggerFactory loggerFactory,
- AdminContextInitializer seeder,
- AccountIdentityInitializer identitySeeder)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseExceptionHandler("/Error");
- app.UseHsts();
- }
- var reportStorageFileDirectoryPath = Path.Combine(env.ContentRootPath, @"Reports\ReportBase");
- DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension.RegisterExtensionGlobal(new ReportStorageWebExtension1(env,reportStorageFileDirectoryPath));
- DevExpress.XtraReports.Configuration.Settings.Default.UserDesignerOptions.DataBindingMode = DevExpress.XtraReports.UI.DataBindingMode.Expressions;
- loggerFactory.AddConsole(_config.GetSection("Logging"));
- loggerFactory.AddDebug();
- // app.UseDeveloperExceptionPage();
- app.UseMultitenancy<AppTenant>();
- app.UseAuthentication();
- app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
- app.UseCors("SednaCloud");
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "MySedna API V1");
- });
- app.Use(async (context, next) =>
- {
- await next();
- if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
- {
- context.Request.Path = "/index.html";
- await next();
- }
- });
- app.UseHttpsRedirection();
- //app.UseHttpsRedirection();
- /* var options = new RewriteOptions()
- .AddRedirectToHttpsPermanent();
- app.UseRewriter(options);*/
- /* app.UseRewriter(new RewriteOptions()
- .AddRedirectToHttps()
- .AddRedirect(@"^section1/(.*)", "new/$1", (int)HttpStatusCode.Redirect)
- .AddRedirect(@"^section2/(\\d+)/(.*)", "new/$1/$2", (int)HttpStatusCode.MovedPermanently)
- .AddRewrite("^feed$", "/?format=rss", skipRemainingRules: false));*/
- app.UseDefaultFiles();
- app.UseStaticFiles();
- app.UseDevExpressControls();
- // app.UseMvc();
- app.UseMvc(routes =>
- {
- /* routes.MapRoute(
- name: "default",
- template: "api/{controller=ReportApi}/{action=Index}/{id?}");*/
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- seeder.Seed().Wait();
- identitySeeder.Seed().Wait();
- if (HybridSupport.IsElectronActive)
- {
- ElectronBootstrap();
- }
- }
- public async void ElectronBootstrap()
- {
- var browserWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
- {
- Width = 1152,
- Height = 864,
- Show = false,
- WebPreferences = new WebPreferences
- {
- WebSecurity = false
- },
- });
- browserWindow.OnReadyToShow += () => browserWindow.Show();
- browserWindow.SetTitle("Electron.NET API Demos");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment