public void CreateRedirectShouldReturnBadRequestWithMessageWhenUrlIsInvalid(RedirectSave input, string errorMessage)
        {
            // arrange
            // disable it in config
            Mock.Get(UmbracoConfig.For.UmbracoSettings().WebRouting).SetupGet(x => x.DisableRedirectUrlTracking).Returns(false);

            this.redirectUrlServiceMock.Setup(x => x.Register(It.IsAny <string>(), It.IsAny <Guid>()));

            this.localizeTextServiceMock.Setup(
                x => x.Localize(errorMessage, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >())).Returns(errorMessage);

            // act
            var result = this.controller.CreateRedirect(input);

            // assert
            this.redirectUrlServiceMock.Verify(x => x.Register(It.IsAny <string>(), It.IsAny <Guid>()), Times.Never);
            this.localizeTextServiceMock.Verify(
                x => x.Localize(errorMessage, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >()), Times.Once);

            Assert.IsNotNull(result);

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);

            Assert.IsNotNull(result.Content);
            var content = (ObjectContent)result.Content;

            Assert.IsNotNull(content.Value);
            Assert.IsInstanceOf <SimpleNotificationModel>(content.Value);

            Assert.AreEqual(errorMessage, ((SimpleNotificationModel)content.Value).Message);
        }
        public void CreateRedirectShouldSaveUrlInLowerCase()
        {
            // arrange
            var input = new RedirectSave
            {
                Url        = "/Foo",
                ContentKey = Guid.NewGuid()
            };

            var msgKey = "redirectsviewer/createSuccess";

            // disable it in config
            Mock.Get(UmbracoConfig.For.UmbracoSettings().WebRouting).SetupGet(x => x.DisableRedirectUrlTracking).Returns(false);

            var redirectMock = new Mock <IRedirectUrl>();

            redirectMock.SetupGet(x => x.Url).Returns("/bar");

            long total;

            this.redirectUrlServiceMock.Setup(x => x.GetAllRedirectUrls(0, int.MaxValue, out total)).Returns(new List <IRedirectUrl>
            {
                redirectMock.Object
            });

            this.redirectUrlServiceMock.Setup(x => x.Register(input.Url, input.ContentKey));

            this.localizeTextServiceMock.Setup(
                x => x.Localize(msgKey, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >())).Returns(msgKey);

            this.domainServiceMock.Setup(x => x.GetAll(true)).Returns(new List <IDomain>());

            // act
            var result = this.controller.CreateRedirect(input);

            // assert
            this.redirectUrlServiceMock.Verify(x => x.GetAllRedirectUrls(0, int.MaxValue, out total), Times.Once);
            this.redirectUrlServiceMock.Verify(x => x.Register(input.Url, input.ContentKey), Times.Once);
            this.localizeTextServiceMock.Verify(
                x => x.Localize(msgKey, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >()), Times.Once);
            this.domainServiceMock.Verify(x => x.GetAll(true), Times.Once);

            Assert.IsNotNull(result);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

            Assert.IsTrue(input.Url == "/foo");

            Assert.IsNotNull(result.Content);
            var content = (ObjectContent)result.Content;

            Assert.IsNotNull(content.Value);
            Assert.IsInstanceOf <SimpleNotificationModel>(content.Value);

            Assert.AreEqual(msgKey, ((SimpleNotificationModel)content.Value).Message);
        }
        public void CreateRedirectShouldReturnErrorResponsetWhenCreateFails()
        {
            // arrange
            var input = new RedirectSave
            {
                Url        = "/foo",
                ContentKey = Guid.NewGuid()
            };

            var msgKey = "redirectsviewer/createError";

            // disable it in config
            Mock.Get(UmbracoConfig.For.UmbracoSettings().WebRouting).SetupGet(x => x.DisableRedirectUrlTracking).Returns(false);

            long total;

            this.redirectUrlServiceMock.Setup(x => x.GetAllRedirectUrls(0, int.MaxValue, out total)).Returns(new List <IRedirectUrl>());

            this.redirectUrlServiceMock.Setup(x => x.Register(input.Url, input.ContentKey)).Throws(new Exception("Error during creating of redirect"));

            this.localizeTextServiceMock.Setup(
                x => x.Localize(msgKey, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >())).Returns(msgKey);

            this.domainServiceMock.Setup(x => x.GetAll(true)).Returns(new List <IDomain>());

            // act
            var result = this.controller.CreateRedirect(input);

            // assert
            this.redirectUrlServiceMock.Verify(x => x.GetAllRedirectUrls(0, int.MaxValue, out total), Times.Once);
            this.redirectUrlServiceMock.Verify(x => x.Register(input.Url, input.ContentKey), Times.Once);
            this.localizeTextServiceMock.Verify(
                x => x.Localize(msgKey, It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >()), Times.Once);
            this.domainServiceMock.Verify(x => x.GetAll(true), Times.Once);

            Assert.IsNotNull(result);

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);

            Assert.IsNotNull(result.Content);
            var content = (ObjectContent)result.Content;

            Assert.IsNotNull(content.Value);
            Assert.IsInstanceOf <SimpleNotificationModel>(content.Value);

            Assert.AreEqual(msgKey, ((SimpleNotificationModel)content.Value).Message);
        }
        public void CreateRedirectShouldReturnBadRequestWhenInputIsInvalid(RedirectSave input)
        {
            // arrange
            // disable it in config
            Mock.Get(UmbracoConfig.For.UmbracoSettings().WebRouting).SetupGet(x => x.DisableRedirectUrlTracking).Returns(false);

            this.redirectUrlServiceMock.Setup(x => x.Register(It.IsAny <string>(), It.IsAny <Guid>()));

            // act
            var result = this.controller.CreateRedirect(input);

            // assert
            this.redirectUrlServiceMock.Verify(x => x.Register(It.IsAny <string>(), It.IsAny <Guid>()), Times.Never);

            Assert.IsNotNull(result);

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
        }
        /// <summary>
        /// Validates the url when creating a redirect
        /// </summary>
        /// <param name="redirect">
        /// The redirect.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string ValidateUrl(RedirectSave redirect)
        {
            if (redirect.Url.StartsWith("http://") || redirect.Url.StartsWith("https://"))
            {
                return(this._localizedTextService.Localize("redirectsviewer/urlRelativeError"));
            }

            if (redirect.Url.Contains("."))
            {
                return(this._localizedTextService.Localize("redirectsviewer/urlNoDotsError"));
            }

            if (redirect.Url.Contains(" "))
            {
                return(this._localizedTextService.Localize("redirectsviewer/urlNoSpacesError"));
            }


            // make sure we have a valid url
            redirect.Url = redirect.Url.ToLower().EnsureStartsWith("/").TrimEnd("/");

            return(string.Empty);
        }
        public HttpResponseMessage CreateRedirect(RedirectSave redirect)
        {
            if (this.IsUrlTrackingDisabled())
            {
                return(new HttpResponseMessage(HttpStatusCode.Conflict));
            }

            if (redirect.ContentKey == Guid.Empty || string.IsNullOrEmpty(redirect.Url))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var urlError = this.ValidateUrl(redirect);

            if (!string.IsNullOrEmpty(urlError))
            {
                return(this.Request.CreateNotificationValidationErrorResponse(urlError));
            }

            try
            {
                // check if we there is a domain configured for this node in umbraco
                var rootNode = string.Empty;

                // get all the domains that have a root content id set
                var domains = this._domainService.GetAll(true).Where(x => x.RootContentId.HasValue).ToList();

                if (domains.Any())
                {
                    // get the content item
                    var content = this._contentService.GetById(redirect.ContentKey);

                    if (content == null)
                    {
                        throw new Exception("Content does not exist");
                    }

                    // get all the ids in the path
                    var pathIds = content.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                    if (pathIds.Any())
                    {
                        // find a domain that is in the path of the item
                        var assignedDomain = domains.FirstOrDefault(x => pathIds.Contains(x.RootContentId.Value.ToString()));

                        if (assignedDomain != null)
                        {
                            // get the root content node
                            rootNode = assignedDomain.RootContentId.Value.ToString();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(rootNode))
                {
                    // prefix the url with the root content node
                    redirect.Url = rootNode + redirect.Url;
                }

                // check if there is already a redirect with the url
                long total;
                var  redirects = this._redirectUrlService.GetAllRedirectUrls(0, int.MaxValue, out total);

                if (redirects.Any(x => x.Url == redirect.Url))
                {
                    return(this.Request.CreateNotificationValidationErrorResponse(this._localizedTextService.Localize("redirectsviewer/urlExistsError")));
                }

                this._redirectUrlService.Register(redirect.Url, redirect.ContentKey);
                return(this.Request.CreateNotificationSuccessResponse(this._localizedTextService.Localize("redirectsviewer/createSuccess")));
            }
            catch (Exception ex)
            {
                this._logger.Error(this.GetType(), "Error creating redirect", ex);
                return(this.Request.CreateNotificationValidationErrorResponse(this._localizedTextService.Localize("redirectsviewer/createError")));
            }
        }