Example #1
0
        private void RegisterFramework(IServiceCollection serviceCollection)
        {
            serviceCollection.AddScoped <IPageHeadBuilder, PageHeadBuilder>();

            serviceCollection.AddScoped <IThemeProvider, ThemeProvider>();
            serviceCollection.AddScoped <IThemeContext, ThemeContext>();

            serviceCollection.AddScoped <SlugRouteTransformer>();

            serviceCollection.AddScoped <IResourceManager, ResourceManager>();

            if (DataSettingsManager.DatabaseIsInstalled())
            {
                serviceCollection.AddScoped <LocService>();
            }
            else
            {
                var provider = serviceCollection.BuildServiceProvider();
                var _tmp     = provider.GetRequiredService <IStringLocalizerFactory>();
                serviceCollection.AddScoped(c => new LocService(_tmp));
            }

            //powered by
            serviceCollection.AddSingleton <IPoweredByMiddlewareOptions, PoweredByMiddlewareOptions>();
        }
Example #2
0
        public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
        {
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            application.UseMiddleware <DbVersionCheckMiddleware>();
        }
Example #3
0
        /// <summary>
        /// Add exception handling
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void UseGrandExceptionHandler(this IApplicationBuilder application)
        {
            var serviceProvider          = application.ApplicationServices;
            var appConfig                = serviceProvider.GetRequiredService <AppConfig>();
            var hostingEnvironment       = serviceProvider.GetRequiredService <IWebHostEnvironment>();
            var useDetailedExceptionPage = appConfig.DisplayFullErrorStack || hostingEnvironment.IsDevelopment();

            if (useDetailedExceptionPage)
            {
                //get detailed exceptions for developing and testing purposes
                application.UseDeveloperExceptionPage();
            }
            else
            {
                //or use special exception handler
                application.UseExceptionHandler("/errorpage.htm");
            }

            //log errors
            application.UseExceptionHandler(handler =>
            {
                handler.Run(async context =>
                {
                    var exception = context.Features.Get <IExceptionHandlerFeature>()?.Error;
                    if (exception == null)
                    {
                        return;
                    }

                    string authHeader = context.Request.Headers["Authorization"];
                    var apirequest    = authHeader != null && authHeader.Split(' ')[0] == "Bearer";
                    if (apirequest)
                    {
                        await context.Response.WriteAsync(exception.Message);
                        return;
                    }
                    try
                    {
                        //check whether database is installed
                        if (DataSettingsManager.DatabaseIsInstalled())
                        {
                            var logger = context.RequestServices.GetRequiredService <ILogger>();
                            //get current customer
                            var workContext = context.RequestServices.GetRequiredService <IWorkContext>();
                            //log error
                            logger.Error(exception.Message, exception, workContext.CurrentCustomer);
                        }
                    }
                    finally
                    {
                        //rethrow the exception to show the error page
                        throw exception;
                    }
                });
            });
        }
Example #4
0
        private void RegisterInstallService(IServiceCollection serviceCollection)
        {
            var databaseInstalled = DataSettingsManager.DatabaseIsInstalled();

            if (!databaseInstalled)
            {
                //installation service
                serviceCollection.AddScoped <IInstallationLocalizedService, InstallationLocalizedService>();
                serviceCollection.AddScoped <IInstallationService, InstallationService>();
            }
        }
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    await next();

                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    await next();

                    return;
                }

                //only in GET requests
                if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
                {
                    await next();

                    return;
                }

                //whether SEO friendly URLs are enabled
                if (!_config.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    await next();

                    return;
                }

                var lang = context.RouteData.Values["language"];

                if (lang == null)
                {
                    await next();

                    return;
                }

                //check whether current page URL is already localized URL
                var pageUrl = context.HttpContext?.Request?.GetEncodedPathAndQuery();

                if (await IsLocalized(pageUrl, context.HttpContext.Request.PathBase))
                {
                    await next();

                    return;
                }

                pageUrl        = AddLanguageSeo(pageUrl, context.HttpContext.Request.PathBase, _workContext.WorkingLanguage);
                context.Result = new RedirectResult(pageUrl, false);
            }
Example #6
0
        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
        {
            //check whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            //configure authentication
            application.UseHostFiltering();
        }
