public void CreateRoutes(IEndpointRouteBuilder endpoints)
        {
            var installPathSegment = _hostingEnvironment.ToAbsolute(Cms.Core.Constants.SystemDirectories.Install).TrimStart('/');

            switch (_runtime.Level)
            {
            case var _ when _runtime.EnableInstaller():

                endpoints.MapUmbracoRoute <InstallApiController>(installPathSegment, Cms.Core.Constants.Web.Mvc.InstallArea, "api", includeControllerNameInRoute: false);

                endpoints.MapUmbracoRoute <InstallController>(installPathSegment, Cms.Core.Constants.Web.Mvc.InstallArea, string.Empty, includeControllerNameInRoute: false);

                // register catch all because if we are in install/upgrade mode then we'll catch everything and redirect
                endpoints.MapFallbackToAreaController(
                    "Redirect",
                    ControllerExtensions.GetControllerName <InstallController>(),
                    Cms.Core.Constants.Web.Mvc.InstallArea);


                break;

            case RuntimeLevel.Run:

                // when we are in run mode redirect to the back office if the installer endpoint is hit
                endpoints.MapGet($"{installPathSegment}/{{controller?}}/{{action?}}", context =>
                {
                    // redirect to umbraco
                    context.Response.Redirect(_linkGenerator.GetBackOfficeUrl(_hostingEnvironment) !, false);
                    return(Task.CompletedTask);
                });
Example #2
0
    private void AssertMinimalBackOfficeRoutes(EndpointDataSource route)
    {
        var endpoint1 = (RouteEndpoint)route.Endpoints[0];

        Assert.AreEqual("umbraco/{action}/{id?}", endpoint1.RoutePattern.RawText);
        Assert.AreEqual(Constants.Web.Mvc.BackOfficeArea, endpoint1.RoutePattern.Defaults[AreaToken]);
        Assert.AreEqual("Default", endpoint1.RoutePattern.Defaults[ActionToken]);
        Assert.AreEqual(
            ControllerExtensions.GetControllerName <BackOfficeController>(),
            endpoint1.RoutePattern.Defaults[ControllerToken]);
        Assert.AreEqual(
            endpoint1.RoutePattern.Defaults[AreaToken],
            typeof(BackOfficeController).GetCustomAttribute <AreaAttribute>(false).RouteValue);

        var endpoint2      = (RouteEndpoint)route.Endpoints[1];
        var controllerName = ControllerExtensions.GetControllerName <AuthenticationController>();

        Assert.AreEqual(
            $"umbraco/backoffice/{Constants.Web.Mvc.BackOfficeApiArea.ToLowerInvariant()}/{controllerName.ToLowerInvariant()}/{{action}}/{{id?}}",
            endpoint2.RoutePattern.RawText);
        Assert.AreEqual(Constants.Web.Mvc.BackOfficeApiArea, endpoint2.RoutePattern.Defaults[AreaToken]);
        Assert.IsFalse(endpoint2.RoutePattern.Defaults.ContainsKey(ActionToken));
        Assert.AreEqual(controllerName, endpoint2.RoutePattern.Defaults[ControllerToken]);
        Assert.AreEqual(
            endpoint1.RoutePattern.Defaults[AreaToken],
            typeof(BackOfficeController).GetCustomAttribute <AreaAttribute>(false).RouteValue);
    }
Example #3
0
        public ActionResult RenderDashboard(DashboardItemModel model)
        {
            switch (model.DashboardType)
            {
            case DashboardType.PartialView:
                return(PartialView(model.ViewName));

            case DashboardType.ChildAction:
                MethodInfo childAction;
                var        editorController = model.GetEditorDashboardAction(BackOfficeRequestContext.RegisteredComponents, out childAction);

                if (!TypeFinder.IsTypeAssignableFrom <PartialViewResult>(childAction.ReturnType) &&
                    !TypeFinder.IsTypeAssignableFrom <ContentResult>(childAction.ReturnType))
                {
                    throw new InvalidOperationException("ChildAction dashboards should have a return type of " + typeof(PartialViewResult).Name + " or " + typeof(ContentResult).Name);
                }

                //proxy the request to the controller
                var result = this.ProxyRequestToController(
                    ControllerExtensions.GetControllerName(editorController.Metadata.ComponentType),
                    childAction.Name,
                    editorController.Metadata,
                    BackOfficeRequestContext.Application.Settings.RebelPaths.BackOfficePath,
                    "editorId",
                    new Dictionary <string, object>());

                return(Content(result.RenderedOutput));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #4
0
        public async Task TestAllScores(string user)
        {
            using var scope  = Factory.Services.CreateScope();
            using var client = Factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test", user);

            var url     = scope.ServiceProvider.GetRequiredService <LinkGenerator>();
            var context = scope.ServiceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;

            var uri = url.GetPathByAction(
                context, nameof(ScoresController.Get),
                ControllerExtensions.GetControllerName <ScoresController>(),
                new
            {
                isApproved = true,
                top        = 10
            });

            Assert.NotNull(uri);

            var jsonOptions = scope.ServiceProvider.GetRequiredService <IOptions <JsonSerializerSettings> >().Value;
            var serializer  = JsonSerializer.Create(jsonOptions);

            var responseStream = await client.GetStreamAsync(uri).ConfigureAwait(false);

            var data = serializer.Deserialize <IEnumerable <ScoreViewModel> >(new JsonTextReader(new StreamReader(responseStream)));
        }
Example #5
0
        public void RuntimeState_Install(RuntimeLevel level)
        {
            InstallAreaRoutes routes = GetInstallAreaRoutes(level);
            var endpoints            = new TestRouteBuilder();

            routes.CreateRoutes(endpoints);

            Assert.AreEqual(2, endpoints.DataSources.Count);
            EndpointDataSource route = endpoints.DataSources.First();

            Assert.AreEqual(2, route.Endpoints.Count);

            var endpoint1 = (RouteEndpoint)route.Endpoints[0];

            Assert.AreEqual($"install/api/{{action}}/{{id?}}", endpoint1.RoutePattern.RawText);
            Assert.AreEqual(Constants.Web.Mvc.InstallArea, endpoint1.RoutePattern.Defaults[AreaToken]);
            Assert.AreEqual("Index", endpoint1.RoutePattern.Defaults[ActionToken]);
            Assert.AreEqual(ControllerExtensions.GetControllerName <InstallApiController>(), endpoint1.RoutePattern.Defaults[ControllerToken]);
            Assert.AreEqual(endpoint1.RoutePattern.Defaults[AreaToken], typeof(InstallApiController).GetCustomAttribute <AreaAttribute>(false).RouteValue);

            var endpoint2 = (RouteEndpoint)route.Endpoints[1];

            Assert.AreEqual($"install/{{action}}/{{id?}}", endpoint2.RoutePattern.RawText);
            Assert.AreEqual(Constants.Web.Mvc.InstallArea, endpoint2.RoutePattern.Defaults[AreaToken]);
            Assert.AreEqual("Index", endpoint2.RoutePattern.Defaults[ActionToken]);
            Assert.AreEqual(ControllerExtensions.GetControllerName <InstallController>(), endpoint2.RoutePattern.Defaults[ControllerToken]);
            Assert.AreEqual(endpoint2.RoutePattern.Defaults[AreaToken], typeof(InstallController).GetCustomAttribute <AreaAttribute>(false).RouteValue);

            EndpointDataSource fallbackRoute = endpoints.DataSources.Last();

            Assert.AreEqual(1, fallbackRoute.Endpoints.Count);

            Assert.AreEqual("Fallback {*path:nonfile}", fallbackRoute.Endpoints[0].ToString());
        }
Example #6
0
        /// <summary>
        /// Return the Url for a Web Api service
        /// </summary>
        /// <param name="url"></param>
        /// <param name="actionName"></param>
        /// <param name="apiControllerType"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetUmbracoApiService(this UrlHelper url, string actionName, Type apiControllerType, object id = null)
        {
            if (actionName == null)
            {
                throw new ArgumentNullException(nameof(actionName));
            }
            if (string.IsNullOrWhiteSpace(actionName))
            {
                throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(actionName));
            }
            if (apiControllerType == null)
            {
                throw new ArgumentNullException(nameof(apiControllerType));
            }

            var area = "";

            var apiController = Current.UmbracoApiControllerTypes
                                .SingleOrDefault(x => x == apiControllerType);

            if (apiController == null)
            {
                throw new InvalidOperationException("Could not find the umbraco api controller of type " + apiControllerType.FullName);
            }
            var metaData = PluginController.GetMetadata(apiController);

            if (metaData.AreaName.IsNullOrWhiteSpace() == false)
            {
                //set the area to the plugin area
                area = metaData.AreaName;
            }
            return(url.GetUmbracoApiService(actionName, ControllerExtensions.GetControllerName(apiControllerType), area, id));
        }
Example #7
0
    /// <summary>
    ///     Return the back office url if the back office is installed
    /// </summary>
    public static string?GetBackOfficeUrl(this LinkGenerator linkGenerator, IHostingEnvironment hostingEnvironment)
    {
        Type?backOfficeControllerType;

        try
        {
            backOfficeControllerType = Assembly.Load("Umbraco.Web.BackOffice")
                                       .GetType("Umbraco.Web.BackOffice.Controllers.BackOfficeController");
            if (backOfficeControllerType == null)
            {
                return("/"); // this would indicate that the installer is installed without the back office
            }
        }
        catch
        {
            return
                (hostingEnvironment
                 .ApplicationVirtualPath);   // this would indicate that the installer is installed without the back office
        }

        return(linkGenerator.GetPathByAction(
                   "Default",
                   ControllerExtensions.GetControllerName(backOfficeControllerType),
                   new { area = Constants.Web.Mvc.BackOfficeApiArea }));
    }
    public void RuntimeState_All_Routes(RuntimeLevel level)
    {
        var routes    = GetRoutes(level);
        var endpoints = new TestRouteBuilder();

        routes.CreateRoutes(endpoints);

        Assert.AreEqual(2, endpoints.DataSources.Count);
        var route = endpoints.DataSources.First();

        Assert.AreEqual(2, route.Endpoints.Count);

        var endpoint0 = (RouteEndpoint)route.Endpoints[0];

        Assert.AreEqual($"{routes.GetPreviewHubRoute()}/negotiate", endpoint0.RoutePattern.RawText);
        var endpoint1 = (RouteEndpoint)route.Endpoints[1];

        Assert.AreEqual($"{routes.GetPreviewHubRoute()}", endpoint1.RoutePattern.RawText);

        var endpoint3             = (RouteEndpoint)endpoints.DataSources.Last().Endpoints[0];
        var previewControllerName = ControllerExtensions.GetControllerName <PreviewController>();

        Assert.AreEqual(
            $"umbraco/{previewControllerName.ToLowerInvariant()}/{{action}}/{{id?}}",
            endpoint3.RoutePattern.RawText);
        Assert.AreEqual(Constants.Web.Mvc.BackOfficeArea, endpoint3.RoutePattern.Defaults["area"]);
        Assert.AreEqual("Index", endpoint3.RoutePattern.Defaults[ActionToken]);
        Assert.AreEqual(previewControllerName, endpoint3.RoutePattern.Defaults[ControllerToken]);
        Assert.AreEqual(
            endpoint3.RoutePattern.Defaults["area"],
            typeof(PreviewController).GetCustomAttribute <AreaAttribute>(false).RouteValue);
    }
        /// <summary>
        /// Return the Url for a Web Api service
        /// </summary>
        /// <param name="url"></param>
        /// <param name="actionName"></param>
        /// <param name="apiControllerType"></param>
        /// <param name="routeVals"></param>
        /// <returns></returns>
        public static string GetUmbracoApiService(this UrlHelper url, string actionName, Type apiControllerType, RouteValueDictionary routeVals = null)
        {
            if (string.IsNullOrEmpty(actionName))
            {
                throw new ArgumentNullOrEmptyException(nameof(actionName));
            }
            if (apiControllerType == null)
            {
                throw new ArgumentNullException(nameof(apiControllerType));
            }

            var area = "";

            var apiController = Current.UmbracoApiControllerTypes
                                .SingleOrDefault(x => x == apiControllerType);

            if (apiController == null)
            {
                throw new InvalidOperationException("Could not find the umbraco api controller of type " + apiControllerType.FullName);
            }
            var metaData = PluginController.GetMetadata(apiController);

            if (!metaData.AreaName.IsNullOrWhiteSpace())
            {
                //set the area to the plugin area
                area = metaData.AreaName;
            }
            return(url.GetUmbracoApiService(actionName, ControllerExtensions.GetControllerName(apiControllerType), area, routeVals));
        }
        /// <summary>
        /// Creates the specified controller by using the specified request context.
        /// </summary>
        /// <returns>
        /// The controller.
        /// </returns>
        /// <param name="requestContext">The request context.</param><param name="controllerName">The name of the controller.</param>
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            Type controllerType = _innerFactory.GetControllerType(requestContext, controllerName) ??
                                  _innerFactory.GetControllerType(requestContext, ControllerExtensions.GetControllerName(typeof(RebelController)));

            return(_innerFactory.GetControllerInstance(requestContext, controllerType));
        }
Example #11
0
        public ActionResult Index(int?id = null)
        {
            var availableLanguages = _localizationService.GetAllLanguages();

            if (id.HasValue)
            {
                var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
                var content        = umbracoContext.Content?.GetById(true, id.Value);
                if (content is null)
                {
                    return(NotFound());
                }

                availableLanguages = availableLanguages.Where(language => content.Cultures.ContainsKey(language.IsoCode));
            }
            var model = new BackOfficePreviewModel(_features, availableLanguages);

            if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false)
            {
                var viewEngineResult = _viewEngines.FindView(ControllerContext, model.PreviewExtendedHeaderView !, false);
                if (viewEngineResult.View == null)
                {
                    throw new InvalidOperationException("Could not find the view " + model.PreviewExtendedHeaderView + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations));
                }
            }

            var viewPath = Path.Combine(
                _globalSettings.UmbracoPath,
                Constants.Web.Mvc.BackOfficeArea,
                ControllerExtensions.GetControllerName <PreviewController>() + ".cshtml")
                           .Replace("\\", "/"); // convert to forward slashes since it's a virtual path

            return(View(viewPath, model));
        }
