Ejemplo n.º 1
0
 public s1WebHostModule(IWebHostEnvironment env)
 {
     _env = env;
     _appConfiguration = env.GetAppConfiguration();
 }
Ejemplo n.º 2
0
 public HomeController(IConfiguration configuration, IWebHostEnvironment environment)
 {
     _configuration = configuration;
     _environment   = environment;
 }
Ejemplo n.º 3
0
 public UpsertModel(IUnitOfWork unitOfWork, IWebHostEnvironment hostingEnvironment)
 {
     _unitOfWork = unitOfWork;
     _hostingEnvironment = hostingEnvironment;
 }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            var args = new List <string>
            {
                "api_a",
                "api_b"
            };

            //// Enable middleware to serve generated Swagger as a JSON endpoint
            //app.UseSwagger();
            //app.UseSwaggerUI(options =>
            //{
            //    foreach (var item in args)
            //    {
            //        options.SwaggerEndpoint($"/doc/{item}/swagger.json", item);
            //    }
            //}); //URL: /swagger

            //通过网关设置跨域
            app.UseOcelot((ocelotBuilder, pipelineConfiguration) =>
            {
                // This is registered to catch any global exceptions that are not handled
                // It also sets the Request Id if anything is set globally
                ocelotBuilder.UseExceptionHandlerMiddleware();
                // This is registered first so it can catch any errors and issue an appropriate response
                ocelotBuilder.UseResponderMiddleware();
                ocelotBuilder.UseDownstreamRouteFinderMiddleware();
                ocelotBuilder.UseDownstreamRequestInitialiser();
                ocelotBuilder.UseRequestIdMiddleware();
                ocelotBuilder.UseMiddleware <ClientRateLimitMiddleware>();
                ocelotBuilder.UseMiddleware <ClaimsToHeadersMiddleware>();
                ocelotBuilder.UseLoadBalancingMiddleware();
                ocelotBuilder.UseDownstreamUrlCreatorMiddleware();
                ocelotBuilder.UseOutputCacheMiddleware();
                ocelotBuilder.UseMiddleware <HttpRequesterMiddleware>();
                // cors headers
                ocelotBuilder.Use(async(context, next) =>
                {
                    if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))
                    {
                        var allowed = Configuration["CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray();
                        context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowed.Length == 0 ? new[] { "*" } : allowed));
                    }
                    if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowHeaders))
                    {
                        var allowed = Configuration["Headers"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray();
                        context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, allowed.Length == 0 ? new[] { "*" } : allowed));
                    }
                    if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlRequestMethod))
                    {
                        var allowed = Configuration["Method"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray();
                        context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, allowed.Length == 0 ? new[] { "*" } : allowed));
                    }
                    await next();
                });
            });
            //app.UseOcelot().Wait();
        }
Ejemplo n.º 5
0
 public BaseController(IWebHostEnvironment environment)
 {
     _hostingEnvironment = environment;
 }
Ejemplo n.º 6
0
 public StartupTest(IWebHostEnvironment env, IConfiguration configuration) : base(env, configuration)
 {
 }
Ejemplo n.º 7
0
 public DownloadController(IWebHostEnvironment env)
 {
     _env = env;
 }
Ejemplo n.º 8
0
 public HandleExceptionFilter(ILogger<HandleExceptionFilter> logger, IWebHostEnvironment env)
 {
     _logger = logger;
     _env = env;
 }