Example #7
0
        /// <summary>
        /// Adds services for WebEncoderOptions
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddWebEncoder(this IServiceCollection services)
        {
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            services.Configure <WebEncoderOptions>(options =>
            {
                options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });
        }
        public virtual IActionResult RestartInstall()
        {
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //stop application
            _applicationLifetime.StopApplication();

            //Redirect to home page
            return(RedirectToRoute("HomePage"));
        }
Example #9
0
        /// <summary>
        /// Adds services required for themes support
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddThemes(this IServiceCollection services)
        {
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            //themes support
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            });
        }
Example #10
0
        /// <summary>
        /// Save log application started
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void LogApplicationStarted(this IApplicationBuilder application)
        {
            //whether database is already installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            var serviceProvider = application.ApplicationServices;
            var logger          = serviceProvider.GetRequiredService <ILogger>();

            logger.Information("Application started", null, null);
        }
Example #11
0
        public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
        {
            var pattern = "";

            if (DataSettingsManager.DatabaseIsInstalled())
            {
                var config = endpointRouteBuilder.ServiceProvider.GetRequiredService <AppConfig>();
                if (config.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    pattern = $"{{language:lang={config.SeoFriendlyUrlsDefaultCode}}}/";
                }
            }

            //home page
            endpointRouteBuilder.MapControllerRoute("HomePage", pattern, new { controller = "Home", action = "Index" });


            RegisterAccountRoute(endpointRouteBuilder, pattern);

            RegisterVendorRoute(endpointRouteBuilder, pattern);

            RegisterCartRoute(endpointRouteBuilder, pattern);

            RegisterOrderRoute(endpointRouteBuilder, pattern);

            RegisterMerchandiseReturnRoute(endpointRouteBuilder, pattern);

            RegisterCommonRoute(endpointRouteBuilder, pattern);

            RegisterCatalogRoute(endpointRouteBuilder, pattern);

            RegisterProductRoute(endpointRouteBuilder, pattern);

            RegisterCmsRoute(endpointRouteBuilder, pattern);

            RegisterBlogRoute(endpointRouteBuilder, pattern);

            RegisterNewsletterRoute(endpointRouteBuilder, pattern);

            RegisterAddToCartRoute(endpointRouteBuilder, pattern);

            RegisterOutOfStockSubscriptionRoute(endpointRouteBuilder, pattern);

            RegisterCheckoutRoute(endpointRouteBuilder, pattern);

            RegisterDownloadRoute(endpointRouteBuilder, pattern);

            RegisterPageRoute(endpointRouteBuilder, pattern);

            RegisterInstallRoute(endpointRouteBuilder, pattern);
        }
Example #12
0
        public virtual IActionResult ChangeLanguage(string language)
        {
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            var locService = _serviceProvider.GetRequiredService <IInstallationLocalizedService>();

            locService.SaveCurrentLanguage(language);

            //Reload the page
            return(RedirectToAction("Index", "Install"));
        }
        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
        {
            //check whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            //configure authentication
            application.UseGrandAuthentication();

            //set workcontext
            application.UseMiddleware <WorkContextMiddleware>();
        }
Example #14
0
            /// <summary>
            /// Called early in the filter pipeline to confirm request is authorized
            /// </summary>
            /// <param name="filterContext">Authorization filter context</param>
            public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)
            {
                if (filterContext == null)
                {
                    throw new ArgumentNullException(nameof(filterContext));
                }

                //check whether this filter has been overridden for the action
                var actionFilter = filterContext.ActionDescriptor.FilterDescriptors
                                   .Where(f => f.Scope == FilterScope.Action)
                                   .Select(f => f.Filter).OfType <AuthorizeAdminAttribute>().FirstOrDefault();

                //ignore filter (the action is available even if a customer hasn't access to the admin area)
                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //there is AdminAuthorizeFilter, so check access
                if (filterContext.Filters.Any(filter => filter is AuthorizeAdminFilter))
                {
                    //authorize permission of access to the admin area
                    if (!await _permissionService.Authorize(StandardPermission.AccessAdminPanel))
                    {
                        filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
                    }

                    //get allowed IP addresses
                    var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;

                    //there are no restrictions
                    if (ipAddresses == null || !ipAddresses.Any())
                    {
                        return;
                    }

                    //whether current IP is allowed
                    var currentIp = filterContext.HttpContext?.Connection?.RemoteIpAddress?.ToString();
                    if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))
                    {
                        filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
                    }
                }
            }
