public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                UserSession userSession = GetUserSession(context);

                if (userSession != null)
                {
                    if (userSession.UserBasketId != 0 && !CookieExists(context, Constants.ShoppingCart))
                    {
                        CookieAdd(context, Constants.ShoppingCart,
                                  Encrypt(userSession.UserBasketId.ToString(), _shoppingCartService.GetEncryptionKey()), 180);
                    }

                    if (userSession.UserBasketId == 0 && CookieExists(context, Constants.ShoppingCart))
                    {
                        try
                        {
                            string basketCookie = Decrypt(CookieValue(context, Constants.ShoppingCart, String.Empty),
                                                          _shoppingCartService.GetEncryptionKey());

                            if (Int64.TryParse(basketCookie, out long result))
                            {
                                userSession.UserBasketId = result;
                            }
                            else
                            {
                                userSession.UserBasketId = 0;
                            }
                        }
                        catch (FormatException)
                        {
                            // problem decrypting the cookie so delete it
                            CookieDelete(context, Constants.ShoppingCart);
                        }
                    }

                    context.Items[Constants.BasketSummary]  = GetBasketSummary(userSession.UserBasketId);
                    context.Items[Constants.DefaultTaxRate] = _cartSettings.DefaultTaxRate;
                }
            }

            await _next(context);
        }
Ejemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                string fileExtension = RouteFileExtension(context);

                if (!String.IsNullOrEmpty(fileExtension) &&
                    StaticFileExtensions.Contains($"{fileExtension};"))
                {
                    await _next(context);

                    return;
                }

                string route = RouteLowered(context);

                if (route.Length > 1 && route[route.Length - 1] == Constants.ForwardSlashChar)
                {
                    route = route.Substring(0, route.Length - 1);
                }

                string    cacheName = $"Seo Cache {route}";
                CacheItem cacheItem = _memoryCache.GetCache().Get(cacheName);

                if (cacheItem == null)
                {
                    _seoProvider.GetSeoDataForRoute(route, out string title, out string description,
                                                    out string author, out List <string> tags);
                    cacheItem = new CacheItem(cacheName, new SeoCacheItem(title, description, author, tags));
                    _memoryCache.GetCache().Add(cacheName, cacheItem);
                }

                SeoCacheItem seoCache = (SeoCacheItem)cacheItem.Value;
                context.Items[SeoMetaAuthor]      = seoCache.Author;
                context.Items[SeoTitle]           = seoCache.Title;
                context.Items[SeoMetaDescription] = seoCache.Description;
                context.Items[SeoMetaKeywords]    = seoCache.Keywords;
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            string fileExtension = RouteFileExtension(context);

            if (!String.IsNullOrEmpty(fileExtension) && _staticFileExtensions.Contains($"{fileExtension};"))
            {
                await _next(context);

                return;
            }

            string route = RouteLowered(context);

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                bool validateFormInput = false;

                foreach (ManagedRoute restrictedRoute in _managedRoutes)
                {
                    if (restrictedRoute.ValidateFormFields && restrictedRoute.Route.StartsWith(route))
                    {
                        validateFormInput = true;
                        break;
                    }
                }

                ValidateRequestResult validateResult = _validateConnections.ValidateRequest(context.Request, validateFormInput, out int count);

                if (!validateResult.HasFlag(ValidateRequestResult.IpWhiteListed))
                {
                    if (validateResult.HasFlag(ValidateRequestResult.IpBlackListed))
                    {
                        context.Response.StatusCode = _badEggSettings.BannedResponseCode;
                        return;
                    }
                    else if (validateResult.HasFlag(ValidateRequestResult.TooManyRequests))
                    {
                        _notificationService.RaiseEvent(nameof(ValidateRequestResult.TooManyRequests), GetIpAddress(context));
                        context.Response.StatusCode = _badEggSettings.TooManyRequestResponseCode;
                        return;
                    }
                }
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                if (context.Items.TryGetValue(Constants.UserCulture, out object sessionCulture))
                {
                    SetUserCulture((string)sessionCulture);
                }
            }

            await _next(context);
        }
        public LocalizedString this[string name]
        {
            get
            {
                using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
                {
                    try
                    {
                        StringBuilder resourceName = new StringBuilder(name.Length);

                        // strip out any non alpha numeric characters
                        foreach (char c in name)
                        {
                            if (c >= 65 && c <= 90)
                            {
                                resourceName.Append(c);
                            }
                            else if (c >= 61 && c <= 122)
                            {
                                resourceName.Append(c);
                            }
                            else if (c >= 48 && c <= 57)
                            {
                                resourceName.Append(c);
                            }
                        }

                        string locString = _resourceManager.GetString(resourceName.ToString(),
                                                                      Thread.CurrentThread.CurrentUICulture);

                        if (String.IsNullOrEmpty(locString))
                        {
                            return(new LocalizedString(name, name));
                        }

                        return(new LocalizedString(name, locString));
                    }
                    catch (Exception error)
                    {
                        PluginInitialisation.GetLogger.AddToLog(LogLevel.Error, nameof(StringLocalizer), error, name);
                        return(new LocalizedString(name, name));
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (_disabled)
                {
                    return;
                }

                using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
                {
                    string routeLowered = RouteLowered(context);

                    using (TimedLock lck = TimedLock.Lock(_lockObject))
                    {
                        if (_ignoredRoutes.Contains(routeLowered))
                        {
                            return;
                        }
                    }

                    if (!context.Response.Headers.ContainsKey("Cache-Control"))
                    {
                        foreach (KeyValuePair <string, CacheControlRoute> keyValuePair in _routePaths)
                        {
                            if (routeLowered.StartsWith(keyValuePair.Key))
                            {
                                context.Response.Headers.Add("Cache-Control", $"max-age={keyValuePair.Value.CacheValue}");
                                return;
                            }
                        }
                    }

                    using (TimedLock lck = TimedLock.Lock(_lockObject))
                    {
                        _ignoredRoutes.Add(routeLowered);
                    }
                }
            }

            finally
            {
                await _next(context);
            }
        }
Ejemplo n.º 7
0
        public async Task Invoke(HttpContext context)
        {
            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_loginTimings))
            {
                UserSession userSession = GetUserSession(context);

                if (userSession != null && String.IsNullOrEmpty(userSession.UserName) &&
                    CookieExists(context, _loginControllerSettings.RememberMeCookieName))
                {
                    using (StopWatchTimer stopwatchAutoLogin = StopWatchTimer.Initialise(_autoLoginTimings))
                    {
                        string cookieValue = CookieValue(context, _loginControllerSettings.RememberMeCookieName,
                                                         _loginControllerSettings.EncryptionKey, String.Empty);

                        if (Int64.TryParse(cookieValue, out long userId))
                        {
                            UserLoginDetails loginDetails = new UserLoginDetails(userId, true);

                            LoginResult loginResult = _loginProvider.Login(String.Empty, String.Empty,
                                                                           base.GetIpAddress(context), 1, ref loginDetails);

                            if (loginResult == LoginResult.Remembered)
                            {
                                userSession.Login(userId, loginDetails.Username, loginDetails.Email);
                                await _authenticationService.SignInAsync(context,
                                                                         _loginControllerSettings.AuthenticationScheme,
                                                                         new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)),
                                                                         _claimsProvider.GetAuthenticationProperties());
                            }
                            else
                            {
                                CookieDelete(context, _loginControllerSettings.RememberMeCookieName);
                            }
                        }
                        else
                        {
                            CookieDelete(context, _loginControllerSettings.RememberMeCookieName);
                        }
                    }
                }
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                string route = RouteLowered(context);

                if (route.StartsWith("/sitemap"))
                {
                    Dictionary <string, string> sitemaps = GetSitemaps(context);

                    if (sitemaps.ContainsKey(route))
                    {
                        await context.Response.WriteAsync(sitemaps[route]);

                        context.Response.StatusCode = 200;
                        return;
                    }
                }
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            string fileExtension = RouteFileExtension(context);

            if (!_processStaticFiles && !String.IsNullOrEmpty(fileExtension) &&
                _staticFileExtensions.Contains($"{fileExtension};"))
            {
                await _next(context);

                return;
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                string route = RouteLowered(context);

                if (route.EndsWith("/robots.txt"))
                {
                    context.Response.StatusCode = 200;

                    // prepend sitemaps if there are any
                    object notificationResult = new object();

                    if (_notificationService.RaiseEvent(Constants.NotificationSitemapNames, context, null, ref notificationResult))
                    {
                        string[] sitemaps = ((System.Collections.IEnumerable)notificationResult)
                                            .Cast <object>()
                                            .Select(x => x.ToString())
                                            .ToArray();

                        if (sitemaps != null)
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            string        url           = GetHost(context);

                            for (int i = 0; i < sitemaps.Length; i++)
                            {
                                stringBuilder.Append($"Sitemap: {url}{sitemaps[i].Substring(1)}\r\n\r\n");
                            }

                            await context.Response.WriteAsync(stringBuilder.ToString());
                        }
                    }

                    context.Response.Body.Write(_spiderData, 0, _spiderData.Length);
                }
                else
                {
                    if (_userSessionManagerLoaded)
                    {
                        if (context.Items.ContainsKey(Constants.UserSession))
                        {
                            try
                            {
                                UserSession userSession = (UserSession)context.Items[Constants.UserSession];

                                foreach (DeniedRoute deniedRoute in _deniedSpiderRoutes)
                                {
                                    if (userSession.IsBot &&
                                        deniedRoute.Route.StartsWith(route) &&
                                        (
                                            deniedRoute.UserAgent == "*" ||
#if NET_CORE
                                            userSession.UserAgent.Contains(deniedRoute.UserAgent, StringComparison.CurrentCultureIgnoreCase)
#else
                                            userSession.UserAgent.ToLower().Contains(deniedRoute.UserAgent.ToLower())
#endif
                                        ))
                                    {
                                        context.Response.StatusCode = 403;
                                        return;
                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                _logger.AddToLog(LogLevel.Error, nameof(SpiderMiddleware), err, MethodBase.GetCurrentMethod().Name);
                            }
                        }
                    }
                }
            }

            await _next(context);
        }
        public async Task Invoke(HttpContext context)
        {
            string fileExtension = base.RouteFileExtension(context);

            // if it's a static file, don't add user session data to the context
            if (!String.IsNullOrEmpty(fileExtension) && _staticFileExtension.Contains($"{fileExtension};"))
            {
                await _next(context);

                return;
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                string        cookieSessionID;
                CookieOptions options = new CookieOptions()
                {
                    HttpOnly = false
                };

                if (context.Request.Cookies.ContainsKey(_cookieName))
                {
                    cookieSessionID = Shared.Utilities.Decrypt(context.Request.Cookies[_cookieName], _cookieEncryptionKey);
                    context.Response.Cookies.Append(_cookieName,
                                                    Shared.Utilities.Encrypt(cookieSessionID, _cookieEncryptionKey), options);
                }
                else
                {
                    cookieSessionID = GetNextID();
                    context.Response.Cookies.Append(_cookieName,
                                                    Shared.Utilities.Encrypt(cookieSessionID, _cookieEncryptionKey), options);
                }

                CacheItem   currentSession = UserSessionManager.UserSessions.Get(cookieSessionID);
                UserSession userSession;

                if (currentSession != null)
                {
                    userSession = (UserSession)currentSession.Value;
                }
                else
                {
                    userSession = GetUserSession(context, cookieSessionID);
                    GetSessionCulture(context, userSession);
                }

                string referrer = context.Request.Headers[Constants.PageReferer];
                userSession.PageView(GetAbsoluteUri(context).ToString(), referrer ?? String.Empty, false);

                context.Items.Add(Constants.UserSession, userSession);
                context.Items.Add(Constants.UserCulture, userSession.Culture);

                string route    = RouteLowered(context);
                bool   loggedIn = !String.IsNullOrEmpty(userSession.UserName);

                // is the route a loggedin/loggedout route
                RouteData partialMatch = null;

                foreach (RouteData routeData in _routeData)
                {
                    if (routeData.Matches(route))
                    {
                        if (routeData.Ignore)
                        {
                            partialMatch = null;
                        }
                        else
                        {
                            partialMatch = routeData;
                        }

                        break;
                    }

                    if (partialMatch == null && route.StartsWith(routeData.Route))
                    {
                        partialMatch = routeData;
                    }
                }

                // if we have a match check if we need to redirect
                if (partialMatch != null)
                {
                    if (!partialMatch.LoggedIn && loggedIn)
                    {
                        context.Response.Redirect(partialMatch.RedirectPath, false);
                        return;
                    }
                    else if (partialMatch.LoggedIn && !loggedIn)
                    {
                        context.Response.Redirect($"{partialMatch.RedirectPath}?returnUrl={context.Request.Path.ToString()}", false);
                        return;
                    }
                }
            }

            await _next(context);
        }
