Exemple #1
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 (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            var grandConfig = application.ApplicationServices.GetRequiredService <GrandConfig>();

            //whether MiniProfiler should be displayed
            if (grandConfig.DisplayMiniProfilerInPublicStore)
            {
                application.UseMiniProfiler();
            }
        }
Exemple #2
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, GrandConfig config)
 {
     //override cookie name
     services.AddAntiforgery(options =>
     {
         options.Cookie = new CookieBuilder()
         {
             Name = ".Grand.Antiforgery"
         };
         if (DataSettingsHelper.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;
         }
     });
 }
Exemple #3
0
        public virtual void OnViewNotFound(ActionContext actionContext, bool isMainPage, IActionResult result, string viewName, IEnumerable <string> searchedLocations)
        {
            //check whether database is installed
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            var workContext = EngineContext.Current.Resolve <IWorkContext>();
            var logger      = EngineContext.Current.Resolve <ILogger>();

            //log error
            var error = $"The view '{viewName}' was not found. The following locations were searched:{Environment.NewLine}{string.Join(Environment.NewLine, searchedLocations)}";

            logger.Error(error, customer: workContext.CurrentCustomer);
        }
Exemple #4
0
        /// <summary>
        /// Returns information about the URL that is associated with the route.
        /// </summary>
        /// <param name="requestContext">An object that encapsulates information about the requested route.</param>
        /// <param name="values">An object that contains the parameters for a route.</param>
        /// <returns>
        /// An object that contains information about the URL that is associated with the route.
        /// </returns>
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            VirtualPathData data = base.GetVirtualPath(requestContext, values);

            if (data != null && DataSettingsHelper.DatabaseIsInstalled() && this.SeoFriendlyUrlsForLanguagesEnabled)
            {
                string rawUrl          = requestContext.HttpContext.Request.RawUrl;
                string applicationPath = requestContext.HttpContext.Request.ApplicationPath;
                if (rawUrl.IsLocalizedUrl(applicationPath, true))
                {
                    data.VirtualPath = string.Concat(rawUrl.GetLanguageSeoCodeFromUrl(applicationPath, true), "/",
                                                     data.VirtualPath);
                }
            }
            return(data);
        }
Exemple #5
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 (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

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

            if (hostingConfig.UseForwardedHeaders)
            {
                application.UseGrandForwardedHeaders();
            }
        }
        /// <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 (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            var serviceProvider = application.ApplicationServices;

            //whether MiniProfiler should be displayed
            if (serviceProvider.GetRequiredService <StoreInformationSettings>().DisplayMiniProfilerInPublicStore)
            {
                application.UseMiniProfiler();
            }
        }
Exemple #7
0
        protected bool CanPerformProfilingAction()
        {
            //will not run in medium trust
            if (CommonHelper.GetTrustLevel() < AspNetHostingPermissionLevel.High)
            {
                return(false);
            }

            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return(false);
            }

            return(true);
            //return EngineContext.Current.Resolve<StoreInformationSettings>().DisplayMiniProfilerInPublicStore;
        }
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public void OnActionExecuting(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

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

                //only in GET requests
                if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

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

                //whether SEO friendly URLs are enabled
                if (!_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    return;
                }

                //ensure that this route is registered and localizable (LocalizedRoute in RouteProvider)
                if (context.RouteData?.Routers == null || !context.RouteData.Routers.ToList().Any(r => r is LocalizedRoute))
                {
                    return;
                }

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

                if (pageUrl.IsLocalizedUrl(context.HttpContext.Request.PathBase, true, out Language _))
                {
                    return;
                }

                //not localized yet, so redirect to the page with working language SEO code
                pageUrl        = pageUrl.AddLanguageSeoCodeToUrl(context.HttpContext.Request.PathBase, true, _workContext.WorkingLanguage);
                context.Result = new RedirectResult(pageUrl, false);
            }