Ejemplo n.º 9
0
 public CarModelsProvider(VehiclesDBContext dBContext, ILogger <CarModelsProvider> logger, IMapper mapper, IWebHostEnvironment environment)
 {
     this.dBContext = dBContext;
     this.logger    = logger;
     this.mapper    = mapper;
     _environment   = environment;
     SeedData();
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> Edit(TestimionalGeneralDto testimionalGeneralDto, IFormFile imgFile, [FromServices] IWebHostEnvironment webHostEnvironment)
        {
            if (ModelState.IsValid)
            {
                if (imgFile != null)
                {
                    string imgName = await ImageUploadHelper.ImageUploadAsync(webHostEnvironment, imgFile, "\\img\\testimonial");

                    testimionalGeneralDto.ImageUrl = imgName;
                }
                else
                {
                    var editedTestimional = await _testimionalService.GetByIdAsync(testimionalGeneralDto.Id);

                    testimionalGeneralDto.ImageUrl = editedTestimional.ImageUrl;
                }
                await _testimionalService.UpdateAsync(new Testimonial
                {
                    Id       = testimionalGeneralDto.Id,
                    ImageUrl = testimionalGeneralDto.ImageUrl,
                    IsDraft  = testimionalGeneralDto.IsDraft,
                    Name     = testimionalGeneralDto.Name,
                    Text     = testimionalGeneralDto.Text,
                    Title    = testimionalGeneralDto.Title
                });

                return(RedirectToAction("Index"));
            }
            return(View(testimionalGeneralDto));
        }
 public ProductController(IProductService Service, ILogger <ProductController> logger, IWebHostEnvironment hostingEnvironment)
     : base(Service, logger)
 {
     _hostingEnvironment = hostingEnvironment;
 }
Ejemplo n.º 12
0
        public async Task <IActionResult> Create(TestimionalAddDto testimionalAddDto, IFormFile imgFile, [FromServices] IWebHostEnvironment webHostEnvironment)
        {
            if (ModelState.IsValid)
            {
                if (imgFile != null)
                {
                    string imgName = await ImageUploadHelper.ImageUploadAsync(webHostEnvironment, imgFile, "\\img\\testimonial");

                    testimionalAddDto.ImageUrl = imgName;
                }

                await _testimionalService.InsertAsync(new Testimonial
                {
                    IsDraft  = testimionalAddDto.IsDraft,
                    Name     = testimionalAddDto.Name,
                    Text     = testimionalAddDto.Text,
                    Title    = testimionalAddDto.Title,
                    ImageUrl = testimionalAddDto.ImageUrl
                });

                return(RedirectToAction("Index"));
            }
            return(View(testimionalAddDto));
        }
Ejemplo n.º 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware <ExceptionMiddleware>();

            app.UseXContentTypeOptions();
            app.UseReferrerPolicy(opt => opt.NoReferrer());
            app.UseXXssProtection(opt => opt.EnabledWithBlockMode());
            // blocking iframe
            app.UseXfo(opt => opt.Deny());
            app.UseCsp(opt => opt
                       // force https
                       .BlockAllMixedContent()
                       // we're gonna ok if generated from our domain
                       .StyleSources(s => s.Self().CustomSources("https://fonts.googleapis.com",
                                                                 "sha256-yChqzBduCCi4o4xdbXRXh4U/t1rP4UUUMJt+rB+ylUI="))
                       .FontSources(s => s.Self().CustomSources("https://fonts.gstatic.com", "data:"))
                       .FormActions(s => s.Self())
                       .FrameAncestors(s => s.Self())
                       .ImageSources(s => s.Self().CustomSources("https://res.cloudinary.com", "https://www.facebook.com", "data:"))
                       .ScriptSources(s => s.Self()
                                      .CustomSources(
                                          "sha256-RZa9FeBeiqCM2+5jcE1mUKMkRZ69RNcOg/OAT6NWJ7Y=",
                                          "sha256-rTuNa9UeAQ5B9gj9rLEY9243ZbVE6Sl++AiPas66JE4=",
                                          "https://connect.facebook.net"
                                          ))
                       );

            if (env.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }
            else
            {
                // hero doesn't allowed this
                // app.UseHsts();

                //instead of that we will use our custom middleware
                app.Use(async(context, next) =>
                {
                    context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000");
                    await next.Invoke();
                });
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            // it searches an index.html file in wwwroot
            app.UseDefaultFiles();

            // serves static files from wwwroot
            app.UseStaticFiles();

            app.UseCors("CorsPolicy");

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub <ChatHub>("/chat");
                // we should create a controller named Fallback and has
                // an action name Index
                endpoints.MapFallbackToController("Index", "Fallback");
            });
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Configure the application HTTP request pipeline
 /// </summary>
 /// <param name="application">Builder for configuring an application's request pipeline</param>
 /// <param name="webHostEnvironment">Web Host Environment</param>
 public static void ConfigureRequestPipeline(this IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
 {
     EngineContext.Current.ConfigureRequestPipeline(application, webHostEnvironment);
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Gets the connection string for either Development or Production environments
 /// </summary>
 /// <returns>string</returns>
 public static string DatabaseConnectionString(IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
 {
     return(webHostEnvironment.IsDevelopment()
         ? configuration.GetConnectionString("DefaultConnection")
         : GetHerokuConnectionString());
 }
Ejemplo n.º 16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostApplicationLifetime applicationLifetime, IWebHostEnvironment env)
        {
            app.AddRequestTiming();

            var logger = app.ApplicationServices.GetService<ILogger<Startup>>();
            //var settings = app.ApplicationServices.GetService<IOptions<AppSettings>>();

            applicationLifetime.ApplicationStopping.Register(() =>
            {
                app.ApplicationServices.GetService<IGameData>().Flush();
            });

            //app.UseAuthentication();
            //app.UseAuthorization();

            app.UseCors(builder =>
                builder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin());

            app.UseResponseCompression();
            app.UseSession();
            app.UseDefaultFiles();
            app.UseStaticFiles();

            //var unityBuildPath = System.IO.Path.Combine(env.WebRootPath, "/assets/build");
            //if (System.IO.Directory.Exists(unityBuildPath))
            //{

            //StaticFileOptions option = new StaticFileOptions();
            //FileExtensionContentTypeProvider contentTypeProvider = (FileExtensionContentTypeProvider)option.ContentTypeProvider ??
            //new FileExtensionContentTypeProvider();

            //contentTypeProvider.Mappings.Add(".mem", "application/octet-stream");
            //contentTypeProvider.Mappings.Add(".data", "application/octet-stream");
            //contentTypeProvider.Mappings.Add(".memgz", "application/octet-stream");
            //contentTypeProvider.Mappings.Add(".datagz", "application/octet-stream");
            //contentTypeProvider.Mappings.Add(".unity3dgz", "application/octet-stream");
            //contentTypeProvider.Mappings.Add(".jsgz", "application/x-javascript; charset=UTF-8");
            //option.ContentTypeProvider = contentTypeProvider;
            //app.UseStaticFiles(option);

            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets", "build")),
            //    RequestPath = "/assets/build",
            //    ContentTypeProvider = UnityContentTypeProvider()
            //});
            //}

            app.Map("/session-state.js", builder =>
            {
                builder.Run(async context =>
                {
                    var sessionInfo = new SessionInfo();
                    context.Response.ContentType = "text/javascript";
                    var service = app.ApplicationServices.GetService<ISessionInfoProvider>();

                    if (!service.TryGet(context.Session, out sessionInfo))
                    {
                        //await logger.WriteErrorAsync("Failed to get sessionInfo for session-state.js");
                    }

                    context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
                    context.Response.Headers.Add("Expires", "-1");

                    await context.Response.WriteAsync($"var SessionState = {JSON.Stringify(sessionInfo)};");
                });
            });


            app.UseWebSockets(new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            });

            //app.UseMvc();

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRavenNestHealthChecks();
                endpoints.MapControllers();
                //endpoints.MapControllerRoute(
                //    name: "default",
                //    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapFallbackToController("Index", "Home");
            });

            app.MapWhen(x => !x.WebSockets.IsWebSocketRequest && !x.Request.Path.Value.StartsWith("/api"), builder =>
            {
                builder.UseRouting();
                builder.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");

                    endpoints.MapFallbackToController("Index", "Home");
                });
            });

            TryGenerateDocumentation(env);
        }
