Exemplo n.º 1
0
        public void ConstructorSetsUrl() {
            // Act
            var result = new RedirectResult(_baseUrl);

            // Assert
            Assert.AreSame(_baseUrl, result.Url);
        }
        public ActionResult Index(string title)
        {
            ActionResult result = null;
            BlogModel model = null;

            if (string.IsNullOrEmpty(title))
            {
                model = this.GetIndexModel();
            }
            else
            {
                model = this.GetIndexModelByTitle(title);

                if (model.FeedItems.TotalRows == 0)
                {
                    result = new RedirectResult(Areas.Error.ErrorUrlHelper.NotFound404(this.Url));
                }
            }

            if(result==null)
            {
                result = View(model);
            }

            return result;
        }
        public void ConstructorSetsUrlAndPermanent() {
            // Act
            var result = new RedirectResult(_baseUrl, permanent: true);

            // Assert
            Assert.AreSame(_baseUrl, result.Url);
            Assert.IsTrue(result.Permanent);
        }
Exemplo n.º 4
0
        public void ConstructorSetsUrl()
        {
            // Act
            var result = new RedirectResult(_baseUrl);

            // Assert
            Assert.Same(_baseUrl, result.Url);
            Assert.False(result.Permanent);
        }
Exemplo n.º 5
0
        public void ExecuteResultWithNullControllerContextThrows() {
            // Arrange
            var result = new RedirectResult(_baseUrl);

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    result.ExecuteResult(null /* context */);
                },
                "context");
        }
Exemplo n.º 6
0
        public void ProcessResult_WhenCreatedWithValidUri_ReturnsUri()
        {
            var response = new FakeResponseContext();
            var result = new RedirectResult("someuri");

            Assert.That(result.Uri, Is.EqualTo("someuri"));

            result.ProcessResult(null, response);

            Assert.That(response.RedirectUrl, Is.EqualTo("someuri"));
        }
Exemplo n.º 7
0
        public void RedirectResult_Constructor_WithParameterUrlAndPermanent_SetsResultUrlAndPermanent()
        {
            // Arrange
            var url = "/test/url";

            // Act
            var result = new RedirectResult(url, permanent: true);

            // Assert
            Assert.True(result.Permanent);
            Assert.Same(url, result.Url);
        }
Exemplo n.º 8
0
        public void RedirectInChildActionThrows() {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.PARENT_ACTION_VIEWCONTEXT] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectResult result = new RedirectResult(_baseUrl);

            // Act & Assert
            ExceptionHelper.ExpectInvalidOperationException(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
            );
        }
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            string LogTitle = string.Format("{0} {1}", MvcApplication.Name, LoggerCategories.UIServerSideUnhandledException);
            NameValueCollection serverVars = System.Web.HttpContext.Current.Request.ServerVariables;
            Dictionary<string, object> param = (from key in serverVars.AllKeys select new KeyValuePair<string, object>(key, serverVars[key])).ToDictionary(k => k.Key, k => k.Value);
            LoggingHelper.Write(new LogEntry(filterContext.Exception, LoggerCategories.UIServerSideUnhandledException, 1, 1, TraceEventType.Error, LogTitle, param));

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                JsonResult jr = new JsonResult()
                {
                    Data = new DataResultString()
                                    {
                                        Message = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError,
                                        IsValid = false,
                                        Data = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError,
                                        MessageType = DataResultMessageType.Error
                                    }
                };

                filterContext.Result = jr;
                filterContext.ExceptionHandled = true;
            }
            else
            {
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                RedirectResult r = null;
                Type exceptionType = filterContext.Exception.GetType();
                if (exceptionType == typeof(FaultException))
                {
                    r = new RedirectResult(string.Format("{0}?id={1}", ErrorUrlHelper.FaultExceptionUnExpected(url), filterContext.Exception.Message));
                }
                else
                {
                    if (exceptionType.Namespace == typeof(Endpoint).Namespace)
                    {
                        r = new RedirectResult(ErrorUrlHelper.CommunicationError(url));
                    }
                    else
                    {
                        r = new RedirectResult(ErrorUrlHelper.UnExpected(url));
                    }
                }

                filterContext.Result = r;
                filterContext.ExceptionHandled = true;
            }
        }
Exemplo n.º 10
0
        public void Execute(ActionContext context, RedirectResult result)
        {
            var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context);

            // IsLocalUrl is called to handle  Urls starting with '~/'.
            var destinationUrl = result.Url;
            if (urlHelper.IsLocalUrl(destinationUrl))
            {
                destinationUrl = urlHelper.Content(result.Url);
            }

            _logger.RedirectResultExecuting(destinationUrl);
            context.HttpContext.Response.Redirect(destinationUrl, result.Permanent);
        }
Exemplo n.º 11
0
        public void ExecuteResultCallsResponseRedirect() {
            // Arrange
            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
            mockResponse.Expect(o => o.Redirect(_baseUrl, false /* endResponse */));
            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
            mockContext.Expect(o => o.Response).Returns(mockResponse.Object);
            ControllerContext context = new ControllerContext(mockContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
            var result = new RedirectResult(_baseUrl);

            // Act
            result.ExecuteResult(context);

            // Assert
            mockResponse.Verify();
        }
Exemplo n.º 12
0
        public void ProcessResult_WhenCreatedWithValidHandler_ReturnsHandlerUri()
        {
            Url.ApplicationPathProvider = new FakeApplicationPathProvider();

            Tinyweb.Handlers = new[] { new HandlerData { Type = typeof(Resource1Handler), Uri = "uri" } };

            var response = new FakeResponseContext();
            var result = new RedirectResult<Resource1Handler>();

            Assert.That(result.Uri, Is.EqualTo("/uri"));

            result.ProcessResult(null, response);

            Assert.That(response.RedirectUrl, Is.EqualTo("/uri"));
        }
Exemplo n.º 13
0
        public void HandleRedirectResultWithNoControllerName()
        {
            // Setup
            var mvc = new MvcEngine();
            var handler = new RedirectHandler(_mockNavigator.Object);
            var values = new RouteDictionary();
            var result = new RedirectResult
            {
                ControllerName = null,
                ActionName = "Index",
                Values = new RouteDictionary(),
            };

            // Execute
            handler.Handle(mvc, "AnotherTest", result);

            // Assert
            _mockNavigator.Verify(i => i.Navigate("AnotherTest", "Index", values), Times.Once);
        }
Exemplo n.º 14
0
        public void Execute_ReturnsContentPath_WhenItDoesNotStartWithTilde(string appRoot,
                                                                           string contentPath,
                                                                           string expectedPath)
        {
            // Arrange
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.Setup(o => o.Redirect(expectedPath, false))
                        .Verifiable();

            var httpContext = GetHttpContext(appRoot, contentPath, expectedPath, httpResponse.Object);
            var actionContext = GetActionContext(httpContext);
            var result = new RedirectResult(contentPath);

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            // Verifying if Redirect was called with the specific Url and parameter flag.
            httpResponse.Verify();
        }
        public void Should_throw_when_conversiontype_is_incorrect()
        {
            ActionResult result = new RedirectResult("http://mvccontrib.org");

            result.AssertResultIs <EmptyResult>();
        }
Exemplo n.º 16
0
        public void HandleRedirectResultWithNullControllerName()
        {
            // Setup
            var mvc = new MvcEngine();
            var handler = new RedirectHandler(_mockNavigator.Object);
            var values = new RouteDictionary();
            var result = new RedirectResult
            {
                ControllerName = "Test",
                ActionName = "Index",
                Values = new RouteDictionary(),
            };

            // Execute
            handler.Handle(a_mvc: mvc, a_controllerName:null, a_result:result);
        }
Exemplo n.º 17
0
        public void Execute_Calls_TempDataKeep()
        {
            // Arrange
            var tempData = new Mock<ITempDataDictionary>();
            tempData.Setup(t => t.Keep()).Verifiable();

            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary))).Returns(tempData.Object);
            var actionContext = GetActionContext(httpContext.Object);

            var result = new RedirectResult("url")
            {
                UrlHelper = Mock.Of<IUrlHelper>()
            };

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            tempData.Verify(t => t.Keep(), Times.Once());
        }