Example #12
0
    /// <summary>
    ///     Initializes a new instance of the <see cref="UmbracoRouteValuesFactory" /> class.
    /// </summary>
    public UmbracoRouteValuesFactory(
        IOptions <UmbracoRenderingDefaultsOptions> renderingDefaults,
        IShortStringHelper shortStringHelper,
        UmbracoFeatures umbracoFeatures,
        IControllerActionSearcher controllerActionSearcher,
        IPublishedRouter publishedRouter)
    {
        _shortStringHelper        = shortStringHelper;
        _umbracoFeatures          = umbracoFeatures;
        _controllerActionSearcher = controllerActionSearcher;
        _publishedRouter          = publishedRouter;
        _defaultControllerName    = new Lazy <string>(() =>
                                                      ControllerExtensions.GetControllerName(renderingDefaults.Value.DefaultControllerType));
        _defaultControllerDescriptor = new Lazy <ControllerActionDescriptor>(() =>
        {
            ControllerActionDescriptor?descriptor = _controllerActionSearcher.Find <IRenderController>(
                new DefaultHttpContext(), // this actually makes no difference for this method
                DefaultControllerName,
                UmbracoRouteValues.DefaultActionName);

            if (descriptor == null)
            {
                throw new InvalidOperationException(
                    $"No controller/action found by name {DefaultControllerName}.{UmbracoRouteValues.DefaultActionName}");
            }

            return(descriptor);
        });
    }
 private UmbracoRouteValues GetRouteValues(IPublishedRequest request)
 => new UmbracoRouteValues(
     request,
     new ControllerActionDescriptor
 {
     ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
     ControllerName     = ControllerExtensions.GetControllerName <TestController>()
 });
 private ControllerActionDescriptor GetDescriptor <T>(string action)
 => new ControllerActionDescriptor
 {
     ActionName         = action,
     ControllerName     = ControllerExtensions.GetControllerName <T>(),
     ControllerTypeInfo = typeof(RenderController).GetTypeInfo(),
     DisplayName        = $"{ControllerExtensions.GetControllerName<T>()}.{action}"
 };
