Esempio n. 1
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);
        }
        public virtual IActionResult Add()
        {
            TAddModel addModel = Dal.GetAddModel();
            Type      type     = addModel.GetType();

            foreach (KeyValuePair <string, StringValues> keyValuePair in this.HttpContext.Request.Query)
            {
                PropertyInfo property = type.GetProperty(keyValuePair.Key);
                if (!Equals(property, null))
                {
                    property.SetValue(addModel, ControllerExtensions.Parse(keyValuePair.Value, property.PropertyType),
                                      null);
                }
            }

            return(base.View("AddOrEdit", addModel));
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            _applicationBuilder = app;
            loggerFactory.AddFile("Logs/log-{Date}.txt", LogLevel.Warning);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
//            app.UseRequestLocalization();
            app.Use(async(context, next) =>
            {
                await next();
                //redirect to login
                if (context.Response.StatusCode == 401 && !context.IsJsonRequest())
                {
                    context.Response.Redirect(ControllerExtensions.RedirectLogin(context.Request.GetDisplayUrl()));
                }
            });
            app.UseResponseCaching();
            app.UseResponseCompression();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseAuthentication();

#if DEBUG
            app.UseSwagger();
            app.UseSwaggerUi3();
#endif

            app.UseMvc();
            app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; });
            var databaseSetupTask = SetupDatabase(loggerFactory, app.ApplicationServices);
            if (!databaseSetupTask.IsCompleted)
            {
                databaseSetupTask.AsTask().Wait();
            }
        }
Esempio n. 4
0
    public async Task Plugin_Controller_Routes_By_Area()
    {
        // Create URL manually, because PrepareSurfaceController URl will prepare whatever the controller is routed as
        var controllerType  = typeof(TestPluginController);
        var pluginAttribute =
            CustomAttributeExtensions.GetCustomAttribute <PluginControllerAttribute>(controllerType, false);
        var controllerName = ControllerExtensions.GetControllerName(controllerType);
        var url            = $"/umbraco/{pluginAttribute?.AreaName}/{controllerName}";

        PrepareUrl(url);

        var response = await Client.GetAsync(url);

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

        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
Esempio n. 5
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);
        }
Esempio n. 6
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
                };
            }));
        }
Esempio n. 7
0
        public async Task <IActionResult> TestAction()
        {
            string           email             = "*****@*****.**";
            string           confirmationToken = "";
            VerifyEmailModel model             = new VerifyEmailModel()
            {
                ConfirmationUrl = await userSvc.GetVerificationCodeAsync(email),
                UserName        = "******",
            };
            string emailView = await ControllerExtensions.RenderViewAsync(this, "~/Views/Email/VerifyEmail.cshtml", model);

            //"Liam Cullers (Google Slides)" <*****@*****.**>
            await userSvc.SendVerificationEmailAsync(email, emailView);

            LayoutModel layoutModel = new LayoutModel();

            return(View("~/Views/Home/Home.cshtml", layoutModel));
        }
Esempio n. 8
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
            };
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the display name of the <see cref="DynamicModuleType"/>
        /// </summary>
        /// <returns><see cref="DynamicModuleType"/>'s display name</returns>
        private string GetDynamicContentTypeDisplayName()
        {
            var widgetName = this.ViewBag.WidgetName as string;

            if (widgetName.IsNullOrEmpty())
            {
                return(null);
            }

            var dynamicType = ControllerExtensions.GetDynamicContentType(widgetName);

            if (dynamicType != null)
            {
                return(dynamicType.DisplayName);
            }

            return(null);
        }
Esempio n. 10
0
        public JsonResult Register(Credentials credentials)
        {
            if (!ModelState.IsValid)
            {
                return(ControllerExtensions.CreateModelValidationResult(this));
            }

            var context = invoker.Invoke(new InvokerContext(new UserRegistration(), credentials));

            if (!context.Results.UserRegistered)
            {
                return(ControllerExtensions.CreateModelErrors(this, context.Messages.ToArray()));
            }

            TempData["Messages"] = context.Messages;

            return(Json(new { Success = true, RedirectURL = Url.Action("Index") }));
        }
        public static IWindsorContainer RegisterMvcControllers([NotNull] this IWindsorContainer container,
                                                               params Type[] controllerTypes)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }
            foreach (var type in controllerTypes)
            {
                if (ControllerExtensions.IsController(type))
                {
                    container.Register(
                        Component.For(type).Named(type.FullName).LifeStyle.Is(LifestyleType.Transient));
                }
            }

            return(container);
        }