Ejemplo n.º 17
0
 public Startup(IWebHostEnvironment environment, IConfiguration configuration)
 {
     Environment = environment;
     Configuration = configuration;
 }
 public Startup(IConfiguration configuration, IWebHostEnvironment env)
 {
     Environment = env;
     Configuration = configuration;
 }
Ejemplo n.º 19
0
 public RTLTextService(IWebHostEnvironment hostingEnvironment)
 {
     _hostingEnvironment = hostingEnvironment;
 }
Ejemplo n.º 20
0
 public CasesController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)
 {
     _context = context;
     this._hostEnvironment = hostEnvironment;
 }
 public HomeController(IWebHostEnvironment host)
 {
     _host = host;
 }
Ejemplo n.º 22
0
 public PeopleController(IDBRepository <People, People> dataRepository, IWebHostEnvironment env)
 {
     _dataRepository = dataRepository;
     _env            = env;
 }
 public HomeController(IIdentityServerInteractionService interaction, IWebHostEnvironment environment, ILogger <HomeController> logger)
 {
     _interaction = interaction;
     _environment = environment;
     _logger      = logger;
 }
Ejemplo n.º 24
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseFileServer();

            // Custom CORS to allow any origin + credentials (which isn't allowed by the CORS spec)
            // This is for testing purposes only (karma hosts the client on its own server), never do this in production
            app.Use((context, next) =>
            {
                var originHeader = context.Request.Headers[HeaderNames.Origin];
                if (!StringValues.IsNullOrEmpty(originHeader))
                {
                    logger.LogInformation("Setting CORS headers.");
                    context.Response.Headers[HeaderNames.AccessControlAllowOrigin]      = originHeader;
                    context.Response.Headers[HeaderNames.AccessControlAllowCredentials] = "true";

                    var requestMethod = context.Request.Headers[HeaderNames.AccessControlRequestMethod];
                    if (!StringValues.IsNullOrEmpty(requestMethod))
                    {
                        context.Response.Headers[HeaderNames.AccessControlAllowMethods] = requestMethod;
                    }

                    var requestHeaders = context.Request.Headers[HeaderNames.AccessControlRequestHeaders];
                    if (!StringValues.IsNullOrEmpty(requestHeaders))
                    {
                        context.Response.Headers[HeaderNames.AccessControlAllowHeaders] = requestHeaders;
                    }
                }

                if (HttpMethods.IsOptions(context.Request.Method))
                {
                    logger.LogInformation("Setting '204' CORS response.");
                    context.Response.StatusCode = StatusCodes.Status204NoContent;
                    return(Task.CompletedTask);
                }

                return(next.Invoke());
            });

            app.Use((context, next) =>
            {
                if (context.Request.Path.StartsWithSegments("/redirect"))
                {
                    var newUrl = context.Request.Query["baseUrl"] + "/testHub?numRedirects=" + Interlocked.Increment(ref _numRedirects);
                    return(context.Response.WriteAsync($"{{ \"url\": \"{newUrl}\" }}"));
                }

                return(next());
            });

            app.Use(async(context, next) =>
            {
                if (context.Request.Path.Value.Contains("/negotiate"))
                {
                    context.Response.Cookies.Append("testCookie", "testValue");
                    context.Response.Cookies.Append("testCookie2", "testValue2");
                    context.Response.Cookies.Append("expiredCookie", "doesntmatter", new CookieOptions()
                    {
                        Expires = DateTimeOffset.Now.AddHours(-1)
                    });
                }

                await next.Invoke();
            });

            app.UseRouting();

            // Custom CORS to allow any origin + credentials (which isn't allowed by the CORS spec)
            // This is for testing purposes only (karma hosts the client on its own server), never do this in production
            app.UseCors(policy =>
            {
                policy.SetIsOriginAllowed(host => host.StartsWith("http://localhost:") || host.StartsWith("http://127.0.0.1:"))
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
            });

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <TestHub>("/testhub");
                endpoints.MapHub <TestHub>("/testhub-nowebsockets", options => options.Transports = HttpTransportType.ServerSentEvents | HttpTransportType.LongPolling);
                endpoints.MapHub <UncreatableHub>("/uncreatable");
                endpoints.MapHub <HubWithAuthorization>("/authorizedhub");

                endpoints.MapConnectionHandler <EchoConnectionHandler>("/echo");

                endpoints.MapGet("/generateJwtToken", context =>
                {
                    return(context.Response.WriteAsync(GenerateJwtToken()));
                });

                endpoints.MapGet("/deployment", context =>
                {
                    var attributes = Assembly.GetAssembly(typeof(Startup)).GetCustomAttributes <AssemblyMetadataAttribute>();

                    context.Response.ContentType = "application/json";
                    using (var textWriter = new StreamWriter(context.Response.Body))
                        using (var writer = new JsonTextWriter(textWriter))
                        {
                            var json       = new JObject();
                            var commitHash = string.Empty;

                            foreach (var attribute in attributes)
                            {
                                json.Add(attribute.Key, attribute.Value);

                                if (string.Equals(attribute.Key, "CommitHash"))
                                {
                                    commitHash = attribute.Value;
                                }
                            }

                            if (!string.IsNullOrEmpty(commitHash))
                            {
                                json.Add("GitHubUrl", $"https://github.com/aspnet/SignalR/commit/{commitHash}");
                            }

                            json.WriteTo(writer);
                        }

                    return(Task.CompletedTask);
                });
            });
        }
