Exemple #1
0
        private static void SetCookie(
            IQueue queue,
            string queueId,
            string originalUrl,
            int placeInQueue,
            RedirectType redirectType,
            string timeStamp,
            string hash,
            DateTime expirationTime)
        {
            var        key = GenerateKey(queue.CustomerId, queue.EventId);
            HttpCookie validationCookie = new HttpCookie(key);

            validationCookie.Values["QueueId"]      = queueId;
            validationCookie.Values["OriginalUrl"]  = HttpUtility.UrlEncode(originalUrl);
            validationCookie.Values["PlaceInQueue"] = Hashing.EncryptPlaceInQueue(placeInQueue);
            validationCookie.Values["RedirectType"] = redirectType.ToString();
            validationCookie.Values["TimeStamp"]    = timeStamp;
            validationCookie.Values["Hash"]         = hash;

            validationCookie.HttpOnly          = true;
            validationCookie.Domain            = CookieDomain;
            validationCookie.Expires           = expirationTime;
            validationCookie.Values["Expires"] = expirationTime.ToString("o");

            if (HttpContext.Current.Response.Cookies.AllKeys.Any(cookieKey => cookieKey == key))
            {
                HttpContext.Current.Response.Cookies.Remove(key);
            }
            HttpContext.Current.Response.Cookies.Add(validationCookie);
        }
 private string BuildRewriteName(
     RedirectType redirectType,
     int segments,
     bool oldUrlHasHost,
     string oldUrlHost,
     string oldUrlPath,
     string oldUrlQueryString,
     bool oldUrlHasRootRedirect,
     bool newUrlHasHost,
     string newUrlHost)
 {
     return(string.Format(
                "{0}{1} rewrite rule for {2}{3}{4}{5}",
                redirectType,
                redirectType == RedirectType.Replace && segments > 0
         ? string.Format(" {0} segment(s)", segments)
         : string.Empty,
                oldUrlHasRootRedirect ? "root url " : "urls ",
                oldUrlHasHost
         ? string.Format("from host '{0}'", oldUrlHost)
         : "from any host",
                !string.IsNullOrWhiteSpace(oldUrlQueryString)
         ? string.Format(
                    " with {0}query string", oldUrlHasRootRedirect ? string.Empty : string.Format("path '{0}' and ", oldUrlPath))
         : string.Empty,
                newUrlHasHost
         ? string.Format(" to host '{0}'", newUrlHost)
         : " to same host"));
 }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance based on the specified HTTP <paramref name="context"/> and <paramref name="redirect"/>.
 /// </summary>
 /// <param name="context">The HTTP context of the request.</param>
 /// <param name="redirect">The redirect indicating where the user should be redirected to.</param>
 /// <param name="redirectType">The redirect type.</param>
 /// <param name="destinationUrl">The destination URL.</param>
 public RedirectPostLookupNotification(HttpContext context, IRedirect redirect, RedirectType redirectType, string destinationUrl)
 {
     HttpContext    = context;
     Redirect       = redirect;
     RedirectType   = redirectType;
     DestinationUrl = destinationUrl;
 }
