Exemplo n.º 1
0
 public void PermanentRedirect()
 {
     var response = new RedirectResponse("/", RedirectResponse.RedirectType.Permanent);
     response.Headers.Should().Contain("Location", "/");
     response.Body.AsString().Should().BeEmpty();
     response.StatusCode.Should().Be(HttpStatusCode.MovedPermanently);
 }
Exemplo n.º 2
0
        public static async Task <IHttpResponse> PostAsync(
            [Property(Name = id_token)] string idToken,
            [Property(Name = state)] IRef <Authorization> authorization,
            IAzureApplication application, IProvideUrl urlHelper,
            IHttpRequest request, IInvokeApplication endpoints,
            RedirectResponse onRedirectResponse,
            ServiceUnavailableResponse onNoServiceResponse,
            BadRequestResponse onBadCredentials,
            GeneralConflictResponse onFailure)
        {
            var parameters = new Dictionary <string, string>
            {
                { id_token, idToken },
                { state, authorization.id.ToString("N") },
            };
            var method = EastFive.Azure.Auth.Method.ByMethodName(
                AzureADB2CProvider.IntegrationName, application);

            return(await EastFive.Azure.Auth.Redirection.ProcessRequestAsync(method, parameters,
                                                                             application, request, endpoints, urlHelper,
                                                                             (redirect, accountIdMaybe) => onRedirectResponse(redirect),
                                                                             (why) => onBadCredentials().AddReason($"Bad credentials:{why}"),
                                                                             (why) => onNoServiceResponse().AddReason(why),
                                                                             (why) => onFailure(why)));
        }
Exemplo n.º 3
0
 public void TemporaryRedirect()
 {
     var response = new RedirectResponse("/", RedirectResponse.RedirectType.Temporary);
     response.Headers.Should().Contain("Location", "/");
     response.Body.AsString().Should().BeEmpty();
     response.StatusCode.Should().Be(HttpStatusCode.TemporaryRedirect);
 }
Exemplo n.º 4
0
        public override RedirectResponse Request(RedirectRequest redirectRequest)
        {
            try
            {
                this._action = "/createRequest";

                string request = Serializer.JsonSerializer.SerializeObject(redirectRequest);

                var node = JsonConvert.DeserializeXmlNode(request, "payload");

                XElement createRequest = new XElement(p2p + "createRequest", XElement.Parse(node.OuterXml));

                string response = this.CallWebService(createRequest);

                JObject res  = JObject.Parse(response);
                var     data = res["ns1:createRequestResponse"]["createRequestResult"];

                return(JsonConvert.DeserializeObject <RedirectResponse>(data.ToString()));
            }
            catch (Exception ex)
            {
                Status           status           = new Status("ERROR", "WR", PlacetoPayException.ReadException(ex), (DateTime.Now).ToString("yyyy-MM-ddTHH\\:mm\\:sszzz"));
                RedirectResponse redirectResponse = new RedirectResponse(null, null, status);

                return(redirectResponse);
            }
        }
Exemplo n.º 5
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = StatePropertyName)] string state,
     [QueryParameter(Name = ClientPropertyName)] IRef <Client> clientRef,
     [QueryParameter(Name = ValidationPropertyName)] string validation,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     //ContentTypeResponse<Authentication> onFound,
     RedirectResponse onFound,
     ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
 {
     return(await await clientRef.StorageGetAsync(
                (client) =>
     {
         var authentication = new Authentication
         {
             authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
             state = state,
         };
         return authentication.StorageCreateAsync(
             (entity) =>
         {
             var location = urlHelper.GetLocation <Authentication>(
                 auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                 application);
             return onFound(location);
         },
             () => throw new Exception("Secure guid not unique"));
     },
                () => onInvalidClient().AsTask()));
 }
Exemplo n.º 6
0
        /**
         * Creates a login failed response.
         *
         * @param string user
         * @param string originalUser
         * @param string redirect_url
         * @param string loginMessage
         *
         * @return RedirectResponse
         */
        private RedirectResponse createLoginFailedResponse(
            string user, string originalUser, string redirect_url, string loginMessage)
        {
            // Read current user and append if possible we need to
            // return the unmodified user otherwise we will leak the login name
            var args = user != null
                ? new Dictionary <string, string>()
            {
                { "user", originalUser }
            }
                : new Dictionary <string, string>();

            if (redirect_url != null)
            {
                args["redirect_url"] = redirect_url;
            }

            var response = new RedirectResponse(
                this.urlGenerator.linkToRoute("core.login.showLoginForm", args)
                );

            response.throttle(new Dictionary <string, string> {
                { "user", user.Substring(0, 64) }
            });
            this.session.set("loginMessages", new List <string>
            {
                "", loginMessage, ""
            });
            return(response);
        }