Example #15
0
        public virtual async Task <IActionResult> Index()
        {
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            var locService = _serviceProvider.GetRequiredService <IInstallationLocalizedService>();

            var installed = await _cacheBase.GetAsync("Installed", async() => { return(await Task.FromResult(false)); });

            if (installed)
            {
                return(View(new InstallModel()
                {
                    Installed = true
                }));
            }

            var model = new InstallModel {
                AdminEmail               = "*****@*****.**",
                InstallSampleData        = false,
                DatabaseConnectionString = "",
            };

            model.AvailableProviders = Enum.GetValues(typeof(DbProvider)).Cast <DbProvider>().Select(v => new SelectListItem {
                Text  = v.ToString(),
                Value = ((int)v).ToString()
            }).ToList();

            foreach (var lang in locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem {
                    Value    = Url.RouteUrl("InstallChangeLanguage", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = locService.GetCurrentLanguage().Code == lang.Code,
                });
            }
            //prepare collation list
            foreach (var col in locService.GetAvailableCollations())
            {
                model.AvailableCollation.Add(new SelectListItem {
                    Value    = col.Value,
                    Text     = col.Name,
                    Selected = locService.GetCurrentLanguage().Code == col.Value,
                });
            }
            return(View(model));
        }
Example #16
0
 /// <summary>
 /// Adds services required for application session state
 /// </summary>
 /// <param name="services">Collection of service descriptors</param>
 public static void AddHttpSession(this IServiceCollection services, AppConfig config)
 {
     services.AddSession(options =>
     {
         options.Cookie = new CookieBuilder()
         {
             Name     = $"{config.CookiePrefix}Session",
             HttpOnly = true,
         };
         if (DataSettingsManager.DatabaseIsInstalled())
         {
             options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
         }
     });
 }
Example #17
0
        /// <summary>
        /// Create and configure MiniProfiler service
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void UseProfiler(this IApplicationBuilder application)
        {
            //whether database is already installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            var appConfig = application.ApplicationServices.GetRequiredService <AppConfig>();

            //whether MiniProfiler should be displayed
            if (appConfig.DisplayMiniProfilerInPublicStore)
            {
                application.UseMiniProfiler();
            }
        }
Example #18
0
        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        /// <param name="webHostEnvironment">WebHostEnvironment</param>
        public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
        {
            //check whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            var serviceProvider = application.ApplicationServices;
            var hostingConfig   = serviceProvider.GetRequiredService <HostingConfig>();

            if (hostingConfig.UseForwardedHeaders)
            {
                application.UseGrandForwardedHeaders();
            }
        }
Example #19
0
 /// <summary>
 /// Adds services required for anti-forgery support
 /// </summary>
 /// <param name="services">Collection of service descriptors</param>
 public static void AddAntiForgery(this IServiceCollection services, AppConfig config)
 {
     //override cookie name
     services.AddAntiforgery(options =>
     {
         options.Cookie = new CookieBuilder()
         {
             Name = $"{config.CookiePrefix}Antiforgery"
         };
         if (DataSettingsManager.DatabaseIsInstalled())
         {
             //whether to allow the use of anti-forgery cookies from SSL protected page on the other store pages which are not
             options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
         }
     });
 }
Example #20
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();

                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                //check request query parameters
                var request = context.HttpContext.Request;

                if (request?.Query == null || !request.Query.Any())
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //try to find by ID
                var affiliateIds = request.Query[ID_QUERY_PARAMETER_NAME];

                if (affiliateIds.Any())
                {
                    string affiliateId = affiliateIds.FirstOrDefault();
                    if (!string.IsNullOrEmpty(affiliateId))
                    {
                        await SetCustomerAffiliateId(await _affiliateService.GetAffiliateById(affiliateId));
                    }
                    return;
                }

                //try to find by friendly name
                var affiliateNames = request.Query[FRIENDLYURLNAME_QUERY_PARAMETER_NAME];

                if (affiliateNames.Any())
                {
                    var affiliateName = affiliateNames.FirstOrDefault();
                    if (!string.IsNullOrEmpty(affiliateName))
                    {
                        await SetCustomerAffiliateId(await _affiliateService.GetAffiliateByFriendlyUrlName(affiliateName));
                    }
                }
            }
Example #21
0
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task InvokeAsync(HttpContext context)
        {
            //whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                var installUrl = $"/install";
                if (!context.Request.GetEncodedPathAndQuery().StartsWith(installUrl, StringComparison.OrdinalIgnoreCase))
                {
                    //redirect
                    context.Response.Redirect(installUrl);
                    return;
                }
            }

            //or call the next middleware in the request pipeline
            await _next(context);
        }