Exemplo n.º 18
0
        public void RedirectInChildActionThrows()
        {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectResult result = new RedirectResult(_baseUrl);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
                );
        }
Exemplo n.º 19
0
        public void AssertIndexWhenCalledReturnsOkResult()
        {
            RedirectResult response = controller.Index();

            Assert.IsInstanceOf <RedirectResult>(response);
        }
        protected IHttpResponse BuildView(string viewName, IHttpRequest request,
                                          HttpResponseStatusCode responseStatus = HttpResponseStatusCode.Ok)
        {
            var htmlLayoutLoadTask = File.ReadAllTextAsync(Constants.HtmlLayoutPath);
            var htmlBodyLoadTask   = File.ReadAllTextAsync(string.Format(Constants.HtmlBodyPath, viewName));

            foreach (var sessionParameter in request.Session.Parameters)
            {
                viewBag[sessionParameter.Key] = sessionParameter.Value.ToString();
            }
            string pageTitle  = viewName.Split('/', StringSplitOptions.RemoveEmptyEntries)[0];
            string htmlLayout = htmlLayoutLoadTask.Result
                                .Replace(Constants.PageTitlePlaceholder, pageTitle);

            if (viewBag.ContainsKey(Constants.PageErrorPlaceholder))
            {
                htmlLayout = htmlLayout.Replace(Constants.PageBodyPlaceholder,
                                                $"{viewBag[Constants.PageErrorPlaceholder]}\r\n{Constants.PageBodyPlaceholder}");
                viewBag.Remove(Constants.PageErrorPlaceholder);
            }
            string content = htmlLayout.Replace(Constants.PageBodyPlaceholder, htmlBodyLoadTask.Result);

            foreach (var item in viewBag)
            {
                content = content.Replace(item.Key, item.Value);
            }
            IHttpResponse response = null;

            switch (responseStatus)
            {
            case HttpResponseStatusCode.Ok:
                response = new HtmlResult(content, responseStatus);
                break;

            case HttpResponseStatusCode.Created:
                break;

            case HttpResponseStatusCode.Found:
                break;

            case HttpResponseStatusCode.SeeOther:
                response = new RedirectResult(viewName, content);
                break;

            case HttpResponseStatusCode.BadRequest:
                break;

            case HttpResponseStatusCode.Unauthorized:
                break;

            case HttpResponseStatusCode.Forbidden:
                break;

            case HttpResponseStatusCode.NotFound:
                break;

            case HttpResponseStatusCode.InternalServerError:
                break;
            }
            return(response);
        }
Exemplo n.º 21
0
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext.Result != null)
            {
                return;
            }

            if (this.SkipAuthorize(filterContext.ActionDescriptor))
            {
                return;
            }

            //ControllerActionDescriptor controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;

            //if (controllerActionDescriptor == null)
            //    return;

            //List<string> permits = GetAttributes<PermissionAttribute>(controllerActionDescriptor.MethodInfo).Concat(GetAttributes<PermissionAttribute>(controllerActionDescriptor.ControllerTypeInfo)).Where(a => a.Permit.IsNotNullOrEmpty()).Select(a => a.Permit).ToList();

            List <string> permissionCodes = filterContext.ActionDescriptor.FilterDescriptors.Where(a => a.Filter is PermissionAttribute).Select(a => a.Filter as PermissionAttribute).Select(a => a.Code).ToList();

            if (permissionCodes.Count == 0)
            {
                return;
            }

            ResultStatus status = ResultStatus.OK;
            string       msg    = null;

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                //说明处于登录状态,则开始验证当前登录用户是否拥有访问权限
                if (this.HasExecutePermission(filterContext, permissionCodes))
                {
                    return;
                }
                status = ResultStatus.Unauthorized;
                msg    = "抱歉,您无当前操作权限";
            }
            else
            {
                status = ResultStatus.NotLogin;
                msg    = "未登录或登录超时,请重新登录";
            }

            HttpRequest httpRequest = filterContext.HttpContext.Request;

            if (status == ResultStatus.Unauthorized || httpRequest.IsAjaxRequest())
            {
                Result        result        = Result.CreateResult(status, msg);
                string        json          = JsonHelper.Serialize(result);
                ContentResult contentResult = new ContentResult()
                {
                    Content = json
                };
                filterContext.Result = contentResult;
                return;
            }
            else
            {
                string url = filterContext.HttpContext.Content("~/Account/Login");
                url = string.Concat(url, "?returnUrl=", httpRequest.Path);

                RedirectResult redirectResult = new RedirectResult(url);
                filterContext.Result = redirectResult;
                return;
            }
        }
        public void ForUrl_should_throw_if_urls_do_not_match()
        {
            var result = new RedirectResult("http://www.asp.net");

            result.ToUrl("http://mvccontrib.org");
        }