Exemple #4
0
        public static void RedirectToSignOutPage(RedirectType redirect = RedirectType.ResponseRedirectSoftCompleteRequest)
        {
            if (HttpContext.Current != null)
            {
                Uri serverUrl = new Uri(client_config.ServerUrl);
                Uri SignInUrl = new Uri(serverUrl, "SignOut");

                Uri ServiceUrl = HttpContext.Current.Request.Url;
                if (client_config.RequireSSL && !ServiceUrl.IsLoopback)
                {
                    if (!String.Equals(ServiceUrl.Scheme, Uri.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase))
                    {
                        UriBuilder b = new UriBuilder(ServiceUrl);
                        b.Scheme = Uri.UriSchemeHttps;
                        b.Port = -1;
                        ServiceUrl = b.Uri;
                    }
                }
                String EncodedServiceUrl = HttpUtility.UrlEncode(ServiceUrl.PathAndQuery);
                String FullRedirectUrl = SignInUrl.PathAndQuery + "?service=" + EncodedServiceUrl;
                switch (redirect)
                {
                    case RedirectType.ResponseRedirectHard:
                        HttpContext.Current.Response.Redirect(FullRedirectUrl);
                        break;
                    case RedirectType.ResponseRedirectSoft:
                        HttpContext.Current.Response.Redirect(FullRedirectUrl, false);
                        break;
                    case RedirectType.ResponseRedirectSoftCompleteRequest:
                        HttpContext.Current.Response.Redirect(FullRedirectUrl, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        break;
                }
            }
        }
        private string GenerateHash(
            string queueId,
            string originalUrl,
            string placeInQueue,
            RedirectType redirectType,
            string timestamp,
            DateTime expires,
            string fingerprint,
            string secretKey)
        {
            using (SHA256 sha2 = SHA256.Create())
            {
                string valueToHash = string.Concat(
                    queueId,
                    originalUrl,
                    placeInQueue,
                    redirectType.ToString(),
                    timestamp,
                    expires.ToString("o"),
                    secretKey,
                    fingerprint);
                byte[] hash = sha2.ComputeHash(Encoding.UTF8.GetBytes(valueToHash));

                return(BitConverter.ToString(hash));
            }
        }
 private string BuildRewriteKey(
     RedirectType redirectType,
     int segments,
     bool oldUrlHasHost,
     string oldUrlHost,
     string oldUrlPath,
     string oldUrlQueryString,
     bool oldUrlHasRootRedirect,
     bool newUrlHasHost,
     string newUrlHost)
 {
     return(string.Format(
                "{0}{1}OldUrlHasHost={2}{3}{4}{5}|NewUrlHasHost={6}{7}",
                redirectType,
                redirectType == RedirectType.Replace && segments > 0
         ? string.Format(",{0}Segments", segments)
         : string.Empty,
                oldUrlHasHost,
                oldUrlHasHost
         ? string.Format(",{0}", oldUrlHost.ToLower())
         : string.Empty,
                oldUrlHasRootRedirect ? ",/" : string.Empty,
                !string.IsNullOrWhiteSpace(oldUrlQueryString)
         ? string.Format(",{0}QueryString", oldUrlHasRootRedirect ? string.Empty : string.Concat(oldUrlPath, ","))
         : string.Empty,
                newUrlHasHost,
                newUrlHasHost
         ? string.Format(",{0}", newUrlHost.ToLower())
         : string.Empty));
 }
Exemple #7
0
        public void Md5KnownUser_Constructor_Test()
        {
            //Arrange
            Guid         expectedQueueId      = Guid.NewGuid();
            DateTime     expectedTimeStamp    = DateTime.UtcNow;
            int          expectedPlaceInQueue = 465;
            string       expectedCustomerId   = "somecust";
            string       expectedEventId      = "someevent";
            string       expectedOriginalUrl  = "http://google.com/";
            RedirectType expectedRedirectType = RedirectType.Safetynet;

            //Act
            Md5KnownUser knownUser = new Md5KnownUser(
                expectedQueueId,
                expectedPlaceInQueue,
                expectedTimeStamp,
                expectedCustomerId,
                expectedEventId,
                expectedRedirectType,
                expectedOriginalUrl);

            //Assert
            Assert.AreEqual(expectedQueueId, knownUser.QueueId);
            Assert.IsTrue(knownUser.PlaceInQueue.HasValue);
            Assert.AreEqual(expectedPlaceInQueue, knownUser.PlaceInQueue.Value);
            Assert.AreEqual(expectedTimeStamp, knownUser.TimeStamp);
            Assert.AreEqual(expectedCustomerId, knownUser.CustomerId);
            Assert.AreEqual(expectedEventId, knownUser.EventId);
            Assert.AreEqual(expectedRedirectType, knownUser.RedirectType);
            Assert.AreEqual(expectedOriginalUrl, knownUser.OriginalUrl);
        }
Exemple #8
0
        public static ActionResult CreateRedirectResult(Site site, FrontRequestChannel channel, string url, string rawUrl, int? statusCode, RedirectType redirectType)
        {
            var redirectUrl = url;
            if (!UrlUtility.IsAbsoluteUrl(redirectUrl))
            {
                redirectUrl = UrlUtility.ResolveUrl(redirectUrl);
                //WrapperUrl will cause endless loop if site host by ASP.NET development server when transfer redirect.
                if (redirectType != RedirectType.Transfer || Settings.IsHostByIIS)
                {
                    redirectUrl = FrontUrlHelper.WrapperUrl(redirectUrl, site, channel).ToString();
                }
            }
            if (!string.IsNullOrEmpty(rawUrl))
            {
                redirectUrl = redirectUrl.AddQueryParam("errorpath", rawUrl);
            }
            if (statusCode != null)
            {
                redirectUrl = redirectUrl.AddQueryParam("statusCode", statusCode.ToString());
            }

            switch (redirectType)
            {
                case RedirectType.Moved_Permanently_301:
                    return new Redirect301Result(redirectUrl);

                case RedirectType.Transfer:
                    return new TransferResult(redirectUrl, statusCode ?? 200);
                case RedirectType.Found_Redirect_302:
                default:
                    return new RedirectResult(redirectUrl);
            }
        }
        public void Should_only_apply_to_action_models_with_a_redirect(
            RedirectType type, string url, bool applies)
        {
            var requestGraph = RequestGraph.CreateFor <Handler>(x => x.RedirectModel());

            new RedirectWriter().AppliesTo(requestGraph
                                           .GetResponseWriterContext(new RedirectModel(type, url))).ShouldEqual(applies);
        }
 public void Create(UserRoleEnum role, int RedirectID, RedirectType type, string format, params string[] args)
 {
     var roleInt = (int)role;
     var users = db.Users.Where(u => (u.Role.RoleEnum & roleInt) == u.Role.RoleEnum).ToList();
     foreach (var u in users)
     {
         Create(u, RedirectID, type, format, args);
     }
 }
        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="location">Адрес назначения.</param>
        /// <param name="type">Тип перенаправления.</param>
        public RedirectHttpResponse(string location, RedirectType type = RedirectType.SeeOther)
        {
            Headers = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "Location", location }
            };

            StatusCode = (int)type;
        }
        /// <summary>
        /// Creates a variable of type AbstractFollowRedirect, add in the FollowRedirect list and return de variable.
        /// </summary>
        /// <param name="request">Session of request</param>
        /// <param name="rType">Redirect Type</param>
        /// <param name="page">Page of request</param>
        /// <param name="validations"></param>
        /// <returns>Returns the variable created</returns>
        internal AbstractFollowRedirect AddFollowRedirect(Session request, RedirectType rType, Page page, List <AbstractValidation> validations)
        {
            var redirect = new AbstractFollowRedirect(request, rType, page);

            redirect.Validations.AddRange(validations);
            FollowRedirects.Add(redirect);

            return(redirect);
        }
        public void CookieValidateResultRepository_GetValidationResult_ReadCookie_Test()
        {
            string secretKey = "acb";

            string       expectedCustomerId       = "CustomerId";
            string       expectedEventId          = "EventId";
            Guid         expectedQueueId          = new Guid(4567846, 35, 87, 3, 5, 8, 6, 4, 8, 2, 3);
            Uri          expectedOriginalUrl      = new Uri("http://original.url/");
            int          expectedPlaceInQueue     = 5486;
            RedirectType expectedRedirectType     = RedirectType.Queue;
            long         expectedSecondsSince1970 = 5465468;
            DateTime     expectedTimeStamp        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expectedSecondsSince1970);
            string       cookieName      = "QueueITAccepted-SDFrts345E-" + expectedCustomerId.ToLower() + "-" + expectedEventId.ToLower();
            DateTime     expectedExpires = DateTime.UtcNow.AddMinutes(2);
            string       expectedHash    = GenerateHash(
                expectedQueueId.ToString(),
                expectedOriginalUrl.AbsoluteUri,
                expectedPlaceInQueue.ToString(),
                expectedRedirectType,
                expectedSecondsSince1970.ToString(),
                expectedExpires,
                string.Empty,
                secretKey);

            this._queue.Stub(queue => queue.CustomerId).Return(expectedCustomerId);
            this._queue.Stub(queue => queue.EventId).Return(expectedEventId);

            HttpCookie cookie = new HttpCookie(cookieName);

            cookie.Values["QueueId"]      = expectedQueueId.ToString();
            cookie.Values["OriginalUrl"]  = expectedOriginalUrl.AbsoluteUri;
            cookie.Values["PlaceInQueue"] = Hashing.EncryptPlaceInQueue(expectedPlaceInQueue);
            cookie.Values["RedirectType"] = expectedRedirectType.ToString();
            cookie.Values["TimeStamp"]    = expectedSecondsSince1970.ToString();
            cookie.Values["Hash"]         = expectedHash;
            cookie.Values["Expires"]      = expectedExpires.ToString("o");
            cookie.HttpOnly = true;

            this._request.Cookies.Add(cookie);

            KnownUserFactory.Configure(secretKey);

            CookieValidateResultRepository repository = new CookieValidateResultRepository();

            AcceptedConfirmedResult actualResult = repository.GetValidationResult(this._queue) as AcceptedConfirmedResult;

            Assert.IsNotNull(actualResult);
            Assert.AreEqual(this._queue, actualResult.Queue);
            Assert.AreEqual(expectedCustomerId, actualResult.KnownUser.CustomerId);
            Assert.AreEqual(expectedEventId, actualResult.KnownUser.EventId);
            Assert.AreEqual(expectedQueueId, actualResult.KnownUser.QueueId);
            Assert.AreEqual(expectedOriginalUrl, actualResult.KnownUser.OriginalUrl);
            Assert.AreEqual(expectedPlaceInQueue, actualResult.KnownUser.PlaceInQueue);
            Assert.AreEqual(expectedRedirectType, actualResult.KnownUser.RedirectType);
            Assert.AreEqual(expectedTimeStamp, actualResult.KnownUser.TimeStamp);
        }