Ejemplo n.º 11
0
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (_settings.Enabled)
            {
                string route = RouteLowered(context);

                if (route.StartsWith("/smoketest/"))
                {
                    using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
                    {
                        if (route.Equals("/smoketest/siteid/"))
                        {
                            byte[] siteId = Encoding.UTF8.GetBytes(
                                Encrypt(String.Join(';', _settings.SiteId), _settings.EncryptionKey));
                            await context.Response.Body.WriteAsync(siteId, 0, siteId.Length);
                        }
                        else if (route.Equals("/smoketest/start/"))
                        {
                            ISmokeTestProvider smokeTestProvider = context.RequestServices
                                                                   .GetService(typeof(ISmokeTestProvider)) as ISmokeTestProvider;

                            if (smokeTestProvider != null)
                            {
                                NVPCodec codec = smokeTestProvider.SmokeTestStart();

                                if (codec != null)
                                {
                                    byte[] testNVPData = Encoding.UTF8.GetBytes(
                                        Encrypt(codec.Encode(), _settings.EncryptionKey));
                                    await context.Response.Body.WriteAsync(testNVPData, 0, testNVPData.Length);
                                }
                            }
                        }
                        else if (route.Equals("/smoketest/count/"))
                        {
                            byte[] siteId = Encoding.UTF8.GetBytes(
                                Encrypt(SmokeTests.Count.ToString(), _settings.EncryptionKey));
                            await context.Response.Body.WriteAsync(siteId, 0, siteId.Length);
                        }
                        else if (route.StartsWith("/smoketest/test"))
                        {
                            string testNumber = route.Substring(16);
                            List <WebSmokeTestItem> testItems = SmokeTests;

                            if (Int32.TryParse(testNumber, out int number) &&
                                number >= 0 &&
                                number < testItems.Count)
                            {
                                context.Response.ContentType = "application/json";
                                byte[] testData = Encoding.UTF8.GetBytes(
                                    Encrypt(JsonConvert.SerializeObject(testItems[number]), _settings.EncryptionKey));
                                await context.Response.Body.WriteAsync(testData, 0, testData.Length);
                            }
                            else
                            {
                                context.Response.StatusCode = 400;
                            }
                        }
                        else if (route.Equals("/smoketest/end/"))
                        {
                            ISmokeTestProvider smokeTestProvider = context.RequestServices
                                                                   .GetService(typeof(ISmokeTestProvider)) as ISmokeTestProvider;

                            if (smokeTestProvider != null)
                            {
                                smokeTestProvider.SmokeTestEnd();
                            }
                        }
                        else
                        {
                            context.Response.StatusCode = 404;
                        }

                        return;
                    }
                }
            }

            await _next(context);
        }