Exemple #9
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!DataSettingsHelper.DatabaseInstalled())
            {
                return;
            }

            if (filterContext?.HttpContext?.Request == null)
            {
                return;
            }

            //不要将筛选器应用于子请求
            if (filterContext.IsChildAction)
            {
                return;
            }

            //不要将筛选器应用于AJAX请求
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                return;
            }

            //筛选仅接受Get请求记录
            if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var webHelper = EngineContext.Current.Resolve <IWebHelper>();

            //更新ip地址
            string currentIpAddress = webHelper.GetCurrentIpAddress();

            if (!string.IsNullOrEmpty(currentIpAddress))
            {
                var workContext = EngineContext.Current.Resolve <IWorkContext>();
                var customer    = workContext.Customer as Customer;
                if (customer != null && !currentIpAddress.Equals(customer.LastIpAddress, StringComparison.InvariantCultureIgnoreCase))
                {
                    var customerService = EngineContext.Current.Resolve <ICustomerService>();
                    customer.LastIpAddress = currentIpAddress;
                    customerService.UpdateCustomer(customer);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Adds authentication service
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddNopAuthentication(this IServiceCollection services)
        {
            //set default authentication schemes
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = NopCookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme    = NopCookieAuthenticationDefaults.ExternalAuthenticationScheme;
            });

            //add main cookie authentication
            authenticationBuilder.AddCookie(NopCookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name      = NopCookieAuthenticationDefaults.CookiePrefix + NopCookieAuthenticationDefaults.AuthenticationScheme;
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopCookieAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsHelper.DatabaseIsInstalled() && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //add external authentication
            authenticationBuilder.AddCookie(NopCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>
            {
                options.Cookie.Name      = NopCookieAuthenticationDefaults.CookiePrefix + NopCookieAuthenticationDefaults.ExternalAuthenticationScheme;
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopCookieAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsHelper.DatabaseIsInstalled() && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //register and configure external authentication plugins now
            var typeFinder = new WebAppTypeFinder();
            var externalAuthConfigurations = typeFinder.FindClassesOfType <IExternalAuthenticationRegistrar>();
            var externalAuthInstances      = externalAuthConfigurations
                                             .Where(x => PluginManager.FindPlugin(x)?.Installed ?? true) //ignore not installed plugins
                                             .Select(x => (IExternalAuthenticationRegistrar)Activator.CreateInstance(x));

            foreach (var instance in externalAuthInstances)
            {
                instance.Configure(authenticationBuilder);
            }
        }
            /// <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 (!DataSettingsHelper.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));
                    }
                }
            }
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task Invoke(HttpContext context, IWebHelper webHelper)
        {
            //TODO test. ensure that no guest record is created

            //whether database is installed
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                //keep alive page requested (we ignore it to prevent creating a guest customer records)
                var keepAliveUrl = $"{webHelper.GetStoreLocation()}keepalive/index";
                if (webHelper.GetThisPageUrl(false).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }
            }
            //or call the next middleware in the request pipeline
            await _next(context);
        }
Exemple #13
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 (!DataSettingsHelper.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);
        }
 /// <summary>
 /// Adds services required for application session state
 /// </summary>
 /// <param name="services">Collection of service descriptors</param>
 public static void AddHttpSession(this IServiceCollection services)
 {
     services.AddSession(options =>
     {
         options.Cookie = new CookieBuilder()
         {
             Name     = ".Grand.Session",
             HttpOnly = true,
         };
         if (DataSettingsHelper.DatabaseIsInstalled())
         {
             //whether to allow the use of session values from SSL protected page on the other store pages which are not
             options.Cookie.SecurePolicy = EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                 ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
         }
     });
 }
 /// <summary>
 /// Adds services required for anti-forgery support
 /// </summary>
 /// <param name="services">Collection of service descriptors</param>
 public static void AddAntiForgery(this IServiceCollection services)
 {
     //override cookie name
     services.AddAntiforgery(options =>
     {
         options.Cookie = new CookieBuilder()
         {
             Name = ".Grand.Antiforgery"
         };
         if (DataSettingsHelper.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 = EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
             ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
         }
     });
 }
Exemple #16
0
        static void Main(string[] args)
        {
            Console.Title = typeof(Program).Name;
            //initialize engine context
            EngineContext.Initialize(false);

            bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();

            var nopVersion = NopVersion.CurrentVersion;


            if (!databaseInstalled)
            {
                Console.WriteLine("Database is not installed, copy Settings.txt to App_Data directory");
                return;
            }

            Console.WriteLine("Welcome to NopCommand for NopCommerce " + nopVersion);

            // Any static classes containing commands for use from the
            // console are located in the Commands namespace. Load
            // references to each type in that namespace via reflection:
            _commandLibraries = new Dictionary <string, Dictionary <string,
                                                                    IEnumerable <ParameterInfo> > >();

            // Use reflection to load all of the classes in the Commands namespace:
            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass && t.Namespace == CommandNamespace && (!t.Name.StartsWith("<>"))
                    select t;
            var commandClasses = q.ToList();

            foreach (var commandClass in commandClasses)
            {
                // Load the method info from each class into a dictionary:
                var methods          = commandClass.GetMethods(BindingFlags.Static | BindingFlags.Public);
                var methodDictionary = new Dictionary <string, IEnumerable <ParameterInfo> >();
                foreach (var method in methods)
                {
                    var commandName = method.Name;
                    methodDictionary.Add(commandName, method.GetParameters());
                }
                // Add the dictionary of methods for the current class into a dictionary of command classes:
                _commandLibraries.Add(commandClass.Name, methodDictionary);
            }
            Run();
        }