Exemple #14
0
 internal UriRedirectActionProperties(UriRedirectActionType actionType, RedirectType redirectType, DestinationProtocol?destinationProtocol, string customPath, string customHostname, string customQueryString, string customFragment)
 {
     ActionType          = actionType;
     RedirectType        = redirectType;
     DestinationProtocol = destinationProtocol;
     CustomPath          = customPath;
     CustomHostname      = customHostname;
     CustomQueryString   = customQueryString;
     CustomFragment      = customFragment;
 }
 internal UriRedirectActionDefinition(UriRedirectActionType typeDefinition, RedirectType redirectType, DestinationProtocol?destinationProtocol, string customPath, string customHostname, string customQueryString, string customFragment)
 {
     TypeDefinition      = typeDefinition;
     RedirectType        = redirectType;
     DestinationProtocol = destinationProtocol;
     CustomPath          = customPath;
     CustomHostname      = customHostname;
     CustomQueryString   = customQueryString;
     CustomFragment      = customFragment;
 }
 internal UrlRedirectActionParameters(UrlRedirectActionParametersTypeName typeName, RedirectType redirectType, DestinationProtocol?destinationProtocol, string customPath, string customHostname, string customQueryString, string customFragment)
 {
     TypeName            = typeName;
     RedirectType        = redirectType;
     DestinationProtocol = destinationProtocol;
     CustomPath          = customPath;
     CustomHostname      = customHostname;
     CustomQueryString   = customQueryString;
     CustomFragment      = customFragment;
 }
 public void Create(User user, int RedirectID, RedirectType type, string format, params string[] args)
 {
     var inbox = new Inbox
     {
         RedirectID = RedirectID,
         RedirectType = (int)type,
         Title = string.Format(format, args),
         User = user,
     };
     db.Inboxes.Add(inbox);
     db.SaveChanges();
 }
        public void should_correctly_prepare_redirect_type(RedirectType type, string expected)
        {
            var dto = new ZoneRedirectRequest
            {
                Name                = Name,
                RedirectType        = type,
                RedirectTo          = RedirectTo,
                RedirectQueryString = RedirectQueryString
            };

            var json = dto.Prepare();

            json.ShouldContain(expected);
        }