Esempio n. 12
0
        // GET: Phones
        public ActionResult List()
        {
            PhonesService phoneService = new PhonesService();
            PhoneListVM   model        = new PhoneListVM();

            TryUpdateModel(model);

            if (!model.ContactID.HasValue)
            {
                return(ControllerExtensions.RedirectToAction <ContactsController>(this, c => c.List()));
            }

            model.Contact = phoneService.GetContact(model.ContactID.Value);
            model.Phones  = phoneService.GetAll().Where(p => p.ContactID == model.ContactID.Value).ToList();


            return(View(model));
        }
Esempio n. 13
0
    /// <summary>
    ///     Return the Url for a Web Api service
    /// </summary>
    /// <param name="url"></param>
    /// <param name="umbracoApiControllerTypeCollection"></param>
    /// <param name="actionName"></param>
    /// <param name="apiControllerType"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    public static string?GetUmbracoApiService(
        this IUrlHelper url,
        UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection,
        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 = string.Empty;

        Type?apiController = umbracoApiControllerTypeCollection.SingleOrDefault(x => x == apiControllerType);

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

        PluginControllerMetadata 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));
    }
Esempio n. 14
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);
    }
Esempio n. 15
0
        public IActionResult SignupProcess(ServiceProviderModel model)
        {
            model.isActive = true; // should be after user has validated their email. but temp for now

            model.VerifyCode = Guid.NewGuid().ToString();
            var serviceprovider = TheRepository.CreateServiceProvider(model);

            model.id                     = serviceprovider.id;
            model.emailConfirmed         = false;
            model.isRegistrationApproved = false;
            model.createdDate            = DateTime.Now;
            model.password               = PasswordHash.PasswordHash.CreateHash(model.password).Replace("1000:", String.Empty);

            LoginModel login = new LoginModel
            {
                userName    = model.emailAddress,
                password    = model.password,
                userid      = serviceprovider.id,
                createdDate = DateTime.Now
            };

            var createdLogin = TheRepository.CreateLogin(login);


            var callbackUrl = Url.Action("VerifyEmail", "Signup", new { userId = serviceprovider.id, code = model.VerifyCode }, Request.Scheme, Request.Host.Value + "/ServiceProviderArea");
            var Body        = $"Welcome from I NEED YOUR TIME. Click <a href='{callbackUrl}'>here</a> to confirm your email";

            var model2 = new Emailmodel
            {
                Name = model.firstName,
                Body = Body
            };
            var renderedHTML = ControllerExtensions.RenderViewAsHTMLString(this, "_VerifyEmail.cshtml", model2);

            EmailManager.SendEmail2(model.emailAddress, "VerifyAccount", renderedHTML.Result);
            //Send an authorisation email to the service provider
            //SendSimpleMessage("Welcome from I NEED YOUR TIME", "*****@*****.**").Content.ToString();

            //Send an email to the Administrator with the service provider details
            //SendSimpleMessage("New customer on INYT website", "*****@*****.**").Content.ToString();

            return(View(model));
        }
Esempio n. 16
0
        public async Task <IActionResult> SetNewPassword([FromBody] SetNewPasswordModel body)
        {
            var user = await _userService.GetUserByIdAsync(body.UserId);

            if (user == null)
            {
                _logger.LogError($"Invalid password reset attemp. User with id {body.UserId} doesn't exist.");
                return(BadRequest());
            }
            var result = await _userService.ResetPasswordAsync(user, body.Token, body.Password);

            if (!result.Succeeded)
            {
                _logger.LogInformation(ControllerExtensions.IdentityErrorBuilder($"Error when resetting password for user {user.Email}. Identity errors: ", result.Errors));
                Dictionary <string, string[]> identityErrors = ControllerExtensions.IdentityErrorsToDictionary(result.Errors);
                return(ValidationError(identityErrors));
            }
            return(Ok());
        }
Esempio n. 17
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());
        }
Esempio n. 18
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 request)
            var applicationUri = _hostingEnvironment.ApplicationMainUrl;
            var callbackUri    = new Uri(applicationUri, action);

            return(callbackUri.ToString());
        }
        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];
            string 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);
        }
Esempio n. 20
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);

            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)
            var applicationUri = _hostingEnvironment.ApplicationMainUrl;
            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(), fromEmail });

            // 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(null /*use info from smtp settings*/, toMailBoxAddress.ToString(), emailSubject, emailBody, true);

            await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.UserInvite, true);
        }