Example #15
0
    public void MapUmbracoApiRoute(string umbracoPath, string area, bool isBackOffice, string defaultAction)
    {
        var endpoints = new TestRouteBuilder();

        endpoints.MapUmbracoApiRoute <Testing1Controller>(umbracoPath, area, isBackOffice, defaultAction);

        var route    = endpoints.DataSources.First();
        var endpoint = (RouteEndpoint)route.Endpoints[0];

        var controllerName        = ControllerExtensions.GetControllerName <Testing1Controller>();
        var controllerNamePattern = controllerName.ToLowerInvariant();
        var areaPattern           = area?.ToLowerInvariant();

        if (isBackOffice)
        {
            if (area.IsNullOrWhiteSpace())
            {
                Assert.AreEqual(
                    $"{umbracoPath}/backoffice/api/{controllerNamePattern}/{{action}}/{{id?}}",
                    endpoint.RoutePattern.RawText);
            }
            else
            {
                Assert.AreEqual(
                    $"{umbracoPath}/backoffice/{areaPattern}/{controllerNamePattern}/{{action}}/{{id?}}",
                    endpoint.RoutePattern.RawText);
            }
        }
        else
        {
            if (area.IsNullOrWhiteSpace())
            {
                Assert.AreEqual(
                    $"{umbracoPath}/api/{controllerNamePattern}/{{action}}/{{id?}}",
                    endpoint.RoutePattern.RawText);
            }
            else
            {
                Assert.AreEqual(
                    $"{umbracoPath}/{areaPattern}/{controllerNamePattern}/{{action}}/{{id?}}",
                    endpoint.RoutePattern.RawText);
            }
        }

        if (!area.IsNullOrWhiteSpace())
        {
            Assert.AreEqual(area, endpoint.RoutePattern.Defaults[AreaToken]);
        }

        if (!defaultAction.IsNullOrWhiteSpace())
        {
            Assert.AreEqual(defaultAction, endpoint.RoutePattern.Defaults["action"]);
        }

        Assert.AreEqual(controllerName, endpoint.RoutePattern.Defaults[ControllerToken]);
    }