Exemplo n.º 7
0
        public async Task <RedirectResponse> NavigatesAsync(RedirectRequest model)
        {
            var response = new RedirectResponse();

            try
            {
                Item entity = await _itemQueryHandler.GetBySegmentAsync(model.Segment);

                if (entity != null && !string.IsNullOrWhiteSpace(entity.OriginUrl))
                {
                    // logging history to the DB
                    await _statisticCommandHandler.ExecuteAsync(new CreateStatisticCommand
                    {
                        IpAddress = model.IpAddress,
                        ItemId    = entity.Id
                    });

                    response.IsSuccess = true;
                    response.OriginUrl = entity.OriginUrl;
                }
            }
            catch (Exception exception)
            {
                response.IsSuccess = false;
                response.Message   = exception.Message;
            }
            return(response);
        }
        /// <summary>
        /// Método CrearOrdenPedido.
        /// </summary>
        /// <returns>Task{Orders}</returns>
        public async Task <Orders> CrearOrdenPedido(Orders ordenPedido, string direccionIP, string agenteUsuario)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            var gateWay = new P2P(ConfigurationManager.AppSettings["Login_Ws_PlaceToPay"],
                                  ConfigurationManager.AppSettings["TranKey_Ws_PlaceToPay"],
                                  new Uri(ConfigurationManager.AppSettings["Url_Ws_PlaceToPay"]), Gateway.TP_REST);
            Amount  montoPago            = new Amount(TOTAL_PAGO);
            Payment pagoPedido           = new Payment(PRODUCTO, PRODUCTO, montoPago);
            var     tiempoExpiracionPago = DateTime.Now.AddMinutes(10);

            ordenPedido.OrderStatus = await this.tiendaVirtualRepositorio.ProcesarEstadoOrden(ESTADOINICIALORDEN);

            ordenPedido.Status_Id  = ordenPedido.OrderStatus.Id;
            ordenPedido.Created_At = DateTime.Now;
            this.tiendaVirtualRepositorio.Insertar(ordenPedido);
            var             urlRedireccionamientoLocal  = string.Format("{0}/{1}{2}", ordenPedido.UrlRaiz, "ordenes/visualizarestado/false/", ordenPedido.Id);
            RedirectRequest solicitudRedireccionamiento = new RedirectRequest(pagoPedido, urlRedireccionamientoLocal, direccionIP,
                                                                              agenteUsuario, tiempoExpiracionPago.ToString("s", CultureInfo.InvariantCulture));

            solicitudRedireccionamiento.Buyer = new Person(string.Empty, string.Empty, ordenPedido.Customer_Name,
                                                           string.Empty, ordenPedido.Customer_Email, mobile: ordenPedido.Customer_Mobile);
            solicitudRedireccionamiento.Locale    = "es_CO";
            solicitudRedireccionamiento.CancelUrl = urlRedireccionamientoLocal;
            RedirectResponse response = gateWay.Request(solicitudRedireccionamiento);

            if (response.Status.status != ESTADO_OK_CREACION_ORDENPEDIDO)
            {
                this.tiendaVirtualRepositorio.Eliminar(ordenPedido);
                throw new Exception(response.Status.Message);
            }
            ordenPedido.Request_Id       = response.RequestId;
            ordenPedido.UrlProcesamiento = response.ProcessUrl;
            this.tiendaVirtualRepositorio.Actualizar(ordenPedido);
            return(await Task.FromResult(ordenPedido));
        }