Exemple #19
0
 private void VerifyRedirect(
     string oldUrl,
     string newUrl,
     bool oldUrlHasHost,
     bool newUrlHasHost,
     string parsedOldUrl,
     string parsedNewUrl,
     string originalOldUrl,
     string originalNewUrl,
     bool originalOldUrlHasHost,
     bool originalNewUrlHasHost,
     RedirectType redirectType,
     IRedirect redirect)
 {
     Assert.AreEqual(
         oldUrl,
         redirect.OldUrl);
     Assert.AreEqual(
         newUrl,
         redirect.NewUrl);
     Assert.AreEqual(
         oldUrlHasHost,
         redirect.OldUrlHasHost);
     Assert.AreEqual(
         newUrlHasHost,
         redirect.NewUrlHasHost);
     Assert.AreEqual(
         parsedOldUrl,
         redirect.ParsedOldUrl);
     Assert.AreEqual(
         parsedNewUrl,
         redirect.ParsedNewUrl);
     Assert.AreEqual(
         originalOldUrl,
         redirect.OriginalOldUrl);
     Assert.AreEqual(
         originalNewUrl,
         redirect.OriginalNewUrl);
     Assert.AreEqual(
         originalOldUrlHasHost,
         redirect.OriginalOldUrlHasHost);
     Assert.AreEqual(
         originalNewUrlHasHost,
         redirect.OriginalNewUrlHasHost);
     Assert.AreEqual(
         redirectType,
         redirect.RedirectType);
 }
        public void CookieValidateResultRepository_SetValidationResult_WriteCookie_Hash_Test()
        {
            string secretKey = "acb";

            string       expectedCustomerId       = "CustomerId";
            string       expectedEventId          = "EventId";
            Guid         expectedQueueId          = Guid.Empty;
            string       expectedOriginalUrl      = "http://original.url/";
            int          expectedPlaceInQueue     = 0;
            RedirectType expectedRedirectType     = RedirectType.Idle;
            long         expectedSecondsSince1970 = 0;
            DateTime     expectedTimeStamp        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expectedSecondsSince1970);
            string       expectedCookieName       = "QueueITAccepted-SDFrts345E-" + expectedCustomerId.ToLower() + "-" + expectedEventId.ToLower();
            DateTime     expectedExpires          = DateTime.UtcNow.AddMinutes(2);
            string       expectedHash             = GenerateHash(
                expectedQueueId.ToString(),
                expectedOriginalUrl,
                expectedPlaceInQueue.ToString(),
                expectedRedirectType,
                expectedSecondsSince1970.ToString(),
                expectedExpires,
                string.Empty,
                secretKey);

            this._knownUser.Stub(knownUser => knownUser.CustomerId).Return(expectedCustomerId);
            this._knownUser.Stub(knownUser => knownUser.EventId).Return(expectedEventId);
            this._knownUser.Stub(knownUser => knownUser.QueueId).Return(expectedQueueId);
            this._knownUser.Stub(knownUser => knownUser.OriginalUrl).Return(expectedOriginalUrl);
            this._knownUser.Stub(knownUser => knownUser.PlaceInQueue).Return(expectedPlaceInQueue);
            this._knownUser.Stub(knownUser => knownUser.RedirectType).Return(expectedRedirectType);
            this._knownUser.Stub(knownUser => knownUser.TimeStamp).Return(expectedTimeStamp);

            this._queue.Stub(queue => queue.CustomerId).Return(expectedCustomerId);
            this._queue.Stub(queue => queue.EventId).Return(expectedEventId);

            CookieValidateResultRepository.Configure(null);
            KnownUserFactory.Configure(secretKey);

            CookieValidateResultRepository repository = new CookieValidateResultRepository();

            AcceptedConfirmedResult result = new AcceptedConfirmedResult(this._queue, this._knownUser, true);

            repository.SetValidationResult(this._queue, result, expectedExpires);

            Assert.AreEqual(1, this._response.Cookies.Count);
            Assert.AreEqual(expectedCookieName, this._response.Cookies[0].Name);
            Assert.AreEqual(expectedHash, this._response.Cookies[0]["Hash"]);
        }