Esempio n. 21
0
        public ActionResult ThankYou(int id, string referenceid)
        {
            BookingsListModel   model    = new BookingsListModel();
            List <BookingModel> bookings = new List <BookingModel>();

            bookings              = TheRepository.GetAllBookingsByCustomer(id).Where(a => a.bookingReference == referenceid).ToList();
            bookings              = bookings.Where(a => a.bookingFulfilled == false).ToList();
            model.bookings        = bookings;
            model.serviceProvider = TheRepository.GetServiceProvider(model.bookings[0].serviceProviderId);
            model.customer        = TheRepository.GetCustomer(id);

            //Send an authorisation email to the customer
            EmailInfo emailInfo = new EmailInfo();

            emailInfo.Body       = $"Welcome from I NEED YOUR TIME. Please see below for details of the appointment";
            emailInfo.emailType  = "Appointment confirmation";
            emailInfo.IsBodyHtml = true;
            emailInfo.Subject    = "Welcome to INYT";
            emailInfo.ToAddress  = model.customer.emailAddress;
            //_emailManager.SendEmail(emailInfo);
            var model2 = new Emailmodel
            {
                Name = model.customer.firstName,
                Body = emailInfo.Body
            };
            var renderedHTML = ControllerExtensions.RenderViewAsHTMLString(this, "_VerifyEmail.cshtml", model2);

            EmailManager.SendEmail2(model.customer.emailAddress, "VerifyAccount", renderedHTML.Result);

            if (bookings != null)
            {
                foreach (var booking in bookings)
                {
                    booking.bookingFulfilled = true;
                    booking.bookingAccepted  = true;
                    booking.bookingReference = referenceid;
                    TheRepository.UpdateBooking(booking);
                }
            }

            return(View(model));
        }
Esempio n. 22
0
        /// <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 <ActionResult <object> > GetApiControllerProxy(Type controllerType, string action, FormCollection querystring)
        {
            // note: this is all required in order to execute the auth-filters for the sub request, we
            // need to "trick" mvc into thinking that it is actually executing the proxied controller.

            var controllerName = ControllerExtensions.GetControllerName(controllerType);

            // create proxy route data specifying the action & controller to execute
            var routeData = new RouteData(new RouteValueDictionary()
            {
                [ActionToken]     = action,
                [ControllerToken] = controllerName
            });

            if (!(querystring is null))
            {
                foreach (var(key, value) in querystring)
                {
                    routeData.Values[key] = value;
                }
            }

            var actionDescriptor = _actionDescriptorCollectionProvider.ActionDescriptors.Items
                                   .Cast <ControllerActionDescriptor>()
                                   .First(x =>
                                          x.ControllerName.Equals(controllerName) &&
                                          x.ActionName == action);

            var actionContext          = new ActionContext(HttpContext, routeData, actionDescriptor);
            var proxyControllerContext = new ControllerContext(actionContext);
            var controller             = (TreeControllerBase)_controllerFactory.CreateController(proxyControllerContext);

            // TODO: What about other filters? Will they execute?
            var isAllowed = await controller.ControllerContext.InvokeAuthorizationFiltersForRequest(actionContext);

            if (!isAllowed)
            {
                return(Forbid());
            }

            return(controller);
        }
Esempio n. 23
0
    public void RuntimeState_Install(RuntimeLevel level)
    {
        var routes    = GetInstallAreaRoutes(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 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);

        var fallbackRoute = endpoints.DataSources.Last();

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

        Assert.AreEqual("Fallback {*path:nonfile}", fallbackRoute.Endpoints[0].ToString());
    }
Esempio n. 24
0
        public JsonResult Login(Credentials credentials)
        {
            if (!ModelState.IsValid)
            {
                return(ControllerExtensions.CreateModelValidationResult(this));
            }

            var context = invoker.Invoke(new InvokerContext(new UserLogin(), credentials));

            if (!context.Results.LoggedIn)
            {
                return(ControllerExtensions.CreateModelErrors(this, context.Messages.ToArray()));
            }

            TempData["Messages"] = context.Messages;

            FormsAuthentication.SetAuthCookie(credentials.CompanyName, false);
            Session["CompanyName"] = credentials.CompanyName;
            return(Json(new { Success = true, RedirectURL = Url.Action("Index", "Home") }));
        }
        public async Task FunctionalDeletePoolIdTest()
        {
            var batchService = new BatchService(ConfigurationHelper.GetConfiguration());
            var controller   = ControllerExtensions.NewCloudController();

            // Create a json body with a specific pool id
            var jsonBody = new DeletePoolApiJsonBody
            {
                PoolId = "TEST_RENDERING"
            };

            var result = await controller.DeletePool((JObject)JToken.FromObject(jsonBody));

            Assert.IsInstanceOfType(result, typeof(HttpResponseMessage));
            Assert.IsTrue(result.IsSuccessStatusCode);

            var pool = batchService.GetPoolsInBatch();

            Assert.IsTrue(pool?.FirstOrDefault(p => p.Id == jsonBody.PoolId).State == Microsoft.Azure.Batch.Common.PoolState.Deleting);
        }
