예제 #1
0
        public ActionResult SignIn(LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }

            var result = _authenticationService.Login(Sanitizer.GetSafeHtmlFragment(login.Username), Sanitizer.GetSafeHtmlFragment(login.Password), true);

            if (result == null)
            {
                ModelState.AddModelError("", "Invalid Password!");
                return(JsonValidationError());
            }
            else
            {
                //returnURL needs to be decoded
                string decodedUrl = string.Empty;
                string returnUrl  = TempData["ReturnUrl"] != null ? TempData["ReturnUrl"].ToString() : "";
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    if (returnUrl.ToLower().Contains("passwordrecovery"))
                    {
                        returnUrl = "";
                    }
                }
                decodedUrl = Server.UrlDecode(returnUrl);
                var resp = new BoolResponse {
                    IsValid = true, MessageCode = result.SessionId, Message = result.FirstName, ReturnUrl = decodedUrl
                };
                SiteUtils.SetBasketAction(resetAction: true);
                return(JsonSuccess(resp, JsonRequestBehavior.AllowGet));
            }
        }
예제 #2
0
        // [ValidateInput(false)]
        public ActionResult Registration(RegisterViewModel register)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }
            if (!string.IsNullOrEmpty(register.Password))
            {
                if (!Regex.IsMatch(register.Password, SiteUtils.GetPasswordRegex()))
                {
                    ModelState.AddModelError("Password", "Password does not meet policy!");
                    return(JsonValidationError());
                }
            }
            var response = new BoolResponse();
            //-- to check if user's Email Address already registered
            var existingUser = _customerRepository.GetExistingUser(Sanitizer.GetSafeHtmlFragment(register.Email));

            if (existingUser.Result != null)
            {
                if (existingUser.Result.Count > 0 && existingUser.Result[0].UserSourceType != UserSourceTypes.Newsletter.GetHashCode().ToString())
                {
                    ModelState.AddModelError("Error", "Your email address is already registered with us.");
                    return(JsonValidationError());
                }
                var user = new CustomerModel
                {
                    Email    = Sanitizer.GetSafeHtmlFragment(register.Email),
                    Password = Sanitizer.GetSafeHtmlFragment(register.Password)
                };
                var result = _customerRepository.Register(user);
                if (result.Result.IsValid)
                {
                    var loginResult = _authenticationService.Login(Sanitizer.GetSafeHtmlFragment(register.Email), Sanitizer.GetSafeHtmlFragment(register.Password), true);
                    response.IsValid = true;
                    SiteUtils.SetBasketAction(resetAction: true);
                    return(JsonSuccess(response, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    ModelState.AddModelError("Error", "Registration failed!");
                    return(JsonValidationError());
                }
            }
            else
            {
                ModelState.AddModelError("Error", " '+' Symbol is not allowed in Email!");
                return(JsonValidationError());
            }
        }
예제 #3
0
 public static string RemoveHtml(string content)
 {
     return(Sanitizer.GetSafeHtmlFragment(content));
 }
예제 #4
0
        /// <summary>
        /// Takes in HTML and returns santized Html/string
        /// </summary>
        /// <param name="html"></param>
        /// <param name="useXssSantiser"></param>
        /// <returns></returns>
        public static string ScrubHtml(string html, bool useXssSantiser = false)
        {
            if (string.IsNullOrEmpty(html))
            {
                return(html);
            }

            // clear the flags on P so unclosed elements in P will be auto closed.
            HtmlNode.ElementsFlags.Remove("p");

            var doc = new HtmlDocument();

            doc.LoadHtml(html);

            var finishedHtml = html;

            // Embed Urls
            if (doc.DocumentNode != null)
            {
                // Get all the links we are going to
                var tags = doc.DocumentNode.SelectNodes("//a[contains(@href, 'youtube.com')]|//a[contains(@href, 'youtu.be')]|//a[contains(@href, 'vimeo.com')]|//a[contains(@href, 'screenr.com')]|//a[contains(@href, 'instagram.com')]");

                if (tags != null)
                {
                    // find formatting tags
                    foreach (var item in tags)
                    {
                        if (item.PreviousSibling == null)
                        {
                            // Prepend children to parent node in reverse order
                            foreach (var node in item.ChildNodes.Reverse())
                            {
                                item.ParentNode.PrependChild(node);
                            }
                        }
                        else
                        {
                            // Insert children after previous sibling
                            foreach (var node in item.ChildNodes)
                            {
                                item.ParentNode.InsertAfter(node, item.PreviousSibling);
                            }
                        }

                        // remove from tree
                        item.Remove();
                    }
                }


                //Remove potentially harmful elements
                var nc = doc.DocumentNode.SelectNodes("//script|//link|//iframe|//frameset|//frame|//applet|//object|//embed");
                if (nc != null)
                {
                    foreach (var node in nc)
                    {
                        node.ParentNode.RemoveChild(node, false);
                    }
                }

                //remove hrefs to java/j/vbscript URLs
                nc = doc.DocumentNode.SelectNodes("//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
                if (nc != null)
                {
                    foreach (var node in nc)
                    {
                        node.SetAttributeValue("href", "#");
                    }
                }

                //remove img with refs to java/j/vbscript URLs
                nc = doc.DocumentNode.SelectNodes("//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
                if (nc != null)
                {
                    foreach (var node in nc)
                    {
                        node.SetAttributeValue("src", "#");
                    }
                }

                //remove on<Event> handlers from all tags
                nc = doc.DocumentNode.SelectNodes("//*[@onclick or @onmouseover or @onfocus or @onblur or @onmouseout or @ondblclick or @onload or @onunload or @onerror]");
                if (nc != null)
                {
                    foreach (var node in nc)
                    {
                        node.Attributes.Remove("onFocus");
                        node.Attributes.Remove("onBlur");
                        node.Attributes.Remove("onClick");
                        node.Attributes.Remove("onMouseOver");
                        node.Attributes.Remove("onMouseOut");
                        node.Attributes.Remove("onDblClick");
                        node.Attributes.Remove("onLoad");
                        node.Attributes.Remove("onUnload");
                        node.Attributes.Remove("onError");
                    }
                }

                // remove any style attributes that contain the word expression (IE evaluates this as script)
                nc = doc.DocumentNode.SelectNodes("//*[contains(translate(@style, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'expression')]");
                if (nc != null)
                {
                    foreach (var node in nc)
                    {
                        node.Attributes.Remove("stYle");
                    }
                }

                // build a list of nodes ordered by stream position
                var pos = new NodePositions(doc);

                // browse all tags detected as not opened
                foreach (var error in doc.ParseErrors.Where(e => e.Code == HtmlParseErrorCode.TagNotOpened))
                {
                    // find the text node just before this error
                    var last = pos.Nodes.OfType <HtmlTextNode>().LastOrDefault(n => n.StreamPosition < error.StreamPosition);
                    if (last != null)
                    {
                        // fix the text; reintroduce the broken tag
                        last.Text = error.SourceText.Replace("/", "") + last.Text + error.SourceText;
                    }
                }

                finishedHtml = doc.DocumentNode.WriteTo();
            }


            // The reason we have this option, is using the santiser with the MarkDown editor
            // causes problems with line breaks.
            if (useXssSantiser)
            {
                return(SanitizerCompatibleWithForiegnCharacters(Sanitizer.GetSafeHtmlFragment(finishedHtml)));
            }

            return(finishedHtml);
        }
예제 #5
0
        // GET: Checkout
        public ActionResult OnePageCheckout(string basketId)
        {
            var response = _checkoutApi.Checkout(Sanitizer.GetSafeHtmlFragment(basketId));
            var checkout = response.Result;

            if (checkout.BasketId == null || checkout.Basket == null || checkout.Basket.LineItems.Count < 1)
            {
                return(RedirectToAction("BasketNotFound", "Common"));
            }
            foreach (var pay in checkout.PaymentOptions)
            {
                pay.CardInfo.Amount = checkout.BalanceAmount.Raw.WithTax;
            }
            var result = _configApi.GetConfig();
            var data   = result.Result;

            //checkout.Basket.shippingMethods = 0  is simpl check this implementation later
            data.ShippingCountries = data.ShippingCountries.Where(x => checkout.Basket.shippingMethods.Any(y => y.CountryCode == x.TwoLetterIsoCode) || checkout.Basket.shippingMethods.Count() == 0).Distinct().ToList();
            var model = new CheckoutViewModel
            {
                Checkout          = checkout,
                Register          = new RegistrationModel(),
                Login             = new LoginViewModel(),
                BillingCountries  = data.BillingCountries,
                ShippingCountries = data.ShippingCountries,
                CurrentDate       = DateTime.Today.Date.AddDays(1)
            };

            if (_sessionContext.CurrentUser == null)
            {
                model.RegistrationPrompt = Convert.ToBoolean(_sessionContext.CurrentSiteConfig.BasketSettings.RegistrationPrompt);
            }

            string returnUrl = string.Empty;

            //So that the user can be referred back to where they were when they click logon
            if (Request.UrlReferrer != null)
            {
                returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
            }

            //if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
            if (!string.IsNullOrEmpty(returnUrl))
            {
                TempData["ReturnURL"] = returnUrl;
            }
            if (_sessionContext.CurrentUser == null)
            {
                if (Guid.Parse(checkout.CustomerId) != Guid.Empty)
                {
                    var customerresult = _customerRepository.GetUserdetailsById <CustomerDetailModel>(checkout.CustomerId);
                    if (customerresult != null)
                    {
                        checkout.Email     = customerresult.Result.Email;
                        checkout.CompanyId = customerresult.Result.CompanyId;
                    }
                }
                else
                {
                    _checkoutApi.UpdateUserToBasket(checkout.BasketId, Guid.Empty.ToString());
                    checkout.Stage = BasketStage.Anonymous.GetHashCode();
                }
                SetDataLayerVariables(response.Result?.Basket, WebhookEventTypes.CheckoutStarted);
                return(View(CustomViews.ONE_PAGE_CHECKOUT, model));
            }
            model.Checkout.CustomerId = _sessionContext.CurrentUser.UserId.ToString();
            model.Checkout.Email      = _sessionContext.CurrentUser.Email;
            var WishlistResponse = _customerRepository.GetWishlist(model.Checkout.CustomerId, true);

            model.Checkout.WishlistProducts = WishlistResponse.Result;
            SetDataLayerVariables(response.Result?.Basket, WebhookEventTypes.CheckoutStarted);
            return(View(CustomViews.ONE_PAGE_CHECKOUT, model));
        }
예제 #6
0
        public ActionResult RemoveWishList(string id)
        {
            _customerRepository.RemoveWishList(_sessionContext.CurrentUser.UserId.ToString(), Sanitizer.GetSafeHtmlFragment(id), true);
            var response = _customerRepository.GetWishlist(_sessionContext.CurrentUser.UserId.ToString(), true);

            return(JsonSuccess(response.Result, JsonRequestBehavior.AllowGet));
        }
예제 #7
0
        public ActionResult UpdateBasketDeliveryAddress(CheckoutModel checkout)
        {
            var response = _checkoutApi.UpdateBasketDeliveryAddress(Sanitizer.GetSafeHtmlFragment(checkout.BasketId), checkout);

            return(JsonSuccess(new { response = response, BasketStage = BasketStage.ShippingAddressProvided.GetHashCode() }, JsonRequestBehavior.AllowGet));
        }
예제 #8
0
        /// <summary>
        ///     Validate a user by password
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="maxInvalidPasswordAttempts"> </param>
        /// <returns></returns>
        public bool ValidateUser(string userName, string password, int maxInvalidPasswordAttempts)
        {
            userName = Sanitizer.GetSafeHtmlFragment(userName);
            password = Sanitizer.GetSafeHtmlFragment(password);

            LastLoginStatus = LoginAttemptStatus.LoginSuccessful;

            var user = GetUser(userName);

            if (user == null)
            {
                LastLoginStatus = LoginAttemptStatus.UserNotFound;
                return(false);
            }

            if (user.IsBanned)
            {
                LastLoginStatus = LoginAttemptStatus.Banned;
                return(false);
            }

            if (user.IsLockedOut)
            {
                LastLoginStatus = LoginAttemptStatus.UserLockedOut;
                return(false);
            }

            if (!user.IsApproved)
            {
                LastLoginStatus = LoginAttemptStatus.UserNotApproved;
                return(false);
            }

            var allowedPasswordAttempts = maxInvalidPasswordAttempts;

            if (user.FailedPasswordAttemptCount >= allowedPasswordAttempts)
            {
                LastLoginStatus = LoginAttemptStatus.PasswordAttemptsExceeded;
                return(false);
            }

            var salt            = user.PasswordSalt;
            var hash            = StringUtils.GenerateSaltedHash(password, salt);
            var passwordMatches = hash == user.Password;

            user.FailedPasswordAttemptCount = passwordMatches ? 0 : user.FailedPasswordAttemptCount + 1;

            if (user.FailedPasswordAttemptCount >= allowedPasswordAttempts)
            {
                user.IsLockedOut     = true;
                user.LastLockoutDate = DateTime.UtcNow;
            }

            if (!passwordMatches)
            {
                LastLoginStatus = LoginAttemptStatus.PasswordIncorrect;
                return(false);
            }

            return(LastLoginStatus == LoginAttemptStatus.LoginSuccessful);
        }
예제 #9
0
        public virtual ActionResult GetDeliveryMethodsByPostCode(string countryCode, string basketId, string postCode, string appliedShippingId)
        {
            var  shippingMethods  = _shippingApi.GetShippingMethods(basketId, Sanitizer.GetSafeHtmlFragment(countryCode), postCode);
            bool IsPriceOnRequest = false;
            var  response         = new ResponseModel <BasketModel> {
            };

            // If don't found any shipping in apply postcode control will to to else part and remove applied shipping from basket
            if (shippingMethods.Result != null && shippingMethods.Result.Count > 0)
            {
                var shippingMethod = shippingMethods.Result.Where(x => x.Id == Guid.Parse(appliedShippingId)).FirstOrDefault();
                // shippingMethod can have only that case if shippingMethods list having applied shipping id in that case
                //no need to updateshipping
                if (shippingMethod == null)
                {
                    // In case shippingMethods list don't have applied shipping id default shipping will be apply
                    shippingMethod   = shippingMethods.Result.Where(x => x.IsDefault = true).FirstOrDefault();
                    response         = _basketApi.UpdateShipping(Sanitizer.GetSafeHtmlFragment(basketId), Sanitizer.GetSafeHtmlFragment(Convert.ToString(shippingMethod.Id)), null);
                    IsPriceOnRequest = shippingMethod.IsPriceOnRequest;
                    if (shippingMethod == null)
                    {
                        // In case default shipping is not set that case first shipping will be apply
                        shippingMethod   = shippingMethods.Result.FirstOrDefault();
                        response         = _basketApi.UpdateShipping(Sanitizer.GetSafeHtmlFragment(basketId), Sanitizer.GetSafeHtmlFragment(Convert.ToString(shippingMethod.Id)), null);
                        IsPriceOnRequest = shippingMethod.IsPriceOnRequest;
                    }
                }
                else
                {
                    response         = _basketApi.UpdateShipping(Sanitizer.GetSafeHtmlFragment(basketId), Sanitizer.GetSafeHtmlFragment(Convert.ToString(shippingMethod.Id)), null);
                    IsPriceOnRequest = shippingMethod.IsPriceOnRequest;
                }
            }
            else
            {
                response = _basketApi.UpdateShipping(Sanitizer.GetSafeHtmlFragment(basketId), Sanitizer.GetSafeHtmlFragment(Convert.ToString(Guid.Empty)), null); //Applied shipping remove in case don't found the shipping
            }
            response.Result.IsPriceOnRequest = IsPriceOnRequest;
            response.Result.shippingMethods  = shippingMethods.Result;
            return(JsonSuccess(response.Result, JsonRequestBehavior.AllowGet));
        }
예제 #10
0
        public ActionResult GetShippingMethods(string countryCode)
        {
            var shippingMethods = _shippingApi.GetShippingMethods(_sessionContext.SessionId, Sanitizer.GetSafeHtmlFragment(countryCode));

            return(JsonSuccess(shippingMethods.Result, JsonRequestBehavior.AllowGet));
        }
예제 #11
0
        public virtual ActionResult UpdateShipping(string id, string shippingId, NominatedDeliveryModel nominatedDelivery)
        {
            var response = _basketApi.UpdateShipping(Sanitizer.GetSafeHtmlFragment(id), Sanitizer.GetSafeHtmlFragment(shippingId), nominatedDelivery);
            var basket   = response.Result;

            if (basket.LineItems == null)
            {
                basket.LineItems = new List <BasketLineModel>();
            }
            return(JsonSuccess(new { basket = basket, BasketStage = BasketStage.ShippingMethodSelected.GetHashCode() }, JsonRequestBehavior.AllowGet));
        }
예제 #12
0
        public virtual ActionResult RemovePromoCode(string id, string promoCode)
        {
            var resp = _basketApi.RemovePromoCode(Sanitizer.GetSafeHtmlFragment(id), Sanitizer.GetSafeHtmlFragment(promoCode));

            return(JsonSuccess(resp, JsonRequestBehavior.AllowGet));
        }
예제 #13
0
        /// <summary>
        /// 主方法。
        /// </summary>
        /// <param name="args">傳入參數集合。</param>
        private static void Main(string[] args)
        {
            var originalColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("開始。");
            Console.ForegroundColor = originalColor;

            var testChars = Enumerable.Range(0, char.MaxValue + 1).Select(i => (char)i);
            var testFuncs = new Dictionary <string, Func <string, string> >
            {
                #region -- URL Encode --

                // using System.Web;
                { _httpUtilityUrlEncodeName, str => HttpUtility.UrlEncode(str) },
                { _httpUtilityUrlEncodeUnicodeName, str => HttpUtility.UrlEncodeUnicode(str) }, // Obsolete.
                { _httpUtilityUrlPathEncodeName, str => HttpUtility.UrlPathEncode(str) },

                // using System.Net;
                { _webUtilityUrlEncodeName, str => WebUtility.UrlEncode(str) },

                // using System;
                { _uriEscapeDataStringName, str => Uri.EscapeDataString(str) },
                { _uriEscapeUriStringName, str => Uri.EscapeUriString(str) },

                // PM> Install-Package System.Text.Encodings.Web
                // using System.Text.Encodings.Web;
                { _urlEncoderEncodeName, str => UrlEncoder.Default.Encode(str) },

                // PM> Install-Package Flurl
                // using Flurl;
                { _urlEncodeName, str => Url.Encode(str) },
                { _urlEncodeIllegalCharactersName, str => Url.EncodeIllegalCharacters(str) },

                #endregion -- URL Encode --

                #region -- Html & JavaScript Encode --

                // using System.Web;
                { _httpUtilityHtmlAttributeEncodeName, str => HttpUtility.HtmlAttributeEncode(str) },
                { _httpUtilityHtmlEncodeName, str => HttpUtility.HtmlEncode(str) },
                { _httpUtilityJavaScriptStringEncodeName, str => HttpUtility.JavaScriptStringEncode(str) },

                // using System.Net;
                { _webUtilityHtmlEncodeName, str => WebUtility.HtmlEncode(str) },

                // PM> Install-Package System.Text.Encodings.Web
                // using System.Text.Encodings.Web;
                { _htmlEncoderEncodeName, str => HtmlEncoder.Default.Encode(str) },
                { _javaScriptEncoderEncodeName, str => JavaScriptEncoder.Default.Encode(str) },

                // PM> Install-Package AntiXSS
                // using Microsoft.Security.Application;
                { _sanitizerGetSafeHtmlFragmentName, str => Sanitizer.GetSafeHtmlFragment(str) },

                #endregion -- Html & JavaScript Encode --
            };

            var testData    = GetTestData(testChars, testFuncs);
            var testResults = GetTestResult(testData);

            var filePath = $@"{AppDomain.CurrentDomain.BaseDirectory}Data\TestResults.csv";

            GenerateCsvFile(testResults, filePath);

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("結束。");
            Console.ForegroundColor = originalColor;
        }
예제 #14
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }
            if (!string.IsNullOrEmpty(model.NewPassword))
            {
                if (!Regex.IsMatch(model.NewPassword, SiteUtils.GetPasswordRegex()))
                {
                    ModelState.AddModelError("Password", "Password does not meet policy!");
                    return(JsonValidationError());
                }
            }
            if (model.OldPassword == model.NewPassword)
            {
                ModelState.AddModelError("Error", "Old Password and New Password cannot be same");
                return(JsonValidationError());
            }
            var response = new BoolResponse();
            var result   = _authenticationService.Login(_sessionContext.CurrentUser.Username, Sanitizer.GetSafeHtmlFragment(model.OldPassword), true);

            if (result != null)
            {
                response.IsValid = _customerRepository.ChangePassword(Sanitizer.GetSafeHtmlFragment(model.OldPassword), Sanitizer.GetSafeHtmlFragment(model.NewPassword), _sessionContext.CurrentUser.UserId.ToString()).Result;
                return(JsonSuccess(response, JsonRequestBehavior.AllowGet));
            }
            else
            {
                ModelState.AddModelError("Error", "Old Password didn't match.");
                return(JsonValidationError());
            }
        }
예제 #15
0
        public ActionResult ConvertToOrder(CheckoutModel checkout)
        {
            if (!string.IsNullOrEmpty(checkout.CompanyId) && _sessionContext.CurrentUser == null && checkout.CompanyId != Guid.Empty.ToString())
            {
                //execute when company user tries to place order via guest checkout.
                return(JsonSuccess("", JsonRequestBehavior.DenyGet));
            }
            if (checkout.CustomerId == Guid.Empty.ToString() || checkout.CustomerId == null)
            {
                var user = new CustomerModel {
                    Email    = Sanitizer.GetSafeHtmlFragment(checkout.Email),
                    Password = Sanitizer.GetSafeHtmlFragment(checkout.Password)
                };

                var responseTemp = _customerRepository.GetExistingUser(user.Email);
                if (responseTemp.Result.Count > 0)
                {
                    checkout.CustomerId = responseTemp.Result[0].UserId.ToString();
                }
                else
                {
                    var result = _customerRepository.Register(user);
                    if (result.Result.IsValid)
                    {
                        checkout.CustomerId = result.Result.RecordId;
                    }
                }
            }

            checkout.Payment = new PaymentModel
            {
                PaymentGatewayId = checkout.SelectedPayment.Id,
                PaymentGateway   = checkout.SelectedPayment.SystemName,
                OrderAmount      = checkout.SelectedPayment.CardInfo.Amount,
                Status           = PaymentStatus.Pending.GetHashCode()
            };
            var response = _checkoutApi.ConvertToOrder(Sanitizer.GetSafeHtmlFragment(checkout.BasketId), checkout);

            if (response.Result == null)
            {
                return(JsonSuccess(response, JsonRequestBehavior.AllowGet));
            }
            _b2bRepository.RemoveQuoteBasket();
            var order          = response.Result;
            var paymentRequest = new ProcessPaymentRequest
            {
                BasketId      = checkout.BasketId,
                CurrencyCode  = order.CurrencyCode,
                CustomerId    = checkout.CustomerId,
                LanuguageCode = _sessionContext.CurrentSiteConfig.RegionalSettings.DefaultLanguageCulture,
                OrderId       = order.Id,
                OrderNo       = order.OrderNo,
                PaymentId     = order.Payment.Id,
                UserEmail     = checkout.Email,
                OrderTotal    = order.Payment.OrderAmount,
                Order         = order
            };

            if (!string.IsNullOrEmpty(checkout.SelectedPayment.CardInfo?.CardNo) && !string.IsNullOrEmpty(checkout.SelectedPayment.CardInfo.SecurityCode) && checkout.SelectedPayment.CardInfo.Amount > 0)
            {
                paymentRequest.CardNo     = checkout.SelectedPayment.CardInfo.CardNo;
                paymentRequest.Cvv        = checkout.SelectedPayment.CardInfo.SecurityCode;
                paymentRequest.OrderTotal = checkout.SelectedPayment.CardInfo.Amount;
            }
            if (checkout.SelectedPayment.SystemName != Convert.ToString(PaymentMethodTypes.AccountCredit))
            {
                var payResponse = _checkoutApi.PaymentSetting(checkout.SelectedPayment.SystemName);
                checkout.SelectedPayment = payResponse.Result;
            }
            var paymentResponse = checkout.SelectedPayment.ProcessPayment(paymentRequest);

            if (paymentResponse.Success && paymentResponse.AuthorizedAmount > 0)
            {
                order.Payment.IsValid     = true;
                order.Payment.Status      = order.Payment.IsValid.GetHashCode();
                order.Payment.AuthCode    = paymentResponse.AuthorizationTransactionCode;
                order.Payment.CardNo      = paymentRequest.CardNo;
                order.Payment.OrderAmount = paymentResponse.AuthorizedAmount;
                var result = _checkoutApi.UpdatePayment(order.Id, order.Payment);
                paymentResponse.BalanceAmount = result.Result?.BalanceAmount;
            }

            return(JsonSuccess(paymentResponse, JsonRequestBehavior.AllowGet));
        }
예제 #16
0
        public ActionResult GetAddressById(AddressModel customeraddress)
        {
            var result = _customerRepository.GetAddressById(Sanitizer.GetSafeHtmlFragment(customeraddress.CustomerId), Sanitizer.GetSafeHtmlFragment(customeraddress.Id));

            result.Result.CustomerId = Sanitizer.GetSafeHtmlFragment(customeraddress.CustomerId);
            return(JsonSuccess(result.Result, JsonRequestBehavior.AllowGet));
        }
예제 #17
0
        protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage Request, System.Threading.CancellationToken cancellationToken)
        {
            if (Request.Method == HttpMethod.Options)
            {
                return(base.SendAsync(Request, cancellationToken));
            }

            var queryStrings = Request.RequestUri.ParseQueryString();

            foreach (var key in queryStrings.AllKeys)
            {
                var value = Sanitizer.GetSafeHtmlFragment(queryStrings[key]);
                if (value != queryStrings[key])
                {
                    return(SendError($"input ${key} can not contain sensitive character", HttpStatusCode.BadRequest));
                }
            }

            if (Request.Content.IsFormData())
            {
                var results = Request.Content.ReadAsFormDataAsync().Result;

                foreach (var key in results.AllKeys)
                {
                    var value     = results.GetValues(key).FirstOrDefault();
                    var safeValue = Sanitizer.GetSafeHtmlFragment(value);
                    if (value != safeValue)
                    {
                        return(SendError($"input ${key} can not contain sensitive character", HttpStatusCode.BadRequest));
                    }
                }
            }
            else if (Request.Content.IsMimeMultipartContent())
            {
                string tempDir = profileDirService.GetTempDir();

                var provider = new MultipartFormDataStreamProvider(tempDir);
                var results  = Request.Content.ReadAsMultipartAsync(provider).Result;

                foreach (var key in results.FormData.AllKeys)
                {
                    var value     = results.FormData.GetValues(key).FirstOrDefault();
                    var safeValue = Sanitizer.GetSafeHtmlFragment(value);
                    if (value != safeValue)
                    {
                        return(SendError($"input ${key} can not contain sensitive character", HttpStatusCode.BadRequest));
                    }
                }
            }
            else
            {
                try
                {
                    var result = Request.Content.ReadAsStringAsync().Result;
                    var obj    = JObject.Parse(result);

                    foreach (var item in obj)
                    {
                        var saleValue = Sanitizer.GetSafeHtmlFragment(item.Value.ToString());
                        if (item.Value.ToString() != saleValue)
                        {
                            return(SendError($"input ${item.Key} can not contain sensitive character", HttpStatusCode.BadRequest));
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            return(base.SendAsync(Request, cancellationToken));
        }