Exemple #21
0
        public bool Map(Site site, string inputUrl, out string outputUrl, out RedirectType redirectType)
        {
            outputUrl    = string.Empty;
            redirectType = RedirectType.Found_Redirect_302;
            if (string.IsNullOrEmpty(inputUrl))
            {
                return(false);
            }
            var mapSettings = Kooboo.CMS.Sites.Services.ServiceFactory.UrlRedirectManager.All(site, "");

            //inputUrl = inputUrl.Trim('/');
            if (!inputUrl.StartsWith("/"))
            {
                inputUrl = "/" + inputUrl;
            }
            foreach (var setting in mapSettings)
            {
                var inputPattern = setting.InputUrl;//.Trim('/');

                if (setting.Regex)
                {
                    try
                    {
                        if (Regex.IsMatch(inputUrl, inputPattern, RegexOptions.IgnoreCase))
                        {
                            outputUrl    = wrapOutputUrl(Regex.Replace(inputUrl, inputPattern, setting.OutputUrl, RegexOptions.IgnoreCase));
                            redirectType = setting.RedirectType;
                            return(true);
                        }
                    }
                    catch (Exception e)
                    {
                        Kooboo.HealthMonitoring.Log.LogException(e);
                    }
                }
                else
                {
                    if (inputUrl.EqualsOrNullEmpty(inputPattern, StringComparison.CurrentCultureIgnoreCase))
                    {
                        outputUrl    = wrapOutputUrl(setting.OutputUrl);
                        redirectType = setting.RedirectType;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #22
0
        public bool Map(Site site, string inputUrl, out string outputUrl, out RedirectType redirectType)
        {
            outputUrl = string.Empty;
            redirectType = RedirectType.Found_Redirect_302;
            if (string.IsNullOrEmpty(inputUrl))
            {
                return false;
            }
            var mapSettings = Kooboo.CMS.Sites.Services.ServiceFactory.UrlRedirectManager.All(site, "");
            //inputUrl = inputUrl.Trim('/');
            if (!inputUrl.StartsWith("/"))
            {
                inputUrl = "/" + inputUrl;
            }
            foreach (var setting in mapSettings)
            {
                var inputPattern = setting.InputUrl;//.Trim('/');

                if (setting.Regex)
                {
                    try
                    {
                        if (Regex.IsMatch(inputUrl, inputPattern, RegexOptions.IgnoreCase))
                        {
                            outputUrl = wrapOutputUrl(Regex.Replace(inputUrl, inputPattern, setting.OutputUrl, RegexOptions.IgnoreCase));
                            redirectType = setting.RedirectType;
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        Kooboo.HealthMonitoring.Log.LogException(e);
                    }

                }
                else
                {
                    if (inputUrl.EqualsOrNullEmpty(inputPattern, StringComparison.CurrentCultureIgnoreCase))
                    {
                        outputUrl = wrapOutputUrl(setting.OutputUrl);
                        redirectType = setting.RedirectType;
                        return true;
                    }
                }
            }
            return false;
        }
Exemple #23
0
 internal Md5KnownUser(
     Guid queueId,
     int?placeInQueue,
     DateTime timeStamp,
     string customerId,
     string eventId,
     RedirectType redirectType,
     string originalUrl)
 {
     this.QueueId      = queueId;
     this.PlaceInQueue = placeInQueue;
     this.TimeStamp    = timeStamp;
     this.CustomerId   = customerId;
     this.EventId      = eventId;
     this.OriginalUrl  = originalUrl;
     this.RedirectType = redirectType;
 }
 internal Md5KnownUser(
     Guid queueId, 
     int? placeInQueue, 
     DateTime timeStamp, 
     string customerId, 
     string eventId, 
     RedirectType redirectType, 
     string originalUrl)
 {
     this.QueueId = queueId;
     this.PlaceInQueue = placeInQueue;
     this.TimeStamp = timeStamp;
     this.CustomerId = customerId;
     this.EventId = eventId;
     this.OriginalUrl = originalUrl;
     this.RedirectType = redirectType;
 }
 public static RedirectRule NewFromSystem(string oldPattern, int contentId, RedirectType redirectType,
                                          RedirectRuleType redirectRuleType, string notes)
 {
     return(new RedirectRule
     {
         RedirectOrigin = RedirectOrigin.System,
         OldPattern = oldPattern,
         ContentId = contentId,
         RedirectType = redirectType,
         RedirectRuleType = redirectRuleType,
         IsActive = true,
         CreatedBy = PrincipalInfo.CurrentPrincipal.Identity.Name,
         CreatedOn = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc),
         Notes = notes,
         Priority = Settings.SystemRedirectRulePriority
     });
 }
 public static RedirectRule NewFromImport(string oldPattern, int contentId, RedirectType redirectType,
                                          RedirectRuleType redirectRuleType, bool isActive, string notes, int?priority)
 {
     return(new RedirectRule
     {
         RedirectOrigin = RedirectOrigin.Import,
         OldPattern = UrlPath.ExtractRelativePath(oldPattern),
         ContentId = contentId,
         RedirectType = redirectType,
         RedirectRuleType = redirectRuleType,
         IsActive = isActive,
         CreatedOn = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc),
         CreatedBy = PrincipalInfo.CurrentPrincipal.Identity.Name,
         Notes = notes,
         Priority = priority ?? Settings.DefaultRedirectRulePriority
     });
 }
        public void CookieValidateResultRepository_SetValidationResult_WriteCookie_Test()
        {
            string secretKey = "acb";

            string       expectedCustomerId       = "CustomerId";
            string       expectedEventId          = "EventId";
            Guid         expectedQueueId          = new Guid(4567846, 35, 87, 3, 5, 8, 6, 4, 8, 2, 3);
            string       expectedOriginalUrl      = "http://original.url/";
            int          expectedPlaceInQueue     = 5486;
            RedirectType expectedRedirectType     = RedirectType.Queue;
            long         expectedSecondsSince1970 = 5465468;
            DateTime     expectedTimeStamp        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expectedSecondsSince1970);
            string       expectedCookieName       = "QueueITAccepted-SDFrts345E-" + expectedCustomerId.ToLower() + "-" + expectedEventId.ToLower();

            this._knownUser.Stub(knownUser => knownUser.CustomerId).Return(expectedCustomerId);
            this._knownUser.Stub(knownUser => knownUser.EventId).Return(expectedEventId);
            this._knownUser.Stub(knownUser => knownUser.QueueId).Return(expectedQueueId);
            this._knownUser.Stub(knownUser => knownUser.OriginalUrl).Return(expectedOriginalUrl);
            this._knownUser.Stub(knownUser => knownUser.PlaceInQueue).Return(expectedPlaceInQueue);
            this._knownUser.Stub(knownUser => knownUser.RedirectType).Return(expectedRedirectType);
            this._knownUser.Stub(knownUser => knownUser.TimeStamp).Return(expectedTimeStamp);

            this._queue.Stub(queue => queue.CustomerId).Return(expectedCustomerId);
            this._queue.Stub(queue => queue.EventId).Return(expectedEventId);

            CookieValidateResultRepository.Configure(null);
            KnownUserFactory.Configure(secretKey);

            CookieValidateResultRepository repository = new CookieValidateResultRepository();

            AcceptedConfirmedResult result = new AcceptedConfirmedResult(this._queue, this._knownUser, true);

            repository.SetValidationResult(this._queue, result);

            Assert.AreEqual(1, this._response.Cookies.Count);
            Assert.AreEqual(expectedCookieName, this._response.Cookies[0].Name);
            Assert.IsNull(this._response.Cookies[0].Domain);
            Assert.IsTrue(this._response.Cookies[0].HttpOnly);
            Assert.IsTrue(this._response.Cookies[0].Expires > DateTime.UtcNow.AddMinutes(19).AddSeconds(50));
            Assert.IsTrue(this._response.Cookies[0].Expires < DateTime.UtcNow.AddMinutes(20).AddSeconds(10));
            Assert.AreEqual(expectedQueueId.ToString(), this._response.Cookies[0]["QueueId"]);
            Assert.AreEqual(expectedSecondsSince1970.ToString(), this._response.Cookies[0]["TimeStamp"]);
            Assert.AreEqual(expectedRedirectType.ToString(), this._response.Cookies[0]["RedirectType"]);
            Assert.AreEqual(expectedPlaceInQueue, Hashing.DecryptPlaceInQueue(this._response.Cookies[0]["PlaceInQueue"]));
        }
Exemple #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedirectResponse"/> class.
 /// </summary>
 /// <param name="location">Location to redirect to</param>
 /// <param name="type">Type of redirection to perform</param>
 public RedirectResponse(string location, RedirectType type = RedirectType.SeeOther)
 {
     this.Headers.Add("Location", location);
     this.Contents = GetStringContents(string.Empty);
     this.ContentType = "text/html";
     switch (type)
     {
         case RedirectType.Permanent:
             this.StatusCode = HttpStatusCode.MovedPermanently;
             break;
         case RedirectType.Temporary:
             this.StatusCode = HttpStatusCode.TemporaryRedirect;
             break;
         default:
             this.StatusCode = HttpStatusCode.SeeOther;
             break;
     }
 }
Exemple #29
0
        public IEnumerable <IRedirect> ReadAllRedirects()
        {
            if (_csvReader.Read())
            {
                _csvReader.ReadHeader();
            }

            while (_csvReader.Read())
            {
                var redirectType = _csvReader.GetField <string>("redirecttype");

                RedirectType parsedRedirectType = _configuration.DefaultRedirectType;
                if (!string.IsNullOrWhiteSpace(redirectType) &&
                    !Enum.TryParse(redirectType, out parsedRedirectType))
                {
                    parsedRedirectType = _configuration.DefaultRedirectType;
                }

                yield return(new Redirect
                {
                    OldUrl = TrimWhitespace(
                        _csvReader.GetField <string>("oldurl")),
                    NewUrl = TrimWhitespace(
                        _csvReader.GetField <string>("newurl")),
                    OldUrlHasHost =
                        _csvReader.GetField <bool>("oldurlhashost"),
                    NewUrlHasHost =
                        _csvReader.GetField <bool>("newurlhashost"),
                    ParsedOldUrl = TrimWhitespace(
                        _csvReader.GetField <string>("parsedoldurl")),
                    ParsedNewUrl = TrimWhitespace(
                        _csvReader.GetField <string>("parsednewurl")),
                    OriginalOldUrl = TrimWhitespace(
                        _csvReader.GetField <string>("originaloldurl")),
                    OriginalNewUrl = TrimWhitespace(
                        _csvReader.GetField <string>("originalnewurl")),
                    OriginalOldUrlHasHost =
                        _csvReader.GetField <bool>("oldurlhashost"),
                    OriginalNewUrlHasHost =
                        _csvReader.GetField <bool>("newurlhashost"),
                    RedirectType = parsedRedirectType
                });
            }
        }
        private static void RunVerifyMd5HashTest(
            bool configLoaded,
            string sharedSecreteEventKey = null,
            string prefix             = null,
            string redirectTypeString = null,
            RedirectType redirectType = RedirectType.Unknown)
        {
            //Arrange
            int      expectedPlaceInqueue  = 7810;
            Guid     expectedQueueId       = Guid.NewGuid();
            string   placeInQueueEncrypted = Hashing.EncryptPlaceInQueue(expectedPlaceInqueue);
            long     unixTimestamp         = Hashing.GetTimestamp();
            DateTime expectedTimeStamp     = Hashing.TimestampToDateTime(unixTimestamp);
            string   expectedCustomerId    = "somecust";
            string   expectedEventId       = "someevent";

            string urlNoHash = "http://q.queue-it.net/inqueue.aspx?" + prefix + "c=somecust&" + prefix + "e=someevent&" + prefix + "q=" + expectedQueueId +
                               "&" + prefix + "p=" + placeInQueueEncrypted + "&" + prefix + "ts=" + unixTimestamp + "&" + prefix + "rt=" + redirectTypeString + "&" + prefix + "h=";
            Uri hashUri = new Uri(urlNoHash);

            string hash        = Hashing.GenerateMD5Hash(hashUri.AbsoluteUri, SharedSecreteEventKey);
            string querystring = prefix + "c=somecust&" + prefix + "e=someevent&" + prefix + "q=" + expectedQueueId +
                                 "&" + prefix + "p=" + placeInQueueEncrypted + "&" + prefix + "ts=" + unixTimestamp + "&" + prefix + "rt=" + redirectTypeString + "&" + prefix + "h=" + hash;
            string url = urlNoHash + hash;

            HttpRequest httpRequest = new HttpRequest("inqueue.aspx", url, querystring);

            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(null));

            //Act
            IKnownUser knownUser = KnownUserFactory.VerifyMd5Hash(
                configLoaded ? sharedSecreteEventKey : SharedSecreteEventKey,
                querystringPrefix: configLoaded ? null : prefix);

            //Assert
            Assert.IsNotNull(knownUser);
            Assert.AreEqual(expectedQueueId, knownUser.QueueId);
            Assert.IsTrue(knownUser.PlaceInQueue.HasValue);
            Assert.AreEqual(expectedPlaceInqueue, knownUser.PlaceInQueue);
            Assert.AreEqual(expectedTimeStamp, knownUser.TimeStamp);
            Assert.AreEqual(expectedCustomerId, knownUser.CustomerId);
            Assert.AreEqual(redirectType, knownUser.RedirectType);
            Assert.AreEqual(expectedEventId, knownUser.EventId);
        }
        private static void RunVerifyMd5HashTest(
            bool configLoaded, 
            string sharedSecreteEventKey = null, 
            string prefix = null, 
            string redirectTypeString = null,
            RedirectType redirectType = RedirectType.Unknown)
        {
            //Arrange
            int expectedPlaceInqueue = 7810;
            Guid expectedQueueId = Guid.NewGuid();
            string placeInQueueEncrypted = Hashing.EncryptPlaceInQueue(expectedPlaceInqueue);
            long unixTimestamp = Hashing.GetTimestamp();
            DateTime expectedTimeStamp = Hashing.TimestampToDateTime(unixTimestamp);
            string expectedCustomerId = "somecust";
            string expectedEventId = "someevent";

            string urlNoHash = "http://q.queue-it.net/inqueue.aspx?" + prefix + "c=somecust&" + prefix + "e=someevent&" + prefix + "q=" + expectedQueueId +
                "&" + prefix + "p=" + placeInQueueEncrypted + "&" + prefix + "ts=" + unixTimestamp + "&" + prefix + "rt=" + redirectTypeString + "&" + prefix + "h=";
            Uri hashUri = new Uri(urlNoHash);

            string hash = Hashing.GenerateMD5Hash(hashUri.AbsoluteUri, SharedSecreteEventKey);
            string querystring = prefix + "c=somecust&" + prefix + "e=someevent&" + prefix + "q=" + expectedQueueId +
                "&" + prefix + "p=" + placeInQueueEncrypted + "&" + prefix + "ts=" + unixTimestamp + "&" + prefix + "rt=" + redirectTypeString + "&" + prefix + "h=" + hash;
            string url = urlNoHash + hash;

            HttpRequest httpRequest = new HttpRequest("inqueue.aspx", url, querystring);
            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(null));

            //Act
            IKnownUser knownUser = KnownUserFactory.VerifyMd5Hash(
                configLoaded ? sharedSecreteEventKey : SharedSecreteEventKey, 
                querystringPrefix: configLoaded ? null : prefix);

            //Assert  
            Assert.IsNotNull(knownUser);
            Assert.AreEqual(expectedQueueId, knownUser.QueueId);
            Assert.IsTrue(knownUser.PlaceInQueue.HasValue);
            Assert.AreEqual(expectedPlaceInqueue, knownUser.PlaceInQueue);
            Assert.AreEqual(expectedTimeStamp, knownUser.TimeStamp);
            Assert.AreEqual(expectedCustomerId, knownUser.CustomerId);
            Assert.AreEqual(redirectType, knownUser.RedirectType);
            Assert.AreEqual(expectedEventId, knownUser.EventId);
        }