Example #22
0
        /// <summary>
        /// Add Progressive Web App
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddPWA(this IServiceCollection services, IConfiguration configuration)
        {
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            var config = new AppConfig();

            configuration.GetSection("Application").Bind(config);
            if (config.EnableProgressiveWebApp)
            {
                var options = new WebEssentials.AspNetCore.Pwa.PwaOptions {
                    Strategy       = (WebEssentials.AspNetCore.Pwa.ServiceWorkerStrategy)config.ServiceWorkerStrategy,
                    RoutesToIgnore = "/admin/*"
                };
                services.AddProgressiveWebApp(options);
            }
        }
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //get action and controller names
                var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var actionName       = actionDescriptor?.ActionName;
                var controllerName   = actionDescriptor?.ControllerName;

                if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))
                {
                    return;
                }

                //don't validate on ChangePassword page and store closed
                if ((!(controllerName.Equals("Customer", StringComparison.OrdinalIgnoreCase) &&
                       actionName.Equals("ChangePassword", StringComparison.OrdinalIgnoreCase)))
                    &&
                    !(controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&
                      actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase))
                    )
                {
                    //check password expiration
                    var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery()
                    {
                        Customer = _workContext.CurrentCustomer
                    });

                    if (passwordIsExpired)
                    {
                        //redirect to ChangePassword page if expires
                        context.Result = new RedirectToRouteResult("CustomerChangePassword", new RouteValueDictionary());
                    }
                }
            }
            /// <summary>
            /// Called early in the filter pipeline to confirm request is authorized
            /// </summary>
            /// <param name="filterContext">Authorization filter context</param>
            public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)
            {
                //ignore filter (the action available even when navigation is not allowed)
                if (filterContext == null)
                {
                    throw new ArgumentNullException(nameof(filterContext));
                }

                //check whether this filter has been overridden for the Action
                var actionFilter = filterContext.ActionDescriptor.FilterDescriptors
                                   .Where(f => f.Scope == FilterScope.Action)
                                   .Select(f => f.Filter).OfType <PublicStoreAttribute>().FirstOrDefault();


                //ignore filter (the action is available even if navigation is not allowed)
                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //check whether current customer has access to a public store
                if (await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))
                {
                    return;
                }

                if (_storeInformationSettings.StoreClosed)
                {
                    filterContext.Result = new RedirectToRouteResult("StoreClosed", new RouteValueDictionary());
                }
                else
                {
                    //customer has not access to a public store
                    filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary());
                }
            }
Example #25
0
        /// <summary>
        /// Add mini profiler service for the application
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddGrandMiniProfiler(this IServiceCollection services)
        {
            //whether database is already installed
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            //add MiniProfiler services
            services.AddMiniProfiler(options =>
            {
                options.IgnoredPaths.Add("/api");
                options.IgnoredPaths.Add("/odata");
                options.IgnoredPaths.Add("/health/live");
                options.IgnoredPaths.Add("/.well-known/pki-validation");
                //determine who can access the MiniProfiler results
                options.ResultsAuthorize = request =>
                                           !request.HttpContext.RequestServices.GetRequiredService <AppConfig>().DisplayMiniProfilerInPublicStore ||
                                           request.HttpContext.RequestServices.GetRequiredService <IPermissionService>().Authorize(StandardPermission.AccessAdminPanel).Result;
            });
        }
        /// <summary>
        /// Add and configure any of the middleware
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration root of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //database is already installed, so start scheduled tasks
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                var typeSearcher  = new AppTypeSearcher();
                var scheduleTasks = typeSearcher.ClassesOfType <IScheduleTask>();

                var scheduleTasksInstalled = scheduleTasks
                                             .Where(t => PluginExtensions.OnlyInstalledPlugins(t)); //ignore not installed plugins

                foreach (var task in scheduleTasksInstalled)
                {
                    var assemblyName = task.Assembly.GetName().Name;
                    services.AddSingleton <IHostedService, BackgroundServiceTask>(sp =>
                    {
                        return(new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp));
                    });
                }
            }
        }
            /// <summary>
            /// Called early in the filter pipeline to confirm request is authorized
            /// </summary>
            /// <param name="filterContext">Authorization filter context</param>
            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                //ignore filter actions
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                //check whether this filter has been overridden for the Action
                var actionFilter = context.ActionDescriptor.FilterDescriptors
                                   .Where(f => f.Scope == FilterScope.Action)
                                   .Select(f => f.Filter).OfType <AuthorizeVendorAttribute>().FirstOrDefault();

                //ignore filter (the action is available even if the current customer isn't a vendor)
                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //whether current customer is vendor
                if (!await _groupService.IsVendor(_workContext.CurrentCustomer))
                {
                    return;
                }

                //ensure that this user has active vendor record associated
                if (_workContext.CurrentVendor == null)
                {
                    context.Result = new ChallengeResult();
                }
            }