Exemplo n.º 23
0
 public static void AssertView <T>(RedirectResult result)
 {
     result.ShouldNotBeNull();
 }
        public async Task OnPostAsync_GivenCalculationDoesNotAlreadyExist_ReturnsRedirect()
        {
            //Arrange
            CreateCalculationViewModel viewModel = new CreateCalculationViewModel
            {
                Name = "any name"
            };

            Specification specification = CreateSpecification();

            IEnumerable <Reference> allocationLines = new[]
            {
                new Reference
                {
                    Id   = "alloc-id",
                    Name = "alloc-name"
                }
            };

            CalculationCreateModel createModel = new CalculationCreateModel
            {
                SpecificationId = specificationId
            };

            IMapper mapper = CreateMapper();

            mapper
            .Map <CalculationCreateModel>(Arg.Is(viewModel))
            .Returns(createModel);

            ApiResponse <Calculation> calcApiRespnse = new ApiResponse <Calculation>(HttpStatusCode.NotFound);

            ValidatedApiResponse <Calculation> newCalcApiResponse = new ValidatedApiResponse <Calculation>(HttpStatusCode.OK, new Calculation
            {
                Id = "new-calc-id"
            });

            ISpecsApiClient specsClient = CreateSpecsApiClient();

            specsClient
            .GetCalculationBySpecificationIdAndCalculationName(Arg.Is(specificationId), Arg.Is(viewModel.Name))
            .Returns(calcApiRespnse);

            specsClient
            .CreateCalculation(Arg.Is(createModel))
            .Returns(newCalcApiResponse);

            CreateCalculationPageModel pageModel = CreatePageModel(specsClient, mapper);

            pageModel.PageContext = new PageContext();

            pageModel.CreateCalculationViewModel = viewModel;

            //Act
            IActionResult result = await pageModel.OnPostAsync(specificationId);

            //Assert
            result
            .Should()
            .NotBeNull();

            result
            .Should()
            .BeAssignableTo <RedirectResult>();

            RedirectResult redirectResult = result as RedirectResult;

            redirectResult
            .Url
            .Should()
            .Be($"/specs/policies/{specificationId}?operationType=CalculationCreated&operationId=new-calc-id");
        }
        //
        // GET: /Home/
        public async Task <ActionResult> Index()
        {
            // Force SSL
            if (!Request.IsSecureConnection)
            {
                string         httplength   = "http";
                string         nonsecureurl = Request.Url.AbsoluteUri.Substring(httplength.Length);
                string         secureurl    = String.Format("https{0}", nonsecureurl);
                RedirectResult result       = Redirect(secureurl);
                result.ExecuteResult(this.ControllerContext);
            }

            // This is where state of the app is maintained and data passed between view and controller
            AppState appState = new AppState();

            // Authorization back from AAD in a form post as requested in the authorize request
            if (Request.Form != null)
            {
                // Did it return with an error?
                if (!String.IsNullOrEmpty(Request.Form["error"]))
                {
                    appState.ErrorMessage    = Request.Form["error"];
                    appState.AppIsAuthorized = false;

                    return(View(appState));
                }

                // Authorized without error: Check to see if we have an ID token
                if (String.IsNullOrEmpty(Request.Form["id_token"]))
                {
                    appState.AppIsAuthorized = false;
                }
                else
                {
                    // Was it correlated with authorize request
                    var authstate = Session[AppSessionVariables.AuthState] as String;
                    Session[AppSessionVariables.AuthState] = null;
                    if (String.IsNullOrEmpty(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (No auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }
                    if (!Request.Form["state"].Equals(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (Invalid auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }

                    // Get the TenantId out of the ID Token to address tenant specific token endpoint.
                    // No validation of ID Token as the only info we need is the tenantID
                    // If for any case your app wants to use the ID Token to authenticate
                    // it must be validated.
                    JwtToken openIDToken = GetTenantId(Request.Form["id_token"]);
                    appState.TenantId     = openIDToken.tid;
                    appState.TenantDomain = openIDToken.domain;
                    appState.LoggedOnUser = openIDToken.upn;

                    appState.AppIsAuthorized = true;
                }
            }

            if (appState.AppIsAuthorized)
            {
                // Get app-only access tokens ....
                try
                {
                    // Get an app-only access token for the AAD Graph Rest APIs
                    var authResult = await GetAppOnlyAccessToken(appConfig.GraphResourceUri, appState.TenantId);

                    // Get list of users in this Tenant from AAD Graph to fill drop down with smtp addresses
                    List <GraphUser> users = GetUsers(appState.TenantId, authResult.AccessToken);

                    appState.MailboxList        = this.BuildMailboxDropDownList(string.Empty, users);
                    appState.MailboxSmtpAddress = appState.MailboxList.SelectedValue as String;

                    // For convenience maintain this list as a session
                    Session[AppSessionVariables.MailboxList] = users;

                    // Get app-only access tokens for Exchange Rest APIs
                    authResult = await GetAppOnlyAccessToken(appConfig.ExchangeResourceUri, appState.TenantId);

                    appState.AccessToken = authResult.AccessToken;
                    appState.AccessTokenAquiredWithoutError = true;

                    SetSessionInProgress();

                    foreach (SelectListItem item in appState.MailboxList)
                    {
                        FetchInboxData(appState, item.Text.ToString());
                        FetchSendData(appState, item.Text.ToString());
                    }
                }
                catch (Exception ex)
                {
                    appState.ErrorMessage = ex.Message;
                }
            }

            return(View(appState));
        }
Exemplo n.º 26
0
 public static RedirectWithMessageResult WithMessage(this RedirectResult instance, string header, string message)
 => new RedirectWithMessageResult(instance, header, message);
Exemplo n.º 27
0
        public StoresViewModel ModelFromActionResult <T>(ActionResult actionResult)
        {
            object model = null;

            if (actionResult.GetType() == typeof(ViewResult))
            {
                ViewResult      viewResult = (ViewResult)actionResult;
                StoresViewModel TMmodel    = new StoresViewModel();
                Errors          errors     = new Errors();



                if (viewResult.ViewData.ModelState.IsValid == false)
                {
                    foreach (ModelState modelState in viewResult.ViewData.ModelState.Values)
                    {
                        foreach (System.Web.Mvc.ModelError error in modelState.Errors)
                        {
                            errors.message = error.ErrorMessage;
                            TMmodel.errors = errors;
                            model          = TMmodel;
                        }
                    }
                }
                else
                {
                    model = viewResult.Model;
                }
            }
            else if (actionResult.GetType() == typeof(PartialViewResult))
            {
                PartialViewResult partialViewResult = (PartialViewResult)actionResult;
                model = partialViewResult.Model;
            }
            else if (actionResult.GetType() == typeof(RedirectResult))
            {
                RedirectResult  partialViewResult = (RedirectResult)actionResult;
                StoresViewModel TMmodel           = new StoresViewModel();
                Errors          errors            = new Errors();

                //if (partialViewResult.RouteValues.ContainsKey("message"))
                //{
                //    errors.message = (string)partialViewResult.RouteValues["message"];
                //}

                //if (partialViewResult.RouteValues.ContainsKey("statuscode"))
                //{
                //    errors.statuscode = (int)partialViewResult.RouteValues["statuscode"];
                //}


                TMmodel.errors = errors;
                model          = TMmodel;
                //errors.message = partialViewResult.RouteValues[1];
            }
            else
            {
                throw new InvalidOperationException(string.Format("Actionresult of type {0} is not supported by ModelFromResult extractor.", actionResult.GetType()));
            }


            return((StoresViewModel)model);
        }
Exemplo n.º 28
0
    protected override Task ExecuteAsync(HttpContext httpContext, string contentPath)
    {
        var redirectResult = new RedirectResult(contentPath, false, false);

        return(redirectResult.ExecuteAsync(httpContext));
    }
        public void BeRedirect_GivenRedirect_ShouldPass()
        {
            ActionResult result = new RedirectResult("/");

            result.Should().BeRedirectResult();
        }
Exemplo n.º 30
0
        public void TestSairRedirecionamento()
        {
            RedirectResult resultado = controller.Sair() as RedirectResult;

            Assert.AreEqual("~/", resultado.Url);
        }
Exemplo n.º 31
0
        public ActionResult SubmitButton()
        {
            ActionResult result;

            try
            {
                if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
                {
                    result = RedirectToRoute("Login");
                }
                else
                {
                    IEnumerable <ShoppingCartItem> shoppingCartItems = _workContext.CurrentCustomer.ShoppingCartItems;
                    List <ShoppingCartItem>        list =
                        shoppingCartItems.Where(item => item.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
                    if (list.Count == 0)
                    {
                        result = RedirectToRoute("ShoppingCart");
                    }
                    else
                    {
                        string currencyCode =
                            _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                        var curencies = _p24PaymentSettings.Currencies.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
                        if (!curencies.Contains(currencyCode))
                        {
                            throw new ApplicationException("Privat24. currency is not supported. (only  UAH, USD, EUR)");
                        }
                        if (string.IsNullOrEmpty(_p24PaymentSettings.MerchantId))
                        {
                            throw new ApplicationException("Privat24. merchant_id is not set");
                        }
                        if (string.IsNullOrEmpty(_p24PaymentSettings.MerchantSignature))
                        {
                            throw new ApplicationException("Privat24. merchant_sig is not set");
                        }

                        var privat24PaymentProcessor = _paymentService.LoadPaymentMethodBySystemName("Nop.Payments.Privat24") as Privat24PaymentProcessor;
                        if (privat24PaymentProcessor == null ||
                            !privat24PaymentProcessor.IsPaymentMethodActive(_paymentSettings) ||
                            !privat24PaymentProcessor.PluginDescriptor.Installed)
                        {
                            throw new NopException("Privat24 module cannot be loaded");
                        }

                        var processPaymentRequest = new ProcessPaymentRequest
                        {
                            PaymentMethodSystemName = "Nop.Payments.Privat24",
                            CustomerId = _workContext.CurrentCustomer.Id
                        };

                        ProcessPaymentRequest processPaymentRequest2 = processPaymentRequest;
                        PlaceOrderResult      placeOrderResult       = _orderProcessingService.PlaceOrder(processPaymentRequest2);
                        if (!placeOrderResult.Success)
                        {
                            privat24PaymentProcessor.LogMessage(string.Format("CreateOrder() error: {0}",
                                                                              placeOrderResult));
                            result = RedirectToRoute("ShoppingCart");
                        }
                        else
                        {
                            Order placedOrder = placeOrderResult.PlacedOrder;
                            if (placedOrder == null)
                            {
                                privat24PaymentProcessor.LogMessage("order==null");
                                result = RedirectToRoute("ShoppingCart");
                            }
                            else
                            {
                                privat24PaymentProcessor.LogMessage("create new order: Order Number " + placedOrder.Id);
                                string text = privat24PaymentProcessor.CreateFormPrivat24(placedOrder.Id,
                                                                                          placedOrder.OrderTotal);
                                result = new RedirectResult(text);
                            }
                        }
                    }
                }
            }
            catch (Exception arg)
            {
                result = Content("Error: " + arg);
            }
            return(result);
        }
Exemplo n.º 32
0
 /// <summary>
 /// Converts a redirect result action into a client side script location change instruction wrapped in HTML.
 /// Useful for delivering a client side redirect action in an HTML payload.
 /// </summary>
 /// <param name="redirectResult"></param>
 /// <returns></returns>
 public static string MakeRedirectHtmlPayload(RedirectResult redirectResult)
 {
     return(JavaScriptHelper.BuildJavaScriptTag(null, MakeRedirectJsAction(redirectResult), false).ToString(TagRenderMode.Normal));
 }
Exemplo n.º 33
0
        protected virtual Task <object> GetLoginResult(RequestContext context)
        {
            var result = new RedirectResult("/login", Status.SeeOther);

            return(Task.FromResult <object>(result));
        }
Exemplo n.º 34
0
 /// <summary>
 /// Converts a redirect result action into a client side script location change instruction.
 /// </summary>
 /// <param name="redirectResult"></param>
 /// <returns></returns>
 public static string MakeRedirectJsAction(RedirectResult redirectResult)
 {
     return(string.Format("window.location = \"{0}\";", redirectResult.Url));
 }
Exemplo n.º 35
0
        public IHttpResponse PostRegister(IHttpRequest request)
        {
            var userName        = request.FormData["username"].ToString().Trim();
            var password        = request.FormData["password"].ToString();
            var confirmPassword = request.FormData["confirmPassword"].ToString();
            var email           = request.FormData["email"].ToString();

            //Validate
            if (string.IsNullOrWhiteSpace(userName) || userName.Length < 4)
            {
                return(new BadRequestResult("Please provide valid username with length of 4 or more characters.", HttpResponseStatusCode.Unauthorized));
            }

            if (this.Context.Users.Any(x => x.Username == userName))
            {
                return(new BadRequestResult("User with the same name already exists.", HttpResponseStatusCode.Unauthorized));
            }
            if (this.Context.Users.Any(x => x.Email == email))
            {
                return(new BadRequestResult("User with the same Email already exists.", HttpResponseStatusCode.Unauthorized));
            }
            if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
            {
                return(new BadRequestResult("Please provide password of length 6 or more.", HttpResponseStatusCode.Unauthorized));
            }
            if (string.IsNullOrWhiteSpace(email))
            {
                return(new BadRequestResult("Please add an Email.", HttpResponseStatusCode.Unauthorized));
            }

            if (password != confirmPassword)
            {
                return(new BadRequestResult("Passwords do not match.", HttpResponseStatusCode.SeeOther));
            }

            // Hash password
            var hashedPassword = this.hashService.Hash(password);

            // Create user
            var user = new User
            {
                Username = userName,
                Password = hashedPassword,
                Email    = email
            };

            this.Context.Users.Add(user);

            try
            {
                this.Context.SaveChanges();
            }
            catch (Exception e)
            {
                // TODO: Log error
                return(new BadRequestResult(e.Message, HttpResponseStatusCode.InternalServerError));
            }

            // TODO: Login
            var response = new RedirectResult("/");

            this.SignInUser(userName, request, response);
            // Redirect
            return(response);
        }
Exemplo n.º 36
0
 public static WrappedActionResultWithFlash <RedirectResult> WithFlash([NotNull] this RedirectResult instance, [NotNull] IDictionary <string, string> arguments)
 {
     return(Flash(instance, arguments));
 }
Exemplo n.º 37
0
 /// <summary>
 /// Creates a cookie containing a "flash message" to be shown on the client-side (after following the redirect)
 /// </summary>
 /// <param name="result"></param>
 /// <param name="messageClass"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 public static RedirectResult WithFlashMessage(this RedirectResult result, string messageClass, string message)
 {
     return(WithFlashMessage <RedirectResult>(result, messageClass, message));
 }
Exemplo n.º 38
0
 public static WrappedActionResultWithFlash <RedirectResult> WithFlash([NotNull] this RedirectResult instance, object arguments)
 {
     return(Flash(instance, ToDictionary(arguments)));
 }
        public void Process(IProcessedRedirect processedRedirect)
        {
            // skip processed redirect if it's invalid or contains one or more of skip result types
            if (!processedRedirect.ParsedRedirect.IsValid ||
                processedRedirect.Results
                .Select(r => r.Type)
                .Distinct()
                .Count(r => _skipResultTypes.Contains(r, StringComparer.OrdinalIgnoreCase)) > 0)
            {
                return;
            }

            var checkRedirect    = false;
            var isCyclicRedirect = false;
            var redirectCount    = -1;
            var urlsIndex        = new HashSet <string>();
            var redirectsVisited = new List <IParsedRedirect>();

            string url    = null;
            string newUrl =
                processedRedirect.ParsedRedirect.OldUrl.Formatted;
            string            lastVisitedUrl;
            UrlResponseResult urlResponseResult = null;

            var urlsVisited = new List <string>(new [] { newUrl });

            do
            {
                url    = newUrl;
                newUrl = null;

                var urlFormatted = _urlHelper.FormatUrl(url);

                redirectCount++;
                checkRedirect = false;

                // get response from url
                HttpResponse response;
                if (_responseCache.ContainsKey(urlFormatted))
                {
                    // get response from cache
                    response = _responseCache[urlFormatted];
                }
                else
                {
                    // get response from url
                    response = _httpClient.Get(urlFormatted);

                    // add response to cache
                    _responseCache.Add(urlFormatted, response);
                }

                lastVisitedUrl = url;

                // set has redirect and url to response location,
                // if url returns 301 and has location
                if (response != null)
                {
                    var statusCode = response.StatusCode;

                    string locationUrl;
                    if (response.Headers.ContainsKey("Location"))
                    {
                        var location = response.Headers["Location"] ?? string.Empty;

                        locationUrl = !Regex.IsMatch(
                            location ?? string.Empty, "^https?://", RegexOptions.IgnoreCase | RegexOptions.Compiled)
                            ? _urlHelper.Combine(url, location)
                            : location ?? string.Empty;
                    }
                    else
                    {
                        locationUrl = string.Empty;
                    }

                    urlResponseResult = new UrlResponseResult
                    {
                        Type    = ResultTypes.UrlResponse,
                        Message = string.Format(
                            "Url '{0}' returned response with status code '{1}'",
                            url,
                            statusCode),
                        Url        = url,
                        StatusCode = statusCode,
                        Location   = locationUrl
                    };

                    switch (response.StatusCode)
                    {
                    case 301:
                    case 302:
                        // url returns 301 or 302
                        // update redirect with url from location
                        newUrl = locationUrl;
                        break;

                    case 404:
                        // url returns 404, check if a redirect exists
                        checkRedirect = true;
                        break;

                    default:
                        // urls not returning 301 or 404 are considered a url with a response
                        // stop redirecting
                        url = null;
                        break;
                    }
                }
                else
                {
                    urlResponseResult = null;
                }

                // check redirect for url
                var matchingRedirectResult = GetMatchingRedirect(urlFormatted);
                if (checkRedirect &&
                    matchingRedirectResult.HasMatch)
                {
                    redirectsVisited.Add(
                        matchingRedirectResult.ParsedRedirect);

                    if (matchingRedirectResult.ResultRedirectType == RedirectType.Replace)
                    {
                        // update redirect with new url from replaced redirect
                        newUrl = _redirectHelper.Replace(urlFormatted,
                                                         matchingRedirectResult.ParsedRedirect);
                    }
                    else
                    {
                        // update redirect with new url from existing redirect
                        newUrl = matchingRedirectResult.ParsedRedirect.NewUrl.Formatted;
                    }
                }

                // add new url to urls visited, if not null
                if (!string.IsNullOrWhiteSpace(newUrl))
                {
                    urlsVisited.Add(newUrl);
                }

                // cyclic redirect, if url and new url is not https redirect and url exists in url index
                if (newUrl != null && !_urlHelper.IsHttpsRedirect(
                        url,
                        newUrl) &&
                    urlsIndex.Contains(_urlHelper.FormatUrl(newUrl)))
                {
                    isCyclicRedirect = true;
                    break;
                }

                // add formatted url to urls index, if it doesn't exist
                if (!urlsIndex.Contains(urlFormatted))
                {
                    urlsIndex.Add(urlFormatted);
                }
            } while (!string.IsNullOrWhiteSpace(newUrl) &&
                     redirectCount < 20);

            // add url response result, if it's defined
            if (urlResponseResult != null)
            {
                processedRedirect.Results.Add(
                    urlResponseResult);
                _results.Add(urlResponseResult);
            }

            if (isCyclicRedirect)
            {
                // add cyclic redirect result
                var cyclicResult = new RedirectResult
                {
                    Type    = ResultTypes.CyclicRedirect,
                    Message =
                        string.Format(
                            "Cyclic redirect at url '{0}'",
                            lastVisitedUrl),
                    Url              = lastVisitedUrl,
                    RedirectCount    = redirectCount,
                    UrlsVisited      = urlsVisited,
                    RedirectsVisited = redirectsVisited
                };
                processedRedirect.Results.Add(
                    cyclicResult);
                _results.Add(cyclicResult);
            }
            else if (redirectCount >= _configuration.MaxRedirectCount)
            {
                // add too many redirects result as redirect count is
                // higher then max redirect count
                var tooManyRedirectsResult = new RedirectResult
                {
                    Type    = ResultTypes.TooManyRedirects,
                    Message = string.Format(
                        "Too many redirect at url '{0}' exceeding max redirect count of {1}",
                        lastVisitedUrl,
                        _configuration.MaxRedirectCount),
                    Url              = lastVisitedUrl,
                    RedirectCount    = redirectCount,
                    UrlsVisited      = urlsVisited,
                    RedirectsVisited = redirectsVisited
                };
                processedRedirect.Results.Add(
                    tooManyRedirectsResult);
                _results.Add(
                    tooManyRedirectsResult);
            }
            else if (redirectCount > 1 && redirectCount < _configuration.MaxRedirectCount)
            {
                // add optimized redirect result as redirect count is higher than 1
                // and less than max redirect count
                var optimizedRedirectResult = new RedirectResult
                {
                    Type    = ResultTypes.OptimizedRedirect,
                    Message = string.Format(
                        "Optimized redirect to url '{0}'",
                        lastVisitedUrl),
                    Url              = lastVisitedUrl,
                    RedirectCount    = redirectCount,
                    UrlsVisited      = urlsVisited,
                    RedirectsVisited = redirectsVisited
                };
                processedRedirect.Results.Add(
                    optimizedRedirectResult);
                _results.Add(
                    optimizedRedirectResult);
            }
        }
Exemplo n.º 40
0
        public ActionResult SubmitButton()
        {
            try
            {
                //user validation
                if ((Services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                {
                    return(RedirectToRoute("Login"));
                }

                var store    = Services.StoreContext.CurrentStore;
                var customer = Services.WorkContext.CurrentCustomer;
                var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(store.Id);
                var cart     = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id);

                if (cart.Count == 0)
                {
                    return(RedirectToRoute("ShoppingCart"));
                }

                if (String.IsNullOrEmpty(settings.ApiAccountName))
                {
                    throw new ApplicationException("PayPal API Account Name is not set");
                }
                if (String.IsNullOrEmpty(settings.ApiAccountPassword))
                {
                    throw new ApplicationException("PayPal API Password is not set");
                }
                if (String.IsNullOrEmpty(settings.Signature))
                {
                    throw new ApplicationException("PayPal API Signature is not set");
                }

                var provider  = PaymentService.LoadPaymentMethodBySystemName(PayPalExpressProvider.SystemName, true);
                var processor = provider != null ? provider.Value as PayPalExpressProvider : null;
                if (processor == null)
                {
                    throw new SmartException("PayPal Express Checkout module cannot be loaded");
                }

                var processPaymentRequest = new PayPalProcessPaymentRequest();

                processPaymentRequest.StoreId = store.Id;

                //Get sub-total and discounts that apply to sub-total
                decimal  orderSubTotalDiscountAmountBase = decimal.Zero;
                Discount orderSubTotalAppliedDiscount    = null;
                decimal  subTotalWithoutDiscountBase     = decimal.Zero;
                decimal  subTotalWithDiscountBase        = decimal.Zero;

                _orderTotalCalculationService.GetShoppingCartSubTotal(cart,
                                                                      out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);

                //order total
                decimal resultTemp = decimal.Zero;
                resultTemp += subTotalWithDiscountBase;

                //Get discounts that apply to Total
                Discount appliedDiscount = null;
                var      discountAmount  = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount);

                //if the current total is less than the discount amount, we only make the discount equal to the current total
                if (resultTemp < discountAmount)
                {
                    discountAmount = resultTemp;
                }

                //reduce subtotal
                resultTemp -= discountAmount;

                if (resultTemp < decimal.Zero)
                {
                    resultTemp = decimal.Zero;
                }

                decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase;

                resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, Services.WorkContext.WorkingCurrency);
                if (tempDiscount > decimal.Zero)
                {
                    tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, Services.WorkContext.WorkingCurrency);
                }

                processPaymentRequest.PaymentMethodSystemName = PayPalExpressProvider.SystemName;
                processPaymentRequest.OrderTotal         = resultTemp;
                processPaymentRequest.Discount           = tempDiscount;
                processPaymentRequest.IsRecurringPayment = false;

                //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id);

                processPaymentRequest.CustomerId = Services.WorkContext.CurrentCustomer.Id;
                this.Session["OrderPaymentInfo"] = processPaymentRequest;

                var resp = processor.SetExpressCheckout(processPaymentRequest, cart);

                if (resp.Ack == AckCodeType.Success)
                {
                    processPaymentRequest.PaypalToken         = resp.Token;
                    processPaymentRequest.OrderGuid           = new Guid();
                    processPaymentRequest.IsShippingMethodSet = ControllerContext.RouteData.IsRouteEqual("ShoppingCart", "Cart");
                    this.Session["OrderPaymentInfo"]          = processPaymentRequest;

                    _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, PayPalExpressProvider.SystemName, store.Id);

                    var result = new RedirectResult(String.Format(settings.GetPayPalUrl() + "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token));

                    return(result);
                }
                else
                {
                    var error = new StringBuilder("We apologize, but an error has occured.<br />");
                    foreach (var errormsg in resp.Errors)
                    {
                        error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage));
                    }

                    Logger.InsertLog(LogLevel.Error, resp.Errors[0].ShortMessage, resp.Errors[0].LongMessage, customer);

                    NotifyError(error.ToString(), false);

                    return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
                }
            }
            catch (Exception ex)
            {
                Logger.InsertLog(LogLevel.Error, ex.Message, ex.StackTrace, Services.WorkContext.CurrentCustomer);

                NotifyError(ex.Message, false);

                return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
            }
        }
        public async Task OnPostAsync_GivenViewModelIsValid_ReturnsRedirect()
        {
            //Arrange
            const string specName = "spec name";

            CreateSpecificationModel createModel = new CreateSpecificationModel
            {
                Name             = specName,
                Description      = "description",
                FundingStreamIds = new[] { "fs1" },
                FundingPeriodId  = "fp1"
            };

            ApiResponse <Specification> existingSpecificationResponse = new ApiResponse <Specification>(HttpStatusCode.NotFound);

            ISpecsApiClient apiClient = CreateApiClient();

            apiClient
            .GetSpecificationByName(Arg.Is(specName))
            .Returns(existingSpecificationResponse);

            Specification createdSpecification = new Specification()
            {
                Id = "specId",
            };

            apiClient
            .CreateSpecification(Arg.Any <CreateSpecificationModel>())
            .Returns(new ValidatedApiResponse <Specification>(HttpStatusCode.OK, createdSpecification));

            IMapper mapper = CreateMapper();

            mapper
            .Map <CreateSpecificationModel>(Arg.Any <CreateSpecificationViewModel>())
            .Returns(createModel);

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <IEnumerable <string> >(), Arg.Is(FundingStreamActionTypes.CanCreateSpecification))
            .Returns(true);

            CreateSpecificationPageModel pageModel = CreatePageModel(apiClient, mapper, authorizationHelper);

            pageModel.CreateSpecificationViewModel = new CreateSpecificationViewModel
            {
                Name             = specName,
                Description      = "description",
                FundingStreamIds = new[] { "fs1" },
                FundingPeriodId  = "fp1"
            };

            //Act
            IActionResult result = await pageModel.OnPostAsync();

            //Assert
            result
            .Should()
            .BeOfType <RedirectResult>();

            RedirectResult redirectResult = result as RedirectResult;

            redirectResult
            .Url
            .Should()
            .Be("/specs/policies/specId?operationType=SpecificationCreated&operationId=specId");
        }
Exemplo n.º 42
0
 public static IActionResult DisplayView(this Controller controller, string viewName, RedirectResult result)
 {
     return(controller.Redirect(result.Url));
 }
Exemplo n.º 43
0
 protected virtual Task<object> GetLoginResult()
 {
     var result = new RedirectResult("/login", Status.SeeOther);
     return Task.FromResult<object>(result);
 }
        //参考文章 https://www.cnblogs.com/yaopengfei/p/11232921.html

        /// <summary>
        /// 权限过滤器
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //匿名标识 无需验证
            if (context.Filters.Any(e => (e as AllowAnonymous) != null))
            {
                return;
            }

            string userId   = context.HttpContext.Session.GetString("LoginUserId");
            string userName = context.HttpContext.Session.GetString("LoginUserName");

            if (string.IsNullOrEmpty(userId))
            {
                if (IsAjaxRequest(context.HttpContext.Request))
                {
                    //是ajax请求
                    context.Result = new JsonResult(new { status = "error", message = "你没有登录" });
                }
                else
                {
                    var result = new RedirectResult("~/Account/Login");
                    context.Result = result;
                }
                return;
            }
            if (!string.IsNullOrEmpty(userName) && userName.Equals("admin"))
            {
                return;
            }

            //对应action方法或者Controller上若存在NonePermissionAttribute标识,即表示为管理员的默认权限,只要登录就有权限
            var isNone = context.Filters.Any(e => (e as NonePermissionAttribute) != null);

            if (isNone)
            {
                return;
            }

            //获取请求的区域,控制器,action名称
            var area       = context.RouteData.DataTokens["area"]?.ToString();
            var controller = context.RouteData.Values["controller"]?.ToString();
            var action     = context.RouteData.Values["action"]?.ToString();
            var isPermit   = false;

            //校验权限
            //isPermit = ServiceFactory.CheckAdminPermit(adminInfo.Id, area, controller, action);
            if (isPermit)
            {
                return;
            }

            //此action方法的父辈权限判断,只要有此action对应的父辈权限,皆有权限访问
            var pAttrs = context.Filters.Where(e => (e as ParentPermissionAttribute) != null).ToList();

            if (pAttrs.Count > 0)
            {
                foreach (ParentPermissionAttribute pattr in pAttrs)
                {
                    if (!string.IsNullOrEmpty(pattr.Area))
                    {
                        area = pattr.Area;
                    }
                    //isPermit = ServiceFactory.CheckAdminPermit(adminInfo.Id, area, pattr.Controller, pattr.Action);
                    if (isPermit)
                    {
                        return;
                    }
                }
            }
            if (!isPermit)
            {
                context.Result = new ContentResult()
                {
                    Content = "无权限访问"
                };
                return;
            }

            #region 另一种校验思路

            //string allowAttrName = typeof(AllowAnonymousAttribute).ToString();
            //string attrName = typeof(CheckPermissionAttribute).ToString();
            ////所有目标对象上所有特性
            //var data = context.ActionDescriptor.EndpointMetadata.ToList();
            //bool isHasAttr = false;
            ////循环比对是否含有skip特性
            ////如果action带有允许匿名访问的特性,则直接返回,不再进行安全认证
            //if (data.Any(r => r.ToString().Equals(allowAttrName, StringComparison.OrdinalIgnoreCase)))
            //{
            //    return;
            //}

            //data.ForEach(i => i.ToString().Equals(attrName, StringComparison.OrdinalIgnoreCase));
            //foreach (var item in data)
            //{
            //    if (data.ToString().Equals(attrName))
            //    {
            //        isHasAttr = true;
            //    }
            //}

            ////1. 校验是否标记跨过登录验证
            //if (isHasAttr)
            //{
            //    //表示该方法或控制器跨过登录验证
            //    //继续走控制器中的业务即可
            //}
            //else
            //{
            //    //2.判断是什么请求,进行响应的页面跳转
            //    //PS:根据request.Headers["X-Requested-With"]是否包含XMLHttpRequest来判断是不是ajax请求。
            //    if (IsAjaxRequest(context.HttpContext.Request))
            //    {
            //        //是ajax请求
            //        context.Result = new JsonResult(new { status = "error", message = "你没有权限" });
            //    }
            //    else
            //    {
            //        var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
            //        context.Result = result;
            //    }

            //}

            #endregion



            //获取区域、控制器、Action的名称
            //方法1
            //context.ActionDescriptor.RouteValues["area"].ToString();
            //context.ActionDescriptor.RouteValues["controller"].ToString();
            //context.ActionDescriptor.RouteValues["action"].ToString();
            //方法2
            //context.RouteData.Values["controller"].ToString();
            //context.RouteData.Values["action"].ToString();
            //string actionName = context.RouteData.Values["action"].ToString();
            //if (context.HttpContext.User.Identity.Name != "admin")
            //{
            //    //未通过验证则跳转到无权限提示页
            //    RedirectToActionResult content = new RedirectToActionResult("NoAuth", "Exception", null);
            //    context.Result = content;
            //}

            #region .net fraemwork 版本
            ////获得当前要执行的Action上标注的CheckPermissionAttribute实例对象
            //CheckPermissionAttribute[] permAtts = (CheckPermissionAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckPermissionAttribute), false);
            //if (permAtts.Length <= 0)//没有标注任何的CheckPermissionAttribute,因此也就不需要检查是否登录
            //                         //“无欲无求”
            //{
            //    return;//登录等这些不要求有用户登录的功能
            //}
            ////得到当前登录用户的id
            //long? userId = (long?)filterContext.HttpContext.Session["LoginUserId"];
            //if (userId == null)//连登录都没有,就不能访问
            //{
            //    // filterContext.HttpContext.Response.Write("没有登录");
            //    //filterContext.HttpContext.Response.Redirect();

            //    //根据不同的请求,给予不同的返回格式。确保ajax请求,浏览器端也能收到json格式
            //    if (filterContext.HttpContext.Request.IsAjaxRequest())
            //    {
            //        AjaxResult ajaxResult = new AjaxResult();
            //        ajaxResult.Status = "redirect";
            //        ajaxResult.Data = "/Main/Login";
            //        ajaxResult.ErrorMsg = "没有登录";
            //        filterContext.Result = new JsonNetResult { Data = ajaxResult };
            //    }
            //    else
            //    {
            //        filterContext.Result = new RedirectResult("~/Main/Login");
            //    }
            //    //filterContext.Result = new ContentResult() { Content= "没有登录" };
            //    return;
            //}
            ////由于ZSZAuthorizeFilter不是被autofac创建,因此不会自动进行属性的注入
            ////需要手动获取Service对象
            //IAdminUserService userService =
            //    DependencyResolver.Current.GetService<IAdminUserService>();

            ////检查是否有权限
            //foreach (var permAtt in permAtts)
            //{
            //    //判断当前登录用户是否具有permAtt.Permission权限
            //    //(long)userId   userId.Value
            //    if (!userService.HasPermission(userId.Value, permAtt.Permission))
            //    {
            //        //只要碰到任何一个没有的权限,就禁止访问
            //        //在IAuthorizationFilter里面,只要修改filterContext.Result
            //        //那么真正的Action方法就不会执行了
            //        if (filterContext.HttpContext.Request.IsAjaxRequest())
            //        {
            //            AjaxResult ajaxResult = new AjaxResult();
            //            ajaxResult.Status = "error";
            //            ajaxResult.ErrorMsg = "没有权限" + permAtt.Permission;
            //            filterContext.Result = new JsonNetResult { Data = ajaxResult };
            //        }
            //        else
            //        {
            //            filterContext.Result
            //           = new ContentResult { Content = "没有" + permAtt.Permission + "这个权限" };
            //        }
            //        return;
            //    }
            //}
            #endregion
        }
        public ActionResult SendToPaymentProvider(
            PaymentProviderConfiguration configuration,
            GeneralisedPaymentTransfer transferObject,
            Action <PaymentProviderConfiguration, GeneralisedPaymentTransfer, string> saveProviderReference)
        {
            int siteId;

            int.TryParse(configuration.AccountIdentifer, out siteId);

            int scpId;

            int.TryParse(transferObject.Account, out scpId);

            int    hmacKeyId;
            string hmacSecretKey;

            CapitaApiHelpers.GetHmacIdAndSecretKey(configuration.SharedSecret, out hmacKeyId, out hmacSecretKey);

            string returnUrl = $"{transferObject.ReturnUrl}?{RoundTripTokenKey}={transferObject.TransactionId}";

            CapitaInvokeRequest request = new CapitaInvokeRequest()
            {
                SiteId              = siteId,
                ScpId               = scpId,
                HmacKeyId           = hmacKeyId,
                HmacKey             = hmacSecretKey,
                UniqueReference     = transferObject.TransactionId,
                PurchaseId          = transferObject.ProductId,
                BookingRef          = transferObject.Comment2,
                PurchaseDescription = transferObject.Comment1,
                PaymentTotal        = (int)(transferObject.Amount * 100),
                ReturnUrl           = returnUrl,
                IntegraCode         = transferObject.GeneralLedgerCode,
                IsMediated          = transferObject.IsMediated,
                FundCode            = Shared.Capita.Default.FundCode,
                VatCode             = transferObject.VatCode,
                VatRate             = transferObject.VatRate
            };

            if (transferObject.SaveCard != null)
            {
                request.SaveCard     = true;
                request.CardHolderId = MessageContentUtility.TruncateAndStripDisallowed(transferObject.SaveCard.PayerReference, 50, null);
            }

            //Call Capita web service to set up the payment
            CapitaInvokeResponse response = InvokeRequest(request);

            if (response != null && !response.Error)
            {
                //call this action method to save scpReference into PendingPayment table
                saveProviderReference(configuration, transferObject, response.ScpReference);
                RedirectResult resultView = new RedirectResult(response.RedirectUrl, true);
                var            sendToPaymentLogMessage = PaymentFrameworkUtility.DescribeActionResultForLogging(resultView, true);
                this.Logger.CreateEntry(typeof(CapitaPaymentProvider), LogLevel.Info, sendToPaymentLogMessage);
                return(resultView);
            }
            else
            {
                string errorMessage = "Capita Server returns null response.";
                if (response != null)
                {
                    errorMessage += " " + response.ErrorMessage;
                }

                this.Logger.CreateEntry(typeof(CapitaPaymentProvider), LogLevel.Error, errorMessage);
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 46
0
 public RedirectResultAssertions(RedirectResult redirectResult)
 {
     _redirectResult = redirectResult;
 }
Exemplo n.º 47
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                /// <summary>
                /// Se obtiene el contexto de datos
                /// </summary>
                /// <returns></returns>
                /// con
                var httpContext = context.HttpContext;

                /// <summary>
                /// Se obtiene el path solicitado
                /// </summary>
                /// <returns></returns>
                var request = httpContext.Request;


                /// <summary>
                /// Se obtiene información del usuario autenticado
                /// </summary>
                /// <returns></returns>
                var claim         = context.HttpContext.User.Identities.Where(x => x.NameClaimType == ClaimTypes.Name).FirstOrDefault();
                var token         = claim.Claims.Where(c => c.Type == ClaimTypes.SerialNumber).FirstOrDefault().Value;
                var NombreUsuario = claim.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

                var permiso = new PermisoUsuario
                {
                    Contexto = request.Path,
                    Token    = token,
                    Usuario  = NombreUsuario,
                };

                /// <summary>
                /// Se valida que la información del usuario actual tenga permiso para acceder al path solicitado...
                /// </summary>
                /// <returns></returns>
                var respuestaToken = apiServicio.ObtenerElementoAsync1 <Response>(permiso, new Uri(WebApp.BaseAddressSeguridad), "api/Adscpassws/ExisteToken");

                if (!respuestaToken.Result.IsSuccess)
                {
                    context.HttpContext.Authentication.SignOutAsync("Cookies");
                    foreach (var cookie in context.HttpContext.Request.Cookies.Keys)
                    {
                        context.HttpContext.Response.Cookies.Delete(cookie);
                    }
                    var result = new ViewResult {
                        ViewName = "SeccionCerrada"
                    };
                    context.Result = result;
                }
                else
                {
                    var respuesta = apiServicio.ObtenerElementoAsync1 <Response>(permiso, new Uri(WebApp.BaseAddressSeguridad), "api/Adscpassws/TienePermiso");

                    //respuesta.Result.IsSuccess = true;
                    if (!respuesta.Result.IsSuccess)
                    {
                        var result = new ViewResult {
                            ViewName = "AccesoDenegado"
                        };
                        context.Result = result;
                    }
                }
            }
            catch (Exception ex)
            {
                var result = new RedirectResult(WebApp.BaseAddressWebAppLogin);
                foreach (var cookie in context.HttpContext.Request.Cookies.Keys)
                {
                    context.HttpContext.Response.Cookies.Delete(cookie);
                }
                context.Result = result;
            }
        }
            public void Redirects_To_Correct_File()
            {
                RedirectResult result = (RedirectResult)this.controller.GetScript("test");

                Assert.Equal($"/test.js?{this.lastUpdate.ToString("yyyyMMddHHmmss")}", result.Url);
            }