Ejemplo n.º 25
0
 public Startup(IConfiguration configuration, IWebHostEnvironment environment)
 {
     _configuration = configuration;
     _environment   = environment;
 }
Ejemplo n.º 26
0
 public ProductController1(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment)
 {
     _db = db;
     _webHostEnvironment = webHostEnvironment;
 }
Ejemplo n.º 27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            using var scoperService = app.ApplicationServices.CreateScope();

            var roleManager = scoperService.ServiceProvider.GetService <RoleManager <IdentityRole> >();

            var adminRole = roleManager.FindByNameAsync("Admin").GetAwaiter().GetResult();

            var userRole = roleManager.FindByNameAsync("StoreUser").GetAwaiter().GetResult();

            var supportRole = roleManager.FindByNameAsync("Support").GetAwaiter().GetResult();

            if (adminRole == null)
            {
                roleManager.CreateAsync(new IdentityRole
                {
                    Name = "Admin"
                }).GetAwaiter().GetResult();
            }

            if (userRole == null)
            {
                roleManager.CreateAsync(new IdentityRole
                {
                    Name = "StoreUser"
                }).GetAwaiter().GetResult();
            }

            if (supportRole == null)
            {
                roleManager.CreateAsync(new IdentityRole
                {
                    Name = "Support"
                }).GetAwaiter().GetResult();
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }


            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseResponseCompression();
            app.UseResponseCaching();
            app.UseRouting();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <RequestChatHub>("/requestChat");


                endpoints.MapControllerRoute(
                    "areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");


                endpoints.MapRazorPages();
            });
        }