Example #28
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();

                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //only in GET requests
                if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
                {
                    return;
                }

                //update last activity date
                if (_workContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(1.0) < DateTime.UtcNow)
                {
                    await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastActivityDateUtc, DateTime.UtcNow);
                }

                //get current IP address
                var currentIpAddress = context.HttpContext?.Connection?.RemoteIpAddress?.ToString();

                //update customer's IP address
                if (!string.IsNullOrEmpty(currentIpAddress) && !currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress, StringComparison.OrdinalIgnoreCase))
                {
                    _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;
                    await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastIpAddress, currentIpAddress);
                }

                //whether is need to store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = context.HttpContext?.Request?.GetDisplayUrl();

                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                //get previous last page
                var previousPageUrl = _workContext.CurrentCustomer.GetUserFieldFromEntity <string>(SystemCustomerFieldNames.LastVisitedPage);

                //save new one if don't match
                if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))
                {
                    await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastVisitedPage, pageUrl);
                }

                if (!string.IsNullOrEmpty(context.HttpContext.Request.Headers[HeaderNames.Referer]))
                {
                    if (!context.HttpContext.Request.Headers[HeaderNames.Referer].ToString().Contains(context.HttpContext.Request.Host.ToString()))
                    {
                        var previousUrlReferrer = _workContext.CurrentCustomer.GetUserField <string>(_userFieldService, SystemCustomerFieldNames.LastUrlReferrer);
                        var actualUrlReferrer   = context.HttpContext.Request.Headers[HeaderNames.Referer];
                        if (previousUrlReferrer != actualUrlReferrer)
                        {
                            await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastUrlReferrer, actualUrlReferrer);
                        }
                    }
                }

                if (_customerSettings.SaveVisitedPage)
                {
                    if (!_workContext.CurrentCustomer.IsSearchEngineAccount())
                    {
                        //activity
                        await _customerActivityService.InsertActivity("PublicStore.Url", pageUrl, pageUrl, _workContext.CurrentCustomer);

                        //action
                        await _customerActionEventService.Url(_workContext.CurrentCustomer, context.HttpContext?.Request?.Path.ToString(), context.HttpContext?.Request?.Headers["Referer"]);
                    }
                }
            }
        public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
        {
            if (!DataSettingsManager.DatabaseIsInstalled())
            {
                return;
            }

            var pattern = "{**SeName}";
            var config  = endpointRouteBuilder.ServiceProvider.GetRequiredService <AppConfig>();

            if (config.SeoFriendlyUrlsForLanguagesEnabled)
            {
                pattern = $"{{language:lang={config.SeoFriendlyUrlsDefaultCode}}}/{{**SeName}}";
            }

            endpointRouteBuilder.MapDynamicControllerRoute <SlugRouteTransformer>(pattern);

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

            //generic URLs
            endpointRouteBuilder.MapControllerRoute(
                name: "GenericUrl",
                pattern: "{GenericSeName}",
                new { controller = "Common", action = "GenericUrl" });

            //define this routes to use in UI views (in case if you want to customize some of them later)
            endpointRouteBuilder.MapControllerRoute(
                name: "Product",
                pattern: pattern,
                new { controller = "Product", action = "ProductDetails" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Category",
                pattern: pattern,
                new { controller = "Catalog", action = "Category" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Brand",
                pattern: pattern,
                new { controller = "Catalog", action = "Brand" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Collection",
                pattern: pattern,
                new { controller = "Catalog", action = "Collection" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Vendor",
                pattern: pattern,
                new { controller = "Catalog", action = "Vendor" });

            endpointRouteBuilder.MapControllerRoute(
                name: "NewsItem",
                pattern: pattern,
                new { controller = "News", action = "NewsItem" });

            endpointRouteBuilder.MapControllerRoute(
                name: "BlogPost",
                pattern: pattern,
                new { controller = "Blog", action = "BlogPost" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Page",
                pattern: pattern,
                new { controller = "Page", action = "PageDetails" });

            endpointRouteBuilder.MapControllerRoute(
                name: "KnowledgebaseArticle",
                pattern: pattern,
                new { controller = "Knowledgebase", action = "KnowledgebaseArticle" });

            endpointRouteBuilder.MapControllerRoute(
                name: "KnowledgebaseCategory",
                pattern: pattern,
                new { controller = "Knowledgebase", action = "ArticlesByCategory" });

            endpointRouteBuilder.MapControllerRoute(
                name: "Course",
                pattern: pattern,
                new { controller = "Course", action = "Details" });
        }
Example #30
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            var locService = _serviceProvider.GetRequiredService <IInstallationLocalizedService>();

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            string connectionString = "";

            if (model.ConnectionInfo)
            {
                if (String.IsNullOrEmpty(model.DatabaseConnectionString))
                {
                    ModelState.AddModelError("", locService.GetResource("ConnectionStringRequired"));
                }
                else
                {
                    connectionString = model.DatabaseConnectionString;
                }
            }
            else
            {
                if (String.IsNullOrEmpty(model.MongoDBDatabaseName))
                {
                    ModelState.AddModelError("", locService.GetResource("DatabaseNameRequired"));
                }
                if (String.IsNullOrEmpty(model.MongoDBServerName))
                {
                    ModelState.AddModelError("", locService.GetResource("MongoDBServerNameRequired"));
                }
                string userNameandPassword = "";
                if (!(String.IsNullOrEmpty(model.MongoDBUsername)))
                {
                    userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";
                }

                connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;
            }

            if (!string.IsNullOrEmpty(connectionString))
            {
                try
                {
                    var mdb = new MongoDBContext();
                    if (await mdb.DatabaseExist(connectionString))
                    {
                        ModelState.AddModelError("", locService.GetResource("AlreadyInstalled"));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", locService.GetResource("ConnectionStringRequired"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    //save settings
                    var settings = new DataSettings {
                        ConnectionString = connectionString,
                        DbProvider       = model.DataProvider
                    };
                    await DataSettingsManager.SaveSettings(settings);

                    var installationService = _serviceProvider.GetRequiredService <IInstallationService>();
                    await installationService.InstallData(model.AdminEmail, model.AdminPassword, model.Collation,
                                                          model.InstallSampleData, model.CompanyName, model.CompanyAddress, model.CompanyPhoneNumber, model.CompanyEmail);

                    //reset cache
                    DataSettingsManager.ResetCache();

                    PluginManager.ClearPlugins();

                    var pluginsInfo = PluginManager.ReferencedPlugins.ToList();

                    foreach (var pluginInfo in pluginsInfo)
                    {
                        try
                        {
                            var plugin = pluginInfo.Instance <IPlugin>(_serviceProvider);
                            await plugin.Install();
                        }
                        catch (Exception ex)
                        {
                            var _logger = _serviceProvider.GetRequiredService <ILogger>();
                            await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Error during installing plugin " + pluginInfo.SystemName,
                                                    ex.Message + " " + ex.InnerException?.Message);
                        }
                    }

                    //register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(PermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        await _mediator.Send(new InstallPermissionsCommand()
                        {
                            PermissionProvider = provider
                        });
                    }

                    //restart application
                    await _cacheBase.SetAsync("Installed", true, 120);

                    return(View(new InstallModel()
                    {
                        Installed = true
                    }));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsManager.ResetCache();
                    await _cacheBase.Clear();

                    System.IO.File.Delete(CommonPath.SettingsPath);

                    ModelState.AddModelError("", string.Format(locService.GetResource("SetupFailed"), exception.Message + " " + exception.InnerException?.Message));
                }
            }
            //prepare db providers
            model.AvailableProviders = Enum.GetValues(typeof(DbProvider)).Cast <DbProvider>().Select(v => new SelectListItem {
                Text  = v.ToString(),
                Value = ((int)v).ToString()
            }).ToList();

            //prepare language list
            foreach (var lang in locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem {
                    Value    = Url.RouteUrl("InstallChangeLanguage", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            //prepare collation list
            foreach (var col in locService.GetAvailableCollations())
            {
                model.AvailableCollation.Add(new SelectListItem {
                    Value    = col.Value,
                    Text     = col.Name,
                    Selected = locService.GetCurrentLanguage().Code == col.Value,
                });
            }

            return(View(model));
        }