Exemplo n.º 9
0
        public async static Task <HttpResponseMessage> XlsPostAsync(EastFive.Security.SessionServer.Context context,
                                                                    ContentBytes sheet, [QueryParameter] Guid integration, IDictionary <string, bool> resourceTypes,
                                                                    HttpRequestMessage request, System.Web.Http.Routing.UrlHelper url,
                                                                    RedirectResponse onSuccess,
                                                                    NotFoundResponse onNotFound,
                                                                    GeneralConflictResponse onError)
        {
            var sheetId = Guid.NewGuid();

            return(await await context.Integrations.UpdateAsync(integration,
                                                                sheet.content.MD5HashGuid().ToString("N"),
                                                                new Dictionary <string, string>()
            {
                { "resource_types", resourceTypes.SelectKeys().Join(",") },
                { "sheet_id", sheetId.ToString("N") },
            },
                                                                (redirectUrl) =>
            {
                return EastFive.Api.Azure.Credentials.Sheets.SaveAsync(sheetId, sheet.contentType.MediaType, sheet.content, integration,
                                                                       context.DataContext,
                                                                       () => onSuccess(redirectUrl),
                                                                       "Guid not unique".AsFunctionException <HttpResponseMessage>());
            },
                                                                () => onNotFound().ToTask(),
                                                                () => onError("The provided integration ID has not been connected to an authorization.").ToTask()));
        }