Ejemplo n.º 12
0
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string fileExtension = RouteFileExtension(context);

            if (!String.IsNullOrEmpty(fileExtension) &&
                _staticFileExtensions.Contains($"{fileExtension};"))
            {
                await _next(context);

                return;
            }

            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
            {
                string route = RouteLowered(context);

                if (route.Length > 1 && route[route.Length - 1] == Constants.ForwardSlashChar)
                {
                    route = route.Substring(0, route.Length - 1);
                }

                try
                {
                    bool found = false;

                    if (_breadcrumbRoutes.ContainsKey(route))
                    {
                        context.Items.Add(Constants.Breadcrumbs,
                                          GetBreadCrumbs(route, _breadcrumbRoutes[route].Breadcrumbs, String.Empty));
                        found = true;
                    }
                    else
                    {
                        foreach (KeyValuePair <string, BreadcrumbRoute> kvp in _breadcrumbRoutes)
                        {
                            if (route.StartsWith(kvp.Value.PartialRoute) && kvp.Value.HasParameters)
                            {
                                context.Items.Add(Constants.Breadcrumbs,
                                                  GetBreadCrumbs(route, kvp.Value.Breadcrumbs, Route(context).Substring(kvp.Value.PartialRoute.Length - 1)));
                                found = true;
                                break;
                            }
                        }
                    }

                    if (!found)
                    {
                        BreadcrumbItem homeBreadCrumb;

                        if (_stringLocalizer != null)
                        {
                            homeBreadCrumb = new BreadcrumbItem(_stringLocalizer[_homeBreadCrumb.Name], _homeBreadCrumb.Route, _homeBreadCrumb.HasParameters);
                        }
                        else
                        {
                            homeBreadCrumb = _homeBreadCrumb;
                        }

                        context.Items.Add(Constants.Breadcrumbs, new List <BreadcrumbItem>()
                        {
                            homeBreadCrumb
                        });
                    }
                }
                catch (Exception err)
                {
                    _logger.AddToLog(LogLevel.Error, nameof(BreadcrumbMiddleware), err, MethodBase.GetCurrentMethod().Name);
                }
            }

            await _next(context);
        }