Exemple #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedirectResponse"/> class, with
        /// the provided <paramref name="location"/> and <paramref name="type"/>.
        /// </summary>
        /// <param name="location">Location to redirect to</param>
        /// <param name="type">Type of redirection to perform</param>
        public RedirectResponse(string location, RedirectType type = RedirectType.SeeOther)
        {
            this.Headers.Add("Location", location);
            this.Contents    = GetStringContents(string.Empty);
            this.ContentType = "text/html";
            switch (type)
            {
            case RedirectType.Permanent:
                this.StatusCode = HttpStatusCode.MovedPermanently;
                break;

            case RedirectType.Temporary:
                this.StatusCode = HttpStatusCode.TemporaryRedirect;
                break;

            default:
                this.StatusCode = HttpStatusCode.SeeOther;
                break;
            }
        }
    public void should_propagate_unit_tag([Values(null, "tag")] string tag)
    {
        var expected = new MemoryStream();

        // --arrange
        var buildSession = A.Fake <IBuildSession>();

        A.CallTo(() => buildSession.BuildChain).Returns(Unit.IsType <IDisposable>().Tag(tag).ToBuildChain());
        var buildUnitCall = A.CallTo(() => buildSession.BuildUnit(Unit.IsType <MemoryStream>().Tag(tag)));

        buildUnitCall.Returns(expected.ToBuildResult());

        var target = new RedirectType(typeof(MemoryStream), SpecialTag.Propagate);

        // --act
        target.Process(buildSession);

        // --assert
        buildSession.BuildResult.Value.Should().Be(expected);
        buildUnitCall.MustHaveHappenedOnceAndOnly();
    }