Exemplo n.º 10
0
        private static Func <NancyContext, Response> RequiresHttps(bool redirect, int?httpsPort)
        {
            return((ctx) =>
            {
                Response response = null;
                var request = ctx.Request;
                if (!request.Url.IsSecure)
                {
                    if (redirect && request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
                    {
                        var redirectUrl = request.Url.Clone();
                        redirectUrl.Port = httpsPort;
                        redirectUrl.Scheme = "https";
                        response = new RedirectResponse(redirectUrl.ToString());
                    }
                    else
                    {
                        response = new Response {
                            StatusCode = HttpStatusCode.Forbidden
                        };
                    }
                }

                return response;
            });
        }
Exemplo n.º 11
0
 public static async Task <HttpResponseMessage> CreateResponseAsync(
     [QueryParameter(Name = "login_process_id")] Guid credentialProcessId,
     [OptionalQueryParameter(Name = "ApiKeySecurity")] string apiSecurityKey,
     ApiSecurity apiSecurity,
     EastFive.Api.Azure.AzureApplication application, HttpRequestMessage request,
     RedirectResponse redirectResponse,
     ViewStringResponse viewResponse)
 {
     return(await await CredentialProcessDocument.FindByIdAsync(credentialProcessId,
                                                                async (document) =>
     {
         var providerKvp = await application.AuthorizationProviders
                           .Where(prov => prov.Value.GetType().FullName == document.Provider)
                           .FirstAsync(
             value => value,
             () => default(KeyValuePair <string, IProvideAuthorization>));
         var provider = providerKvp.Value;
         Enum.TryParse(document.Action, out AuthenticationActions action);
         return await ResponseController.CreateResponse(application, provider, document.Method, action,
                                                        document.SessionId, document.AuthorizationId, document.Token, document.RefreshToken,
                                                        document.GetValuesCredential(), request.RequestUri,
                                                        document.RedirectUrl.IsNullOrWhiteSpace(
                                                            () => null,
                                                            redirUrlString => new Uri(redirUrlString)),
                                                        (redirectUri, message) => redirectResponse(redirectUri),
                                                        (code, message, reason) => viewResponse($"<html><head><title>{reason}</title></head><body>{message}</body></html>", null),
                                                        application.Telemetry);
     },
                                                                () => viewResponse("", null).AsTask(),
                                                                BlackBarLabs.Persistence.Azure.StorageTables.AzureStorageRepository.CreateRepository(
                                                                    EastFive.Azure.AppSettings.ASTConnectionStringKey)));
 }
Exemplo n.º 12
0
        public IHttpResponse RegisterPost(IHttpRequest req)
        {
            var user = new User();

            try
            {
                if (req.FormData["password"] != req.FormData["confirmPassword"])
                {
                    throw new Exception("Passwords must match.");
                }

                user.Email    = req.FormData["email"];
                user.FullName = req.FormData["fullName"];
                user.Password = req.FormData["password"];
                user.IsAdmin  = false;
            }
            catch
            {
                return(new ViewResponse(HttpStatusCode.NotAuthorized, new RegisterView(true)));
            }

            service.Add(user);
            var response = new RedirectResponse("/");

            req.Session.Add("UserId", service.LastUserId());


            return(response);
        }
        private static Func<NancyContext, Response> RequiresHttpsOrXForwardedProto(bool redirect)
        {
            return ctx =>
            {
                Response response = null;
                Request request = ctx.Request;

                if (!IsSecure(request))
                {
                    if (redirect && request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
                    {
                        Url redirectUrl = request.Url.Clone();
                        redirectUrl.Scheme = "https";
                        redirectUrl.Port = 443;
                        response = new RedirectResponse(redirectUrl.ToString());
                    }
                    else
                    {
                        response = new Response {StatusCode = HttpStatusCode.Forbidden};
                    }
                }

                return response;
            };
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Payment(int idOrden)
        {
            var order = await _ordersService.GetOrder(idOrden);

            if (order == null)
            {
                return(NotFound());
            }

            Gateway gateway = _ordersService.GetGateway();

            Person person = new Person(
                document: order.CustomerDocument,
                documentType: "CC",
                name: order.CustomerName,
                surname: order.CustomerName.Replace(" ", ""),
                email: order.CustomerEmail,
                mobile: order.CustomerMobile
                );

            Amount amount = new Amount(Convert.ToDouble(order.ValorOrder), currency);

            PlacetoPay.Integrations.Library.CSharp.Entities.Payment payment = new PlacetoPay.Integrations.Library.CSharp.Entities.Payment($"TEST_{DateTime.Now:yyyyMMdd_hhmmss}_{order.Id}", $"Pago básico de prueba orden {order.Id} ", amount, false, person);
            RedirectRequest request = new RedirectRequest(payment,
                                                          urlLocalhostDetails + order.Id.ToString(),
                                                          ipAddress,
                                                          "PlacetoPay Sandbox",
                                                          (order.CreatedAt.AddMinutes(60)).ToString(formatDate),
                                                          person,
                                                          person);

            RedirectResponse response = gateway.Request(request);

            if (response.IsSuccessful())
            {
                Models.Payment pago = new Models.Payment()
                {
                    OrderId   = order.Id,
                    Fecha     = Convert.ToDateTime(response.Status.Date),
                    RequestId = Convert.ToInt32(response.RequestId),
                    UrlPago   = response.ProcessUrl,
                    Status    = response.Status.status,
                    Reason    = response.Status.Reason,
                    Message   = response.Status.Message
                };

                if (await _paymentsService.CreatePayment(pago) == 0)
                {
                    // NotFound Response Status 404.
                    return(NotFound());
                }


                return(RedirectToAction("Payment", "Orders", new { idOrden = order.Id, urlPago = response.ProcessUrl }));
            }
            else
            {
                return(RedirectToAction("Details", "Orders", new { id = order.Id, message = response.Status.Message }));
            }
        }
Exemplo n.º 15
0
        public IHttpResponse Login(IHttpRequest request, LoginViewModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Username) ||
                string.IsNullOrWhiteSpace(model.Password))
            {
                this.AddError("You have empty fields");

                return(this.FileViewResponse("/login"));
            }

            var success = this.users.FindUser(model.Username, model.Password);

            if (success)
            {
                this.LoginUser(request, model.Username);
                var response = new RedirectResponse("/");
                return(response);
            }
            else
            {
                this.AddError("Invalid user details!");
                this.ViewData["authDisplay"] = "none";

                return(this.FileViewResponse("/login"));
            }
        }
        public IPaymentResponse Charge(PaymentRequest request)
        {
            var dic = new Dictionary <string, object>();

            dic.Add("amt_tran", request.TotalAmount.ToString());
            var currency = GetCurrencyCode(request.Currency);

            dic.Add("tran_currency", currency);
            dic.Add("purchase_id", DataHelper.GeneratePurchaseId(request.Id));
            var preferences = new Dictionary <string, string>
            {
                { "success_url", PaymentHelper.GetCallbackUrl(this, nameof(CheckoutFinished), Context) },
                { "failure_url", Setting.FailureUrl }
            };

            dic.Add("preferences", preferences);
            var result = QualpayAPI.CheckOutUrl(dic, Setting);

            if (result == null)
            {
                return(null);
            }
            var redirectUrl      = result["checkout_link"];
            RedirectResponse res = new RedirectResponse(redirectUrl, request.Id);

            return(res);
        }
Exemplo n.º 17
0
 public void DefaultRedirect()
 {
     var response = new RedirectResponse("/");
     response.Headers.Should().Contain("Location", "/");
     response.Body.AsString().Should().BeEmpty();
     response.StatusCode.Should().Be(HttpStatusCode.SeeOther);
 }
        public static async Task <IHttpResponse> Get(
            [OptionalQueryParameter(Name = ProvideLoginMock.extraParamState)] IRefOptional <Authorization> authorizationRef,
            [QueryParameter(Name = ProvideLoginMock.extraParamToken)] string token,
            IAzureApplication application, IProvideUrl urlHelper,
            IHttpRequest request,
            RedirectResponse redirectResponse,
            ServiceUnavailableResponse onNoServiceResponse,
            BadRequestResponse onBadCredentials,
            GeneralConflictResponse onFailure)
        {
            var authentication = EastFive.Azure.Auth.Method.ByMethodName(
                ProvideLoginMock.IntegrationName, application);
            var parameters = new Dictionary <string, string>()
            {
                { ProvideLoginMock.extraParamToken, token },
            };

            if (authorizationRef.HasValue)
            {
                parameters.Add(ProvideLoginMock.extraParamState, authorizationRef.id.ToString());
            }

            return(await Redirection.ProcessRequestAsync(authentication,
                                                         parameters,
                                                         application,
                                                         request, urlHelper,
                                                         (redirect) =>
            {
                var response = redirectResponse(redirect);
                return response;
            },
                                                         (why) => onBadCredentials().AddReason($"Bad credentials:{why}"),
                                                         (why) => onNoServiceResponse().AddReason(why),
                                                         (why) => onFailure(why)));
        }
Exemplo n.º 19
0
        public void Constructor_WithLocationUrl_ShouldReturnAResponseWithCorrectHeader()
        {
            var response = new RedirectResponse("http://google.com");

            Assert.That(response.Headers.Keys, Contains.Item("Location"));
            Assert.That(response.Headers["Location"], Is.EqualTo("http://google.com"));
        }
Exemplo n.º 20
0
        public IntegratedAuthenticationModule(ILog log, IAuthCookieCreator tokenIssuer, IApiActionResponseCreator responseCreator, IWebPortalConfigurationStore webPortalConfigurationStore)
        {
            Get[DirectoryServicesConstants.ChallengePath] = c =>
            {
                if (Context.CurrentUser == null)
                {
                    return(responseCreator.Unauthorized(Request));
                }

                var principal   = (IOctopusPrincipal)Context.CurrentUser;
                var authCookies = tokenIssuer.CreateAuthCookies(Context.Request, principal.IdentificationToken, SessionExpiry.TwentyMinutes);

                var      whitelist = webPortalConfigurationStore.GetTrustedRedirectUrls();
                Response response;
                if (Request.Query["redirectTo"].HasValue && Requests.IsLocalUrl(Request.Query["redirectTo"].Value, whitelist))
                {
                    var redirectLocation = Request.Query["redirectTo"].Value;
                    response = new RedirectResponse(redirectLocation).WithCookies(authCookies);
                }
                else
                {
                    if (Request.Query["redirectTo"].HasValue)
                    {
                        log.WarnFormat("Prevented potential Open Redirection attack on an NTLM challenge, to the non-local url {0}", Request.Query["redirectTo"].Value);
                    }

                    response = new RedirectResponse(Request.Url.BasePath ?? "/").WithCookies(authCookies);
                }

                return(response);
            };
        }
 public static async Task <HttpResponseMessage> GetAllSecureAsync(
     [QueryParameter(Name = "ApiKeySecurity")] string apiSecurityKey,
     [QueryParameter(Name = "authorization")] IRef <Authorization> authorizationRef,
     ApiSecurity apiSecurity,
     AzureApplication application,
     HttpRequestMessage request,
     MultipartResponseAsync <Authorization> onContent,
     RedirectResponse onSuccess,
     NotFoundResponse onNotFound,
     ForbiddenResponse onFailure)
 {
     return(await await authorizationRef.StorageGetAsync(
                async authorization =>
     {
         return await await Method.ById(authorization.Method, application,
                                        async method =>
         {
             return await await method.ParseTokenAsync(authorization.parameters, application,
                                                       (externalId, loginProvider) =>
             {
                 return Auth.Redirection.ProcessAsync(authorization,
                                                      async updatedAuth =>
                 {
                 }, method, externalId, authorization.parameters,
                                                      Guid.NewGuid(), request.RequestUri, application, loginProvider,
                                                      (uri) => onSuccess(uri),
                                                      (why) => onFailure().AddReason(why),
                                                      application.Telemetry);
             },
                                                       why => onFailure().AddReason(why).AsTask());
         },
                                        () => onFailure().AddReason("Method no longer supported").AsTask());
     },
                () => onNotFound().AsTask()));
 }
Exemplo n.º 22
0
        public IntegratedAuthenticationModule(ILog log, IAuthCookieCreator tokenIssuer, IApiActionResponseCreator responseCreator, IWebPortalConfigurationStore webPortalConfigurationStore)
        {
            Get[DirectoryServicesConstants.ChallengePath] = c =>
            {
                if (Context.CurrentUser == null)
                {
                    return(responseCreator.Unauthorized(Request));
                }

                var principal   = (IOctopusPrincipal)Context.CurrentUser;
                var tokenCookie = tokenIssuer.CreateAuthCookie(Context, principal.IdentificationToken, false);

                var directoryPathResult = Request.AbsoluteVirtualDirectoryPath();
                if (!directoryPathResult.IsValid)
                {
                    return(responseCreator.BadRequest(directoryPathResult.InvalidReason));
                }

                var      whitelist = webPortalConfigurationStore.GetTrustedRedirectUrls();
                Response response;
                if (Request.Query["redirectTo"].HasValue && Requests.IsLocalUrl(directoryPathResult.Path, Request.Query["redirectTo"].Value, whitelist))
                {
                    var redirectLocation = Request.Query["redirectTo"].Value;
                    response = new RedirectResponse(redirectLocation).WithCookie(tokenCookie);
                }
                else
                {
                    log.WarnFormat("Prevented potential Open Redirection attack on an NTLM challenge from the local instance {0} to the non-local url {1}", directoryPathResult.Path, Request.Query["redirectTo"].Value);
                    response = new RedirectResponse(directoryPathResult.Path ?? "/").WithCookie(tokenCookie);
                }

                return(response);
            };
        }
Exemplo n.º 23
0
        public void DefaultRedirect()
        {
            var response = new RedirectResponse("/");

            response.Headers.Should().Contain("Location", "/");
            response.Body.AsString().Should().BeEmpty();
            response.StatusCode.Should().Be(HttpStatusCode.SeeOther);
        }
Exemplo n.º 24
0
        public void TemporaryRedirect()
        {
            var response = new RedirectResponse("/", RedirectResponse.RedirectType.Temporary);

            response.Headers.Should().Contain("Location", "/");
            response.Body.AsString().Should().BeEmpty();
            response.StatusCode.Should().Be(HttpStatusCode.TemporaryRedirect);
        }
Exemplo n.º 25
0
        public void PermanentRedirect()
        {
            var response = new RedirectResponse("/", RedirectResponse.RedirectType.Permanent);

            response.Headers.Should().Contain("Location", "/");
            response.Body.AsString().Should().BeEmpty();
            response.StatusCode.Should().Be(HttpStatusCode.MovedPermanently);
        }
Exemplo n.º 26
0
        public void Should_add_location_header_to_the_message_when_response_contains_a_api_resource()
        {
            var uri = new Uri("http://example.com");

            var response = new RedirectResponse(uri);

            AssertExpectedStatus(response);
            response.Headers.Location.ShouldEqual(uri);
        }
Exemplo n.º 27
0
        public void Redirection_Response_Without_Status()
        {
            var carrierResponse = new RedirectResponse(new JObject {
                { "requestId", new Random().Next(0, 100000) },
                { "processUrl", "http://localhost/payment/process" },
            });

            Assert.False(carrierResponse.IsSuccessful());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Logs the user out and redirects them to a URL
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="redirectUrl">URL to redirect to</param>
        /// <returns>Nancy response</returns>
        public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl)
        {
            var response             = new RedirectResponse(redirectUrl);
            var authenticationCookie = BuildLogoutCookie(currentConfiguration);

            response.AddCookie(authenticationCookie);

            return(response);
        }
Exemplo n.º 29
0
        public IHttpResponse Logout(IHttpRequest req)
        {
            var response = new RedirectResponse("/");

            req.Cookies.ClearCookies();
            req.Session.Clear();
            response.CookieCollection.ClearCookies();

            return(response);
        }
        /// <summary>
        /// Redirect to provided URL.
        /// </summary>
        /// <param name="url">The URL to redirect.</param>
        /// <param name="closeServerConnection">Close the server connection used by request if any?</param>
        public void Redirect(string url, bool closeServerConnection = false)
        {
            var response = new RedirectResponse();

            response.HttpVersion = WebSession.Request.HttpVersion;
            response.Headers.AddHeader(KnownHeaders.Location, url);
            response.Body = emptyData;

            Respond(response, closeServerConnection);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Redirect to URL.
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task Redirect(string url)
        {
            var response = new RedirectResponse();

            response.HttpVersion = WebSession.Request.HttpVersion;
            response.Headers.AddHeader("Location", url);
            response.Body = new byte[0];

            await Respond(response);
        }
        public void CrearSubcribcion()
        {
            string email, nombre, apellido, espagador;

            email     = "*****@*****.**";
            nombre    = "Daniel";
            apellido  = "betancur";
            espagador = "no";

            try
            {
                Gateway      gateway     = CrearAutenticacion();
                Amount       amount      = new Amount(20000.002);
                string       referencia  = "pruebasd_" + db.Transaccions.ToList().Count();
                Subscription subcripcion = new Subscription(referencia, "No hay descripcion");
                Transaccion  transaccion = new Transaccion();
                transaccion.Id = db.Transaccions.ToList().Count() + 1;
                if (nombre != null && email != null && apellido != null)
                {
                    RedirectRequest request;
                    Person          buyer = new Person("10000004", "CC", nombre, apellido, email);
                    if (espagador == "on")
                    {
                        Person payer = new Person("10000004", "CC", nombre, apellido, email);
                        request = new RedirectRequest(subcripcion,
                                                      "http://localhost:63562/Transacciones/returnURL" + "?" + "id=" + transaccion.Id,
                                                      "192.168.0.2",
                                                      "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
                                                      (DateTime.Now).AddMinutes(40).ToString("yyyy-MM-ddTHH\\:mm\\:sszzz"), payer, buyer);
                    }
                    else
                    {
                        request = new RedirectRequest(subcripcion,
                                                      "http://localhost:63562/Transacciones/returnURL" + "?" + "id=" + transaccion.Id,
                                                      "192.168.0.2",
                                                      "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
                                                      (DateTime.Now).AddMinutes(40).ToString("yyyy-MM-ddTHH\\:mm\\:sszzz"), null, buyer);
                    }
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    RedirectResponse response = gateway.Request(request);
                    transaccion.requestId  = response.RequestId;
                    transaccion.URL        = response.ProcessUrl;
                    transaccion.referencia = referencia;
                    db.Transaccions.Add(transaccion);
                    db.SaveChanges();
                    Response.Redirect(response.ProcessUrl);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: '{0}'", e);
            }
        }
Exemplo n.º 33
0
        public async Task Redirect(string url)
        {
            var response = new RedirectResponse();

            response.HttpVersion = WebSession.Request.HttpVersion;
            response.ResponseHeaders.Add("Location", new Models.HttpHeader("Location", url));
            response.ResponseBody = Encoding.ASCII.GetBytes(string.Empty);

            await Respond(response);

            WebSession.Request.CancelRequest = true;
        }
Exemplo n.º 34
0
        public void Redirection_Response_With_Status()
        {
            var carrierResponse = new RedirectResponse(new JObject {
                { "requestId", new Random().Next(0, 100000) },
                { "processUrl", "http://localhost/payment/process" },
                { "status", new JObject {
                      { "status", "OK" }, { "reason", 2 }, { "message", "Aprobada" }, { "date", "2019-03-10T12:36:36-05:00" }
                  } }
            });

            Assert.True(carrierResponse.IsSuccessful());
        }
Exemplo n.º 35
0
 public RedirectResponseTests()
 {
     Response = new RedirectResponse("https://github.com/bberak");
 }
Exemplo n.º 36
0
        /// <summary>
        /// Creates a response that sets the authentication cookie and redirects
        /// the user back to where they came from.
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="userIdentifier">User identifier guid</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param>
        /// <returns>Nancy response</returns>
        public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = "/")
        {
            var redirectUrl = fallbackRedirectUrl;

            if (context.Request.Query[REDIRECT_QUERYSTRING_KEY].HasValue)
            {
                redirectUrl = context.Request.Query[REDIRECT_QUERYSTRING_KEY];
            }

            var response = new RedirectResponse(redirectUrl);
            var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
            response.AddCookie(authenticationCookie);

            return response;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Logs the user out and redirects them to a URL
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="redirectUrl">URL to redirect to</param>
        /// <returns>Nancy response</returns>
        public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl)
        {
            var response = new RedirectResponse(redirectUrl);
            var authenticationCookie = BuildLogoutCookie(currentConfiguration);
            response.AddCookie(authenticationCookie);

            return response;
        }