Ejemplo n.º 13
0
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            bool passRequestOn = true;

            try
            {
                if (_disabled)
                {
                    return;
                }

                using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
                {
                    string route = RouteLowered(context);

                    string userIpAddress  = GetIpAddress(context);
                    bool   isLocalAddress = _localIpAddresses.Contains(userIpAddress);

#if !DEBUG
                    // always allow local connections
                    if (isLocalAddress)
                    {
                        return;
                    }
#endif

                    foreach (KeyValuePair <string, List <string> > restrictedRoute in _restrictedRoutes)
                    {
                        if (route.StartsWith(restrictedRoute.Key))
                        {
                            foreach (string restrictedIp in restrictedRoute.Value)
                            {
                                if ((isLocalAddress && restrictedIp == LocalHost) || (String.IsNullOrEmpty(restrictedIp)))
                                {
                                    return;
                                }

                                if (userIpAddress.StartsWith(restrictedIp))
                                {
                                    return;
                                }
                            }

                            // if we get here, we are in a restricted route and ip does not match, so fail with forbidden
                            passRequestOn = false;
                            context.Response.StatusCode = 403;
                            _logger.AddToLog(LogLevel.IpRestricted, String.Format(RouteForbidden, userIpAddress, route));
                        }
                    }
                }
            }
            finally
            {
                if (passRequestOn)
                {
                    await _next(context);
                }
            }
        }