Exemple #17
0
        protected void SetWorkingCulture()
        {
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            //ignore static resources
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();

            if (webHelper.IsStaticResource(this.Request))
            {
                return;
            }

            //keep alive page requested (we ignore it to prevent creating a guest customer records)
            //string keepAliveUrl = string.Format("{0}keepalive/index", webHelper.GetStoreLocation());
            //if (webHelper.GetThisPageUrl(false).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase))
            //    return;

            /*
             * if (webHelper.GetThisPageUrl(false).StartsWith(string.Format("{0}admin", webHelper.GetStoreLocation()),
             *  StringComparison.InvariantCultureIgnoreCase))
             * {
             *  //admin area
             *
             *
             *  //always set culture to 'en-US'
             *  //we set culture of admin area to 'en-US' because current implementation of Telerik grid
             *  //doesn't work well in other cultures
             *  //e.g., editing decimal value in russian culture
             *  CommonHelper.SetTelerikCulture();
             * }
             * else
             * {
             *
             *  //public store
             *  var workContext = EngineContext.Current.Resolve<IWorkContext>();
             *  if (workContext.CurrentMember != null )
             *  {
             *      var culture = new CultureInfo(workContext.WorkingLanguage.LanguageCulture);
             *      Thread.CurrentThread.CurrentCulture = culture;
             *      Thread.CurrentThread.CurrentUICulture = culture;
             *  }
             * }*/
        }
        public virtual async Task <IActionResult> Index()
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            var installed = await _cacheManager.GetAsync <bool>("Installed");

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

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

            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", 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));
        }
Exemple #19
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

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

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            //only GET requests
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var customerSettings = EngineContext.Current.Resolve <CustomerSettings>();

            if (!customerSettings.StoreLastVisitedPage)
            {
                return;
            }

            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            var pageUrl   = webHelper.GetThisPageUrl(true);

            if (!String.IsNullOrEmpty(pageUrl))
            {
                var workContext     = EngineContext.Current.Resolve <IWorkContext>();
                var customerService = EngineContext.Current.Resolve <ICustomerService>();

                var previousPageUrl = workContext.CurrentCustomer.GetAttribute <string>(SystemCustomerAttributeNames.LastVisitedPage);
                if (!pageUrl.Equals(previousPageUrl))
                {
                    customerService.SaveCustomerAttribute(workContext.CurrentCustomer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl);
                }
            }
        }
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context, IWebHelper webHelper)
        {
            //whether database is installed
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                var installUrl = string.Format("{0}install", webHelper.GetStoreLocation());
                if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.OrdinalIgnoreCase))
                {
                    //redirect
                    context.Response.Redirect(installUrl);
                    return;
                }
            }

            //or call the next middleware in the request pipeline
            await _next(context);
        }
Exemple #21
0
 /// 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 (DataSettingsHelper.DatabaseIsInstalled())
     {
         var typeFinder    = new WebAppTypeFinder();
         var scheduleTasks = typeFinder.FindClassesOfType <IScheduleTask>();
         foreach (var task in scheduleTasks)
         {
             var assemblyName = task.Assembly.GetName().Name;
             services.AddSingleton <IHostedService, BackgroundServiceTask>(sp =>
             {
                 return(new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp));
             });
         }
     }
 }
        /// <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)
        {
            //check whether database is installed
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            //configure authentication
            application.UseGrandAuthentication();

            //set storecontext
            application.UseMiddleware <StoreContextMiddleware>();

            //set workcontext
            application.UseMiddleware <WorkContextMiddleware>();
        }
Exemple #23
0
        /// <summary>
        /// Add Progressive Web App
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddPWA(this IServiceCollection services)
        {
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            var config = services.BuildServiceProvider().GetRequiredService <GrandConfig>();

            if (config.EnableProgressiveWebApp)
            {
                var options = new WebEssentials.AspNetCore.Pwa.PwaOptions {
                    Strategy = (WebEssentials.AspNetCore.Pwa.ServiceWorkerStrategy)config.ServiceWorkerStrategy
                };
                services.AddProgressiveWebApp(options);
            }
        }