Exemple #34
0
        public async Task <ZoneRedirect> CreateRedirectAsync(int zoneId, string name,
                                                             string redirectTo, RedirectType type, bool redirectQueryString, string iframeTitle = null)
        {
            var requestDto = new ZoneRedirectRequest
            {
                IframeTitle         = iframeTitle,
                Name                = name,
                RedirectQueryString = redirectQueryString,
                RedirectTo          = redirectTo,
                RedirectType        = type
            };

            var response = await _client.Post($"{BaseUrl}/{zoneId}/redirects", requestDto.Prepare());

            ErrorHandler(response.StatusCode);

            var content = await response.Content.ReadAsStringAsync();

            var responseDto = JsonConvert.DeserializeObject <ZoneRedirectResponse>(content);

            return(responseDto.Extract());
        }
Exemple #35
0
        public override void SetValidationResult(IQueue queue, IValidateResult validationResult, DateTime?expirationTime = null)
        {
            AcceptedConfirmedResult acceptedResult = validationResult as AcceptedConfirmedResult;

            if (acceptedResult != null)
            {
                string       queueId      = acceptedResult.KnownUser.QueueId.ToString();
                string       originalUrl  = acceptedResult.KnownUser.OriginalUrl;
                int          placeInQueue = acceptedResult.KnownUser.PlaceInQueue.HasValue ? acceptedResult.KnownUser.PlaceInQueue.Value : 0;
                RedirectType redirectType = acceptedResult.KnownUser.RedirectType;
                string       timeStamp    = Hashing.GetTimestamp(acceptedResult.KnownUser.TimeStamp).ToString();

                if (!expirationTime.HasValue)
                {
                    expirationTime = DateTime.UtcNow.Add(redirectType == RedirectType.Idle ? IdleExpiration : CookieExpiration);
                }

                string hash = GenerateHash(queueId, originalUrl, placeInQueue.ToString(), redirectType, timeStamp, expirationTime.Value);

                SetCookie(queue, queueId, originalUrl, placeInQueue, redirectType, timeStamp, hash, expirationTime.Value);
            }
        }
        public void CookieValidateResultRepository_GetValidationResult_ModifiedCookie_Test()
        {
            string secretKey = "acb";

            string       expectedCustomerId       = "CustomerId";
            string       expectedEventId          = "EventId";
            Guid         expectedQueueId          = new Guid(4567846, 35, 87, 3, 5, 8, 6, 4, 8, 2, 3);
            Uri          expectedOriginalUrl      = new Uri("http://original.url/");
            int          expectedPlaceInQueue     = 5486;
            RedirectType expectedRedirectType     = RedirectType.Queue;
            long         expectedSecondsSince1970 = 5465468;
            DateTime     expectedTimeStamp        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expectedSecondsSince1970);
            string       cookieName   = "QueueITAccepted-SDFrts345E-" + expectedCustomerId.ToLower() + "-" + expectedEventId.ToLower();
            string       expectedHash = "D5-48-23-FE-D0-42-D0-59-88-39-AB-D0-CA-A0-18-5D-B8-21-2C-A7-62-A9-65-73-62-68-74-C5-1C-50-09-BA";

            this._queue.Stub(queue => queue.CustomerId).Return(expectedCustomerId);
            this._queue.Stub(queue => queue.EventId).Return(expectedEventId);

            HttpCookie cookie = new HttpCookie(cookieName);

            cookie.Values["QueueId"]      = expectedQueueId.ToString();
            cookie.Values["OriginalUrl"]  = expectedOriginalUrl.AbsoluteUri;
            cookie.Values["PlaceInQueue"] = Hashing.EncryptPlaceInQueue(expectedPlaceInQueue - 10);
            cookie.Values["RedirectType"] = expectedRedirectType.ToString();
            cookie.Values["TimeStamp"]    = expectedSecondsSince1970.ToString();
            cookie.Values["Hash"]         = expectedHash;

            this._request.Cookies.Add(cookie);

            KnownUserFactory.Configure(secretKey);

            CookieValidateResultRepository repository = new CookieValidateResultRepository();

            AcceptedConfirmedResult actualResult = repository.GetValidationResult(this._queue) as AcceptedConfirmedResult;

            Assert.IsNull(actualResult);
        }
 // Creates a rule with appropriate default values of the url rewrite rule.
 private IISUrlRewriteRule CreateTestRule(ConditionCollection conditions,
                                          string name  = "",
                                          bool enabled = true,
                                          PatternSyntax patternSyntax = PatternSyntax.ECMAScript,
                                          bool stopProcessing         = false,
                                          string url                = "",
                                          bool ignoreCase           = true,
                                          bool negate               = false,
                                          ActionType actionType     = ActionType.None,
                                          string pattern            = "",
                                          bool appendQueryString    = false,
                                          bool rewrittenUrl         = false,
                                          bool global               = false,
                                          UriMatchPart uriMatchPart = UriMatchPart.Path,
                                          RedirectType redirectType = RedirectType.Permanent
                                          )
 {
     return(new IISUrlRewriteRule(
                name,
                new RegexMatch(new Regex("^OFF$"), negate),
                conditions,
                new RewriteAction(RuleResult.ContinueRules, new InputParser().ParseInputString(url, uriMatchPart), queryStringAppend: false),
                global));
 }
        public void CookieValidateResultRepository_GetValidationResult_IdleQueue_NoRenewCookie_Test()
        {
            string secretKey = "acb";

            string       expectedCustomerId       = "CustomerId";
            string       expectedEventId          = "EventId";
            Guid         expectedQueueId          = Guid.Empty;
            Uri          expectedOriginalUrl      = new Uri("http://original.url/");
            int          expectedPlaceInQueue     = 0;
            RedirectType expectedRedirectType     = RedirectType.Idle;
            long         expectedSecondsSince1970 = 0;
            string       cookieName   = "QueueITAccepted-SDFrts345E-" + expectedCustomerId.ToLower() + "-" + expectedEventId.ToLower();
            string       expectedHash = "17-77-3F-7D-2E-10-B1-F0-9B-41-5A-DD-37-BB-8E-3A-F7-0B-F2-9F-E3-3B-2B-F5-83-CE-88-C5-8C-15-26-B4";

            this._queue.Stub(queue => queue.CustomerId).Return(expectedCustomerId);
            this._queue.Stub(queue => queue.EventId).Return(expectedEventId);

            HttpCookie cookie = new HttpCookie(cookieName);

            cookie.Values["QueueId"]      = expectedQueueId.ToString();
            cookie.Values["OriginalUrl"]  = expectedOriginalUrl.AbsoluteUri;
            cookie.Values["PlaceInQueue"] = Hashing.EncryptPlaceInQueue(expectedPlaceInQueue);
            cookie.Values["RedirectType"] = expectedRedirectType.ToString();
            cookie.Values["TimeStamp"]    = expectedSecondsSince1970.ToString();
            cookie.Values["Hash"]         = expectedHash;

            this._request.Cookies.Add(cookie);

            KnownUserFactory.Configure(secretKey);

            CookieValidateResultRepository repository = new CookieValidateResultRepository();

            repository.GetValidationResult(this._queue);

            Assert.AreEqual(0, this._response.Cookies.Count);
        }
 public void Create(int userID, int RedirectID, RedirectType type, string format, params string[] args)
 {
     var user = db.Users.Single(u => u.ID == userID);
     Create(user, RedirectID, type, format, args);
 }
        private static void SetCookie(
            IQueue queue, 
            string queueId, 
            string originalUrl, 
            int placeInQueue, 
            RedirectType redirectType,
            string timeStamp, 
            string hash,
            DateTime expirationTime)
        {
            var key = GenerateKey(queue.CustomerId, queue.EventId);
            HttpCookie validationCookie = new HttpCookie(key);
            validationCookie.Values["QueueId"] = queueId;
            validationCookie.Values["OriginalUrl"] = HttpUtility.UrlEncode(originalUrl);
            validationCookie.Values["PlaceInQueue"] = Hashing.EncryptPlaceInQueue(placeInQueue);
            validationCookie.Values["RedirectType"] = redirectType.ToString();
            validationCookie.Values["TimeStamp"] = timeStamp;
            validationCookie.Values["Hash"] = hash;

            validationCookie.HttpOnly = true;
            validationCookie.Domain = CookieDomain;
            validationCookie.Expires = expirationTime;
            validationCookie.Values["Expires"] = expirationTime.ToString("o");

            if (HttpContext.Current.Response.Cookies.AllKeys.Any(cookieKey => cookieKey == key))
                HttpContext.Current.Response.Cookies.Remove(key);
            HttpContext.Current.Response.Cookies.Add(validationCookie);
        }
Exemple #41
0
 /// <summary>
 /// Returns a redirect result task for the provided URL with the provided redirect type.
 /// </summary>
 /// <param name="url">The URL to redirect to.</param>
 /// <param name="redirectType">The redirect type.</param>
 /// <returns>The redirect result task.</returns>
 public static Task<IResult> RedirectToUrl(string url, RedirectType redirectType)
 {
     return Task.FromResult<IResult>(Result.RedirectToUrl(url, redirectType));
 }
        private string GenerateHash(
            string queueId, 
            string originalUrl, 
            string placeInQueue, 
            RedirectType redirectType, 
            string timestamp,
            DateTime expires)
        {
            using (SHA256 sha2 = SHA256.Create())
            {
                string valueToHash = string.Concat(
                    queueId, 
                    originalUrl, 
                    placeInQueue, 
                    redirectType.ToString(), 
                    timestamp, 
                    expires.ToString("o"),
                    KnownUserFactory.SecretKey);
                byte[] hash = sha2.ComputeHash(Encoding.UTF8.GetBytes(valueToHash));

                return BitConverter.ToString(hash);
            }
        }