Esempio n. 26
0
        public JsonResult GetCookies()
        {
            var mycookies  = new NlCheckout().GetvalueAppsetting("my_cookies");
            var objcookies = Common.util.SessionUtility.ReadCookie(mycookies);
            var arr        = new List <Common.util.ProductItem>();

            if (objcookies != null)
            {
                arr = JsonConvert.DeserializeObject <List <Common.util.ProductItem> >(objcookies);
            }
            if (arr.Any())
            {
                string body = ControllerExtensions.RenderRazorViewToString(this, "ViewComparse", arr);
                return(Json(body, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(1, JsonRequestBehavior.AllowGet));
            }
        }
        public IActionResult Get()
        {
            var result = _securityService.GetSecurities();

            if (result.IsSuccess)
            {
                var models = _mapper.Map <List <Security>, List <SecurityModel> >(result.Value);
                return(Ok(models));
            }
            else
            {
                switch (result.Error)
                {
                case ApplicationMissingDataError error:
                    return(ControllerExtensions.InternalServerError(this, new ServerErrorMessageModel()));

                default:
                    return(ControllerExtensions.InternalServerError(this, new ServerErrorMessageModel()));
                }
            }
        }
        public async Task OrchestratorReturnsNoAutoscalingWhenNotEnabled()
        {
            var configuration = ConfigurationHelper.GetConfiguration();

            configuration["AutomaticScalingThreshold"] = "0";

            var controller = ControllerExtensions.NewOrchestratorController(configuration);

            // Create a json body with correct parameters
            var jsonBody = new OrchestratorApiJsonBody
            {
                TotalSessions = 5,
                TotalSlots    = 10
            };

            var result = await controller.Post((JObject)JToken.FromObject(jsonBody));

            Assert.IsInstanceOfType(result, typeof(HttpResponseMessage));
            Assert.IsTrue((result as HttpResponseMessage).StatusCode == System.Net.HttpStatusCode.BadRequest);
            Assert.IsTrue(((ObjectContent)(result as HttpResponseMessage).Content).Value.ToString().Equals(ApiResultMessages.WarningNoAutoscaling));
        }
Esempio n. 29
0
        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);
                });

                break;

            case RuntimeLevel.BootFailed:
            case RuntimeLevel.Unknown:
            case RuntimeLevel.Boot:
                break;
            }
        }
        /// <summary>
        /// Retreives the string result from a SurfaceController's ChildAction and returns a ContentResult for it.
        /// </summary>
        /// <param name="currentNode"></param>
        /// <param name="macroParams"></param>
        /// <param name="macro"></param>
        /// <param name="currentControllerContext"></param>
        /// <param name="routableRequestContext"></param>
        /// <returns></returns>
        public override ActionResult Execute(
            Content currentNode,
            IDictionary <string, string> macroParams,
            MacroDefinition macro,
            ControllerContext currentControllerContext,
            IRoutableRequestContext routableRequestContext)
        {
            MethodInfo childAction;

            var surfaceController = macro.GetSurfaceMacroChildAction(routableRequestContext.RegisteredComponents, out childAction);

            //we check the return type here, which is cached so it will be fast, but in theory when we execute the controller, it will
            //also ensure this check, though i think it does a different type of check so have left it here at least to display a nicer warning.
            if (!TypeFinder.IsTypeAssignableFrom <PartialViewResult>(childAction.ReturnType) &&
                !TypeFinder.IsTypeAssignableFrom <ContentResult>(childAction.ReturnType))
            {
                throw new InvalidOperationException("ChildAction macros should have a return type of " + typeof(PartialViewResult).Name + " or " + typeof(ContentResult).Name);
            }

            var controllerName = ControllerExtensions.GetControllerName(surfaceController.Metadata.ComponentType);

            //need to get the macroParams to put into an array
            var p = macroParams.ToDictionary <KeyValuePair <string, string>, string, object>(i => i.Key, i => i.Value);

            //proxy the request to the controller
            var result = currentControllerContext.Controller.ProxyRequestToController(
                controllerName,
                childAction.Name,
                surfaceController.Metadata,
                routableRequestContext.Application.Settings.RebelPaths.BackOfficePath,
                "surfaceId",
                p);

            ////write the results to a ContentResult
            return(new ContentResult()
            {
                Content = result.RenderedOutput
            });
        }