Example #16
0
        private void GenerateAuthPaths(out string remainingTimeoutSecondsPath, out string isAuthPath)
        {
            var controllerName = ControllerExtensions.GetControllerName <AuthenticationController>();

            // this path is not a back office request even though it's in the same controller - it's a 'special' endpoint
            var rPath = remainingTimeoutSecondsPath = $"/umbraco/{Constants.Web.Mvc.BackOfficePathSegment}/{Constants.Web.Mvc.BackOfficeApiArea}/{controllerName}/{nameof(AuthenticationController.GetRemainingTimeoutSeconds)}".ToLower();

            // this is on the same controller but is considered a back office request
            var aPath = isAuthPath = $"/umbraco/{Constants.Web.Mvc.BackOfficePathSegment}/{Constants.Web.Mvc.BackOfficeApiArea}/{controllerName}/{nameof(AuthenticationController.IsAuthenticated)}".ToLower();
        }
Example #17
0
    /// <summary>
    ///     Return the back office url if the back office is installed
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string?GetBackOfficeUrl(this IUrlHelper url)
    {
        var backOfficeControllerType = Type.GetType("Umbraco.Web.BackOffice.Controllers");

        if (backOfficeControllerType == null)
        {
            return("/"); // this would indicate that the installer is installed without the back office
        }

        return(url.Action("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea }));
    }
        public async Task NoContentController_Values_When_No_Content()
        {
            IUmbracoContext umbracoContext = GetUmbracoContext(false);

            UmbracoRouteValueTransformer transformer = GetTransformerWithRunState(
                Mock.Of <IUmbracoContextAccessor>(x => x.TryGetUmbracoContext(out umbracoContext)));

            RouteValueDictionary result = await transformer.TransformAsync(new DefaultHttpContext(), new RouteValueDictionary());

            Assert.AreEqual(2, result.Count);
            Assert.AreEqual(ControllerExtensions.GetControllerName <RenderNoContentController>(), result[ControllerToken]);
            Assert.AreEqual(nameof(RenderNoContentController.Index), result[ActionToken]);
        }
    /// <summary>
    ///     Used to map Umbraco controllers consistently
    /// </summary>
    public static void MapUmbracoRoute(
        this IEndpointRouteBuilder endpoints,
        Type controllerType,
        string rootSegment,
        string?areaName,
        string?prefixPathSegment,
        string defaultAction = "Index",
        bool includeControllerNameInRoute = true,
        object?constraints = null)
    {
        var controllerName = ControllerExtensions.GetControllerName(controllerType);

        // build the route pattern
        var pattern = new StringBuilder(rootSegment);

        if (!prefixPathSegment.IsNullOrWhiteSpace())
        {
            pattern.Append('/').Append(prefixPathSegment);
        }

        if (includeControllerNameInRoute)
        {
            pattern.Append('/').Append(controllerName);
        }

        pattern.Append("/{action}/{id?}");

        var defaults = defaultAction.IsNullOrWhiteSpace()
            ? (object)new { controller = controllerName }
            : new { controller = controllerName, action = defaultAction };

        if (areaName.IsNullOrWhiteSpace())
        {
            endpoints.MapControllerRoute(
                $"umbraco-{areaName}-{controllerName}".ToLowerInvariant(),
                pattern.ToString().ToLowerInvariant(),
                defaults,
                constraints);
        }
        else
        {
            endpoints.MapAreaControllerRoute(
                $"umbraco-{areaName}-{controllerName}".ToLowerInvariant(),
                areaName !,
                pattern.ToString().ToLowerInvariant(),
                defaults,
                constraints);
        }
    }
Example #20
0
    private string ConstructCallbackUrl(string userId, string code)
    {
        // Get an mvc helper to get the url
        var action = _linkGenerator.GetPathByAction(
            nameof(BackOfficeController.ValidatePasswordResetCode),
            ControllerExtensions.GetControllerName <BackOfficeController>(),
            new { area = Constants.Web.Mvc.BackOfficeArea, u = userId, r = code });

        // Construct full URL using configured application URL (which will fall back to current request)
        Uri applicationUri = _httpContextAccessor.GetRequiredHttpContext().Request
                             .GetApplicationUri(_webRoutingSettings);
        var callbackUri = new Uri(applicationUri, action);

        return(callbackUri.ToString());
    }
        public async Task Plugin_Controller_Routes_By_Area()
        {
            // Create URL manually, because PrepareSurfaceController URl will prepare whatever the controller is routed as
            Type   controllerType  = typeof(TestPluginController);
            var    pluginAttribute = CustomAttributeExtensions.GetCustomAttribute <PluginControllerAttribute>(controllerType, false);
            var    controllerName  = ControllerExtensions.GetControllerName(controllerType);
            string url             = $"/umbraco/{pluginAttribute?.AreaName}/{controllerName}";

            PrepareUrl(url);

            HttpResponseMessage response = await Client.GetAsync(url);

            string body = await response.Content.ReadAsStringAsync();

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
    /// <summary>
    ///     Outputs the hidden html input field for Surface Controller route information
    /// </summary>
    /// <typeparam name="TSurface">The <see cref="SurfaceController" /> type</typeparam>
    /// <remarks>
    ///     Typically not used directly because BeginUmbracoForm automatically outputs this value when routing
    ///     for surface controllers. But this could be used in case a form tag is manually created.
    /// </remarks>
    public static IHtmlContent SurfaceControllerHiddenInput <TSurface>(
        this IHtmlHelper htmlHelper,
        string controllerAction,
        string area,
        object?additionalRouteVals = null)
        where TSurface : SurfaceController
    {
        var inputField = GetSurfaceControllerHiddenInput(
            GetRequiredService <IDataProtectionProvider>(htmlHelper),
            ControllerExtensions.GetControllerName <TSurface>(),
            controllerAction,
            area,
            additionalRouteVals);

        return(new HtmlString(inputField));
    }
    private bool IsRemainingSecondsRequest(CookieValidatePrincipalContext context)
    {
        RouteValueDictionary routeValues = context.HttpContext.Request.RouteValues;

        if (routeValues.TryGetValue("controller", out var controllerName) &&
            routeValues.TryGetValue("action", out var action))
        {
            if (controllerName?.ToString() == ControllerExtensions.GetControllerName <AuthenticationController>() &&
                action?.ToString() == nameof(AuthenticationController.GetRemainingTimeoutSeconds))
            {
                return(true);
            }
        }

        return(false);
    }
        /// <summary>
        /// Gets a proxy to a controller for a specified action.
        /// </summary>
        /// <param name="controllerType">The type of the controller.</param>
        /// <param name="action">The action.</param>
        /// <param name="querystring">The querystring.</param>
        /// <returns>An instance of the controller.</returns>
        /// <remarks>
        /// <para>Creates an instance of the <paramref name="controllerType"/> and initializes it with a route
        /// and context etc. so it can execute the specified <paramref name="action"/>. Runs the authorization
        /// filters for that action, to ensure that the user has permission to execute it.</para>
        /// </remarks>
        private async Task <object> GetApiControllerProxy(Type controllerType, string action, FormDataCollection querystring)
        {
            // note: this is all required in order to execute the auth-filters for the sub request, we
            // need to "trick" web-api into thinking that it is actually executing the proxied controller.

            var context = ControllerContext;

            // get the controller
            var controller = (ApiController)DependencyResolver.Current.GetService(controllerType)
                             ?? throw new Exception($"Failed to create controller of type {controllerType.FullName}.");

            // create the proxy URL for the controller action
            var proxyUrl = context.Request.RequestUri.GetLeftPart(UriPartial.Authority)
                           + context.Request.GetUrlHelper().GetUmbracoApiService(action, controllerType)
                           + "?" + querystring.ToQueryString();

            // create proxy route data specifying the action & controller to execute
            var proxyRoute = new HttpRouteData(
                context.RouteData.Route,
                new HttpRouteValueDictionary(new { action, controller = ControllerExtensions.GetControllerName(controllerType) }));

            // create a proxy request
            var proxyRequest = new HttpRequestMessage(HttpMethod.Get, proxyUrl);

            // create a proxy controller context
            var proxyContext = new HttpControllerContext(context.Configuration, proxyRoute, proxyRequest)
            {
                ControllerDescriptor = new HttpControllerDescriptor(context.ControllerDescriptor.Configuration, ControllerExtensions.GetControllerName(controllerType), controllerType),
                RequestContext       = context.RequestContext,
                Controller           = controller
            };

            // wire everything
            controller.ControllerContext        = proxyContext;
            controller.Request                  = proxyContext.Request;
            controller.RequestContext.RouteData = proxyRoute;

            // auth
            var authResult = await controller.ControllerContext.InvokeAuthorizationFiltersForRequest();

            if (authResult != null)
            {
                throw new HttpResponseException(authResult);
            }

            return(controller);
        }
        public void MapUmbracoRoute(string umbracoPath, string area, string prefix, string defaultAction, bool includeControllerName)
        {
            var endpoints = new TestRouteBuilder();

            endpoints.MapUmbracoRoute <Testing1Controller>(umbracoPath, area, prefix, defaultAction, includeControllerName);

            EndpointDataSource route = endpoints.DataSources.First();
            var endpoint             = (RouteEndpoint)route.Endpoints[0];

            string controllerName        = ControllerExtensions.GetControllerName <Testing1Controller>();
            string controllerNamePattern = controllerName.ToLowerInvariant();

            if (includeControllerName)
            {
                if (prefix.IsNullOrWhiteSpace())
                {
                    Assert.AreEqual($"{umbracoPath}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText);
                }
                else
                {
                    Assert.AreEqual($"{umbracoPath}/{prefix}/{controllerNamePattern}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText);
                }
            }
            else
            {
                if (prefix.IsNullOrWhiteSpace())
                {
                    Assert.AreEqual($"{umbracoPath}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText);
                }
                else
                {
                    Assert.AreEqual($"{umbracoPath}/{prefix}/{{action}}/{{id?}}", endpoint.RoutePattern.RawText);
                }
            }

            if (!area.IsNullOrWhiteSpace())
            {
                Assert.AreEqual(area, endpoint.RoutePattern.Defaults[AreaToken]);
            }

            if (!defaultAction.IsNullOrWhiteSpace())
            {
                Assert.AreEqual(defaultAction, endpoint.RoutePattern.Defaults["action"]);
            }

            Assert.AreEqual(controllerName, endpoint.RoutePattern.Defaults[ControllerToken]);
        }
Example #26
0
        /// <summary>
        /// Returns the server variables for non-authenticated users
        /// </summary>
        /// <returns></returns>
        internal async Task <Dictionary <string, object> > BareMinimumServerVariablesAsync()
        {
            //this is the filter for the keys that we'll keep based on the full version of the server vars
            var keepOnlyKeys = new Dictionary <string, string[]>
            {
                { "umbracoUrls", new[] { "authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl", "previewHubUrl", "iconApiBaseUrl" } },
                { "umbracoSettings", new[] { "allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "loginLogoImage", "canSendRequiredEmail", "usernameIsEmail", "minimumPasswordLength", "minimumPasswordNonAlphaNum", "hideBackofficeLogo", "disableDeleteWhenReferenced", "disableUnpublishWhenReferenced" } },
                { "application", new[] { "applicationPath", "cacheBuster" } },
                { "isDebuggingEnabled", new string[] { } },
                { "features", new [] { "disabledFeatures" } }
            };
            //now do the filtering...
            var defaults = await GetServerVariablesAsync();

            foreach (var key in defaults.Keys.ToArray())
            {
                if (keepOnlyKeys.ContainsKey(key) == false)
                {
                    defaults.Remove(key);
                }
                else
                {
                    if (defaults[key] is System.Collections.IDictionary asDictionary)
                    {
                        var toKeep = keepOnlyKeys[key];
                        foreach (var k in asDictionary.Keys.Cast <string>().ToArray())
                        {
                            if (toKeep.Contains(k) == false)
                            {
                                asDictionary.Remove(k);
                            }
                        }
                    }
                }
            }

            // TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
            // so based on compat and how things are currently working we need to replace the serverVarsJs one
            ((Dictionary <string, object>)defaults["umbracoUrls"])["serverVarsJs"]
                = _linkGenerator.GetPathByAction(
                      nameof(BackOfficeController.ServerVariables),
                      ControllerExtensions.GetControllerName <BackOfficeController>(),
                      new { area = Constants.Web.Mvc.BackOfficeArea });

            return(defaults);
        }
Example #27
0
        private async Task SendUserInviteEmailAsync(UserBasic?userDisplay, string?from, string?fromEmail, IUser?to, string?message)
        {
            var user = await _userManager.FindByIdAsync(((int?)userDisplay?.Id).ToString());

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            // Use info from SMTP Settings if configured, otherwise set fromEmail as fallback
            var senderEmail = !string.IsNullOrEmpty(_globalSettings.Smtp?.From) ? _globalSettings.Smtp.From : fromEmail;

            var inviteToken = string.Format("{0}{1}{2}",
                                            (int?)userDisplay?.Id,
                                            WebUtility.UrlEncode("|"),
                                            token.ToUrlBase64());

            // Get an mvc helper to get the URL
            var action = _linkGenerator.GetPathByAction(
                nameof(BackOfficeController.VerifyInvite),
                ControllerExtensions.GetControllerName <BackOfficeController>(),
                new
            {
                area   = Constants.Web.Mvc.BackOfficeArea,
                invite = inviteToken
            });

            // Construct full URL using configured application URL (which will fall back to request)
            Uri applicationUri = _httpContextAccessor.GetRequiredHttpContext().Request.GetApplicationUri(_webRoutingSettings);
            var inviteUri      = new Uri(applicationUri, action);

            var emailSubject = _localizedTextService.Localize("user", "inviteEmailCopySubject",
                                                              // Ensure the culture of the found user is used for the email!
                                                              UmbracoUserExtensions.GetUserCulture(to?.Language, _localizedTextService, _globalSettings));
            var emailBody = _localizedTextService.Localize("user", "inviteEmailCopyFormat",
                                                           // Ensure the culture of the found user is used for the email!
                                                           UmbracoUserExtensions.GetUserCulture(to?.Language, _localizedTextService, _globalSettings),
                                                           new[] { userDisplay?.Name, from, message, inviteUri.ToString(), senderEmail });

            // This needs to be in the correct mailto format including the name, else
            // the name cannot be captured in the email sending notification.
            // i.e. "Some Person" <*****@*****.**>
            var toMailBoxAddress = new MailboxAddress(to?.Name, to?.Email);

            var mailMessage = new EmailMessage(senderEmail, toMailBoxAddress.ToString(), emailSubject, emailBody, true);

            await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.UserInvite, true);
        }
Example #28
0
        /// <summary>
        /// Gets metadata for a controller type.
        /// </summary>
        /// <param name="controllerType">The controller type.</param>
        /// <returns>Metadata for the controller type.</returns>
        public static PluginControllerMetadata GetMetadata(Type controllerType)
        {
            return(MetadataStorage.GetOrAdd(controllerType, type =>
            {
                // plugin controller? back-office controller?
                var pluginAttribute = controllerType.GetCustomAttribute <PluginControllerAttribute>(false);
                var backOfficeAttribute = controllerType.GetCustomAttribute <IsBackOfficeAttribute>(true);

                return new PluginControllerMetadata
                {
                    AreaName = pluginAttribute?.AreaName,
                    ControllerName = ControllerExtensions.GetControllerName(controllerType),
                    ControllerNamespace = controllerType.Namespace,
                    ControllerType = controllerType,
                    IsBackOffice = backOfficeAttribute != null
                };
            }));
        }
Example #29
0
        private void Init()
        {
            var top = 100;

            Props ??= new RecentsReactProps
            {
                InitialUrl = _link.GetUriByAction(HttpContext,
                                                  nameof(ScoresController.Get),
                                                  ControllerExtensions.GetControllerName <ScoresController>(),
                                                  new ByBoardScoresQuery
                {
                    IsApproved = true,
                    Top        = top
                }),
                Top          = top,
                RefreshEvery = 5000
            };
        }
Example #30
0
    private UmbracoRouteValuesFactory GetFactory(
        out Mock <IPublishedRouter> publishedRouter,
        out IOptions <UmbracoRenderingDefaultsOptions> renderingDefaults,
        out IPublishedRequest request)
    {
        var builder = new PublishedRequestBuilder(new Uri("https://example.com"), Mock.Of <IFileService>());

        builder.SetPublishedContent(Mock.Of <IPublishedContent>());
        var builtRequest = request = builder.Build();

        publishedRouter = new Mock <IPublishedRouter>();
        publishedRouter.Setup(x => x.UpdateRequestAsync(It.IsAny <IPublishedRequest>(), null))
        .Returns((IPublishedRequest r, IPublishedContent c) => Task.FromResult(builtRequest))
        .Verifiable();

        renderingDefaults =
            Mock.Of <IOptions <UmbracoRenderingDefaultsOptions> >(x =>
                                                                  x.Value.DefaultControllerType == typeof(RenderController));

        // add the default one
        var actionDescriptors = new List <ActionDescriptor>
        {
            new ControllerActionDescriptor
            {
                ControllerName     = ControllerExtensions.GetControllerName <RenderController>(),
                ActionName         = nameof(RenderController.Index),
                ControllerTypeInfo = typeof(RenderController).GetTypeInfo(),
            },
        };
        var actionSelector = new Mock <IActionSelector>();

        actionSelector.Setup(x => x.SelectCandidates(It.IsAny <RouteContext>())).Returns(actionDescriptors);

        var factory = new UmbracoRouteValuesFactory(
            renderingDefaults,
            Mock.Of <IShortStringHelper>(),
            new UmbracoFeatures(),
            new ControllerActionSearcher(
                new NullLogger <ControllerActionSearcher>(),
                actionSelector.Object),
            publishedRouter.Object);

        return(factory);
    }