Ejemplo n.º 28
0
        private static async Task EnsureSeedGlobalConfigurationData(SsoContext context, IConfiguration configuration, IWebHostEnvironment env)
        {
            if (!context.GlobalConfigurationSettings.Any())
            {
                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("SendEmail", configuration.GetSection("EmailConfiguration:SendEmail").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("UseStorage", configuration.GetSection("Storage:UseStorage").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Smtp:Server", configuration.GetSection("EmailConfiguration:SmtpServer").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Smtp:Port", configuration.GetSection("EmailConfiguration:SmtpPort").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Smtp:UseSsl", configuration.GetSection("EmailConfiguration:UseSsl").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Smtp:Username", configuration.GetSection("EmailConfiguration:SmtpUsername").Value, true, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Smtp:Password", configuration.GetSection("EmailConfiguration:SmtpPassword").Value, true, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:Service", configuration.GetSection("Storage:Service").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:VirtualPath", configuration.GetSection("Storage:VirtualPath").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:Username", configuration.GetSection("Storage:Username").Value, true, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:Password", configuration.GetSection("Storage:Password").Value, true, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:StorageName", configuration.GetSection("Storage:StorageName").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:BasePath", configuration.GetSection("Storage:BasePath").Value, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:PhysicalPath", env.WebRootPath, false, false));

                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("Storage:Region", configuration.GetSection("Storage:Region").Value, false, false));

                await context.SaveChangesAsync();
            }

            if (!context.Emails.Any())
            {
                var newUserEmail       = File.ReadAllText(Path.Combine(env.ContentRootPath, @"Assets/templates/new-user-email.html"));
                var resetPasswordEmail = File.ReadAllText(Path.Combine(env.ContentRootPath, @"Assets/templates/reset-password-email.html"));
                var template           = File.ReadAllText(Path.Combine(env.ContentRootPath, @"Assets/templates/default-template.html"));

                await context.Emails.AddAsync(new Email(newUserEmail, "Welcome to Chain of Change - Confirm your e-mail", new Sender("*****@*****.**", "JP Team"), EmailType.NewUser, null));

                await context.Emails.AddAsync(new Email(newUserEmail, "Welcome to Chain of Change - Confirm your e-mail", new Sender("*****@*****.**", "JP Team"), EmailType.NewUserWithoutPassword, null));

                await context.Emails.AddAsync(new Email(resetPasswordEmail, "Chain of Change - Reset Password", new Sender("*****@*****.**", "JP Team"), EmailType.RecoverPassword, null));

                await context.Templates.AddRangeAsync(new Template(template, "Chain of Change", "default-template", Users.GetEmail(configuration)));

                await context.SaveChangesAsync();
            }

            if (SsoVersion.Current <= Version.Parse("3.1.0"))
            {
                await context.GlobalConfigurationSettings.AddAsync(new GlobalConfigurationSettings("SSO:Version", "3.1.1", false, true));

                SsoVersion.Current = Version.Parse("3.1.1");
                var claims = await context.UserClaims.Where(w => w.ClaimType == "username" || w.ClaimType == "email" || w.ClaimType == "picture").ToListAsync();

                context.UserClaims.RemoveRange(claims);

                if (context.Clients.Include(c => c.AllowedGrantTypes).Any(s => s.ClientId == "IS4-Admin" && s.AllowedGrantTypes.Any(a => a.GrantType == "implicit")))
                {
                    var clientAdmin = context.Clients.Include(c => c.AllowedGrantTypes).FirstOrDefault(s => s.ClientId == "IS4-Admin");
                    clientAdmin.RequireClientSecret = false;
                    clientAdmin.AllowedGrantTypes.RemoveAll(a => a.ClientId == clientAdmin.Id);
                    clientAdmin.AllowedGrantTypes.Add(new ClientGrantType()
                    {
                        ClientId  = clientAdmin.Id,
                        GrantType = "authorization_code"
                    });
                    context.Update(clientAdmin);
                }
                await context.SaveChangesAsync();
            }


            if (SsoVersion.Current == Version.Parse("3.1.1"))
            {
                var ssoVersion = context.GlobalConfigurationSettings.FirstOrDefault(w => w.Key == "SSO:Version");
                ssoVersion.Update("3.2.0", true, false);
                SsoVersion.Current = new Version(ssoVersion.Value);
                await context.SaveChangesAsync();
            }

            if (SsoVersion.Current == Version.Parse("3.2.0"))
            {
                var ssoVersion = context.GlobalConfigurationSettings.FirstOrDefault(w => w.Key == "SSO:Version");
                ssoVersion.Update("3.2.2", true, false);
                SsoVersion.Current = new Version(ssoVersion.Value);
                await context.SaveChangesAsync();
            }
        }
Ejemplo n.º 29
0
 public ExceptionsFilter(ILogger <ExceptionsFilter> logger, IWebHostEnvironment env)
 {
     _logger = logger;
     _env    = env;
 }
Ejemplo n.º 30
0
 public CategoryService(BookServices bookServices, bookstoreContext bookstoreContext, IWebHostEnvironment webHostEnvironment, IMapper mapper) : base(bookstoreContext, webHostEnvironment, mapper)
 {
     _bookServices = bookServices;
 }