Exemple #1
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());
            }
        }
        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),
                    SourceProcess = SourceProcessType.SITE_CHECKOUTGUEST.ToString()
                };

                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          = PaymentStatus.Authorized.GetHashCode();
                order.Payment.OrderAmount     = paymentResponse.AuthorizedAmount;
                order.Payment.AuthCode        = paymentResponse.AuthorizationTransactionCode;
                order.Payment.CardNo          = paymentRequest.CardNo;
                order.Payment.PspResponseCode = paymentRequest.PspSessionCookie;

                var paymentResult = _checkoutApi.UpdatePayment(order.Id, order.Payment);
                paymentResponse.BalanceAmount = paymentResult.Result?.BalanceAmount;
                if (paymentResponse.BalanceAmount.Raw.WithTax == 0)
                {
                    SiteUtils.ResetBasketCookie();
                }
            }
            else
            {
                order.Payment.IsValid          = false;
                order.Payment.Status           = PaymentStatus.Pending.GetHashCode();
                order.Payment.AuthCode         = paymentResponse.AuthorizationTransactionCode;
                order.Payment.PspSessionCookie = paymentResponse.PspSessionCookie;
                var paymentResult = _checkoutApi.UpdatePayment(order.Id, order.Payment);
                //paymentResponse.RefOrderId = order.Payment.Id;
            }


            return(JsonSuccess(paymentResponse, JsonRequestBehavior.AllowGet));
        }
Exemple #3
0
        //protected virtual void SetUserCookie(Guid userGuid)
        //{
        //    if (_httpContext == null || _httpContext.Response == null) return;

        //    var cookie = new HttpCookie(UserCookieName)
        //    {
        //        HttpOnly = true,
        //        Value = userGuid.ToString(),
        //        //if user Guid is empty, expire the cookie immediately, else extend it as per configured duration
        //        Expires = userGuid == Guid.Empty ? DateTime.Now.AddMonths(-1) : DateTime.Now.AddHours(CookieExpires)
        //    };
        //    if (_httpContext.Response.Cookies[UserCookieName] != null)
        //    {
        //        _httpContext.Response.Cookies[UserCookieName].Value = userGuid.ToString();
        //        if (userGuid == Guid.Empty)
        //            _httpContext.Response.Cookies.Add(cookie);

        //    }
        //    else
        //    {
        //        _httpContext.Response.Cookies.Add(cookie);
        //    }


        //}
        /// <summary>
        /// Creates a new session for a user and also reads & creates the required cookies. Makes an API call, creates a new user session record with deviceId, UserId, SessionId
        /// Triggers: Session_Start, Logout
        /// In case, its triggered from Logout, the userId & sessionId are reset and a new Session is generated - however device Id is retained.
        /// </summary>
        /// <param name="resetSession">passed as true at the time of Logout</param>
        /// <returns></returns>
        public async Task <string> CreateUserSession(bool resetSession = false)
        {
            if (_httpContext == null || _httpContext.Response == null)
            {
                return("");
            }

            var session = new SessionInfo
            {
                IpAddress = Utils.GetCurrentIpAddress(),
                Browser   = Utils.GetBrowserInfo(),
                Referrer  = Utils.GetReferrer(),
                Utm       = Utils.GetUtm()
            };
            var httpContext = System.Web.HttpContext.Current;


            if (CurrentUser != null && CurrentUser.UserId != null)
            {
                session.CustomerId = CurrentUser.UserId.ToString();
            }
            else
            {
                if (httpContext.Request.QueryString["email"] != null)
                {
                    var user = _customerRepository.GetExistingUser(httpContext.Request.QueryString["email"])?.Result?[0];

                    _httpContext.Session[Constants.SESSION_USERID]       = user.UserId;
                    _httpContext.Session[Constants.SESSION_COMPANYID]    = user.CompanyId;
                    _httpContext.Session[Constants.SESSION_ISGHOSTLOGIN] = user.IsGhostLogin;
                    _httpContext.Session[Constants.SESSION_ADMINUSER]    = user.AdminUserName;
                    if (!Enum.IsDefined(typeof(CompanyUserRole), user.CompanyUserRole)) //Added check for Enum null
                    {
                        _httpContext.Session[Constants.SESSION_COMPANYUSERROLE] = (CompanyUserRole)user.CompanyUserRole.GetHashCode();
                    }

                    //stored the user object in session.
                    _httpContext.Session[Constants.SESSION_CACHED_USER] = user;
                }
            }
            if (_httpContext.Request.Cookies[Constants.COOKIE_DEVICEID] != null)
            {
                session.DeviceId = _httpContext.Request.Cookies[Constants.COOKIE_DEVICEID].Value;
            }
            else // if deviceId Cookie does not exist, create a new deviceID
            {
                session.DeviceId = Guid.NewGuid().ToString();
            }



            //if (_httpContext.Request.Cookies[Constants.COOKIE_USERID] != null)
            //    session.CustomerId = _httpContext.Request.Cookies[Constants.COOKIE_USERID].Value;
            if (_httpContext.Request.Cookies[Constants.COOKIE_SESSIONID] != null && resetSession == false)
            {
                session.SessionId = _httpContext.Request.Cookies[Constants.COOKIE_SESSIONID].Value;
            }
            if (string.IsNullOrEmpty(session.SessionId))
            {
                var cookie_basketId = new HttpCookie(Constants.COOKIE_BASKETID)
                {
                    HttpOnly = true, Value = "", Expires = DateTime.Now.AddDays(-1)
                };
                _httpContext.Response.Cookies.Add(cookie_basketId);

                var response = await _sessionRepository.CreateUserSessionAsync(session);

                session.SessionId = response.Result;
            }

            //if (resetSession)
            //{
            //    // session.SessionId = "";
            //    session.CustomerId = "";
            //}


            //var cookie_userId = new HttpCookie(Constants.COOKIE_USERID){HttpOnly = true,Value = session.CustomerId,Expires = DateTime.Now.AddDays(Constants.COOKIE_USERID_EXPIRES_DAYS)};
            var cookie_deviceId = new HttpCookie(Constants.COOKIE_DEVICEID)
            {
                HttpOnly = true, Value = session.DeviceId, Expires = DateTime.Now.AddDays(Constants.COOKIE_DEVICEID_EXPIRES_DAYS)
            };
            var cookie_sessionId = new HttpCookie(Constants.COOKIE_SESSIONID)
            {
                Value = session.SessionId, Expires = DateTime.Now.AddMinutes(Constants.COOKIE_SESSIONID_EXPIRES_MINUTES)
            };

            //_httpContext.Response.Cookies.Add(cookie_userId);
            _httpContext.Response.Cookies.Add(cookie_deviceId);
            _httpContext.Response.Cookies.Add(cookie_sessionId);
            return(session.SessionId);
        }