Exemple #24
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public void OnActionExecuting(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

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

                //only in GET requests
                if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

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

                //check whether we store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = _webHelper.GetThisPageUrl(true);

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

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

                //save new one if don't match
                if (!pageUrl.Equals(previousPageUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl);
                }
            }
Exemple #25
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 (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            var config = new GrandConfig();

            configuration.GetSection("Grand").Bind(config);
            if (config.EnableProgressiveWebApp)
            {
                var options = new WebEssentials.AspNetCore.Pwa.PwaOptions {
                    Strategy = (WebEssentials.AspNetCore.Pwa.ServiceWorkerStrategy)config.ServiceWorkerStrategy
                };
                services.AddProgressiveWebApp(options);
            }
        }
        /// <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 (!DataSettingsHelper.DatabaseIsInstalled())
            {
                return;
            }

            //add MiniProfiler services
            services.AddMiniProfiler(options => {
                var memoryCache = EngineContext.Current.Resolve <IMemoryCache>();
                options.Storage = new StackExchange.Profiling.Storage.MemoryCacheStorage(memoryCache, TimeSpan.FromMinutes(60));
                //determine who can access the MiniProfiler results
                options.ResultsAuthorize = request =>
                                           !EngineContext.Current.Resolve <StoreInformationSettings>().DisplayMiniProfilerInPublicStore ||
                                           EngineContext.Current.Resolve <IPermissionService>().Authorize(StandardPermissionProvider.AccessAdminPanel);
            });
        }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //ignore static resources
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();

            if (webHelper.IsStaticResource(this.Request))
            {
                return;
            }

            EnsureDatabaseIsInstalled();

            if (DataSettingsHelper.DatabaseIsInstalled() &&
                EngineContext.Current.Resolve <StoreInformationSettings>().DisplayMiniProfilerInPublicStore)
            {
                MiniProfiler.Start();
            }
        }
Exemple #28
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public void OnActionExecuting(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

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

                //only in GET requests
                if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

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

                //check whether we store IP addresses
                if (!_customerSettings.StoreIpAddresses)
                {
                    return;
                }

                //get current IP address
                var currentIpAddress = _webHelper.GetCurrentIpAddress();

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

                //update customer's IP address
                if (!currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress, StringComparison.InvariantCultureIgnoreCase))
                {
                    _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;
                    _customerService.UpdateCustomer(_workContext.CurrentCustomer);
                }
            }
Exemple #29
0
            /// <summary>
            /// Called early in the filter pipeline to confirm request is authorized
            /// </summary>
            /// <param name="filterContext">Authorization filter context</param>
            public void OnAuthorization(AuthorizationFilterContext filterContext)
            {
                if (filterContext == null)
                {
                    throw new ArgumentNullException("filterContext");
                }

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

                //only in GET requests, otherwise the browser might not propagate the verb and request body correctly.
                if (!HttpMethods.IsGet(filterContext.HttpContext.Request.Method))
                {
                    return;
                }

                //ignore this rule for localhost
                if (_webHelper.IsLocalRequest(filterContext.HttpContext.Request))
                {
                    return;
                }

                switch (_seoSettings.WwwRequirement)
                {
                case WwwRequirement.WithWww:
                    //redirect to URL with starting WWW
                    RedirectRequest(filterContext, true);
                    break;

                case WwwRequirement.WithoutWww:
                    //redirect to URL without starting WWW
                    RedirectRequest(filterContext, false);
                    break;

                case WwwRequirement.NoMatter:
                    //do nothing
                    break;

                default:
                    throw new GrandException("Not supported WwwRequirement parameter");
                }
            }
Exemple #30
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)
 {
     if (DataSettingsHelper.DatabaseIsInstalled())
     {
         var logger = EngineContext.Current.Resolve <ILogger>();
         //database is already installed, so start scheduled tasks
         try
         {
             JobManager.UseUtcTime();
             JobManager.JobException += info => logger.Fatal("An error just happened with a scheduled job: " + info.Exception);
             var scheduleTasks = ScheduleTaskManager.Instance.LoadScheduleTasks();       //load records from db to collection
             JobManager.Initialize(new RegistryGrandNode(scheduleTasks));                //init registry and start scheduled tasks
         }
         catch (Exception ex)
         {
             logger.Fatal("Application started error", ex, null);
         }
     }
 }