Пример #1
0
        /// <summary>
        /// Creates a new store object
        /// </summary>
        /// <param name="storeName">Name of the new store</param>
        /// <param name="adminEmail">Email address of initial super user account</param>
        /// <param name="adminPassword">Password for initial super user account</param>
        /// <param name="switchContext">If true, the token context is switched to the new store.  If false, the token
        /// context remains the same as it was before the method is called.</param>
        /// <returns>The created store object</returns>
        public static Store CreateStore(string storeName, string adminEmail, string adminPassword, bool switchContext)
        {
            //NEED TO SAVE THE CURRENT STORE CONTEXT
            Store masterStore = Token.Instance.Store;
            //CREATE THE STORE
            Store newStore = new Store();

            newStore.Name             = storeName;
            newStore.NextOrderId      = 1;
            newStore.OrderIdIncrement = 1;
            newStore.WeightUnit       = CommerceBuilder.Shipping.WeightUnit.Pounds;
            newStore.MeasurementUnit  = CommerceBuilder.Shipping.MeasurementUnit.Inches;
            newStore.Save();
            //NEED TO SWITCH OUR TOKEN CONTEXT TO THE NEW STORE
            Token.Instance.InitStoreContext(newStore);
            //INITIALIZE THE AUDIT LOGS
            Logger.Audit(AuditEventType.ApplicationStarted, true, string.Empty);
            //INITIALIZE ROLES AND GROUPS
            RoleDataSource.EnsureDefaultRoles();
            GroupDataSource.EnsureDefaultGroups();
            //CREATE THE SUPER USER
            User user = UserDataSource.CreateUser(adminEmail, adminPassword);

            //ASSIGN USER TO APPROPRIATE GROUP
            CommerceBuilder.Users.Group suGroup = GroupDataSource.LoadForName("Super Users");
            user.UserGroups.Add(new UserGroup(user.UserId, suGroup.GroupId));
            user.Save();
            //RESET THE ORIGINAL STORE CONTEXT
            if (!switchContext)
            {
                Token.Instance.InitStoreContext(masterStore);
            }
            //RETURN THE NEW STORE
            return(newStore);
        }
Пример #2
0
        private bool CreateAccount()
        {
            // NEED TO REGISTER USER
            if (AbleContext.Current.User.IsAnonymous)
            {
                // VALIDATE EMAIL, IF EMAIL IS ALREADY REGISTERED, ASK FOR LOGIN
                string newEmail = StringHelper.StripHtml(Email.Text);
                if (UserDataSource.IsEmailRegistered(newEmail))
                {
                    IList <string> warningMessages = new List <string>();
                    warningMessages.Add("The email address you have provided is already registered.Please sign in to access your account.");
                    WarningMessageList.DataSource = warningMessages;
                    WarningMessageList.DataBind();
                    return(false);
                }

                // ANONYMOUS USER SELECTING GUEST CHECKOUT, CREATE TEMPORARY ACCOUNT
                User   oldUser     = AbleContext.Current.User;
                string newUserName = "******" + Guid.NewGuid().ToString("N") + "@domain.xyz";
                string newPassword = Guid.NewGuid().ToString("N");
                MembershipCreateStatus createStatus;
                User newUser = UserDataSource.CreateUser(newUserName, newEmail, newPassword, string.Empty, string.Empty, true, 0, out createStatus);

                // IF THE CREATE FAILS, IGNORE AND CONTINUE CREATING THE ORDER
                if (createStatus == MembershipCreateStatus.Success)
                {
                    // CHANGE THE NAME AND EMAIL TO SOMETHING MORE FRIENDLY THAN GUID
                    newUser.UserName                   = "******" + newUser.Id.ToString() + "@domain.xyz";
                    newUser.PrimaryAddress.Email       = newEmail;
                    newUser.PrimaryAddress.CountryCode = AbleContext.Current.Store.DefaultWarehouse.CountryCode;
                    newUser.PrimaryAddress.IsBilling   = true;
                    newUser.PrimaryAddress.Residence   = true;
                    newUser.Save();
                    CommerceBuilder.Users.User.Migrate(oldUser, newUser, true, true);
                    AbleContext.Current.User = newUser;
                    FormsAuthentication.SetAuthCookie(newUser.UserName, false);
                }
            }

            return(true);
        }
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && ValidatePassword())
            {
                if ((!trCaptchaField.Visible) || CaptchaImage.Authenticate(CaptchaInput.Text))
                {
                    // PERFORM CUSTOM VALIDATION TO ENSURE EMAIL IS NOT ALREADY REGISTERED
                    string userName = UserName.Text.Trim();
                    int    userIde  = UserDataSource.GetUserIdByEmail(userName);
                    int    userIdu  = UserDataSource.GetUserIdByUserName(userName);
                    if (userIde == 0 && userIdu == 0)
                    {
                        // NO USER REGISTERED WITH THAT USERNAME OR EMAIL
                        MembershipCreateStatus status;
                        User newUser = UserDataSource.CreateUser(userName, userName, Password.Text, string.Empty, string.Empty, true, 0, out status);
                        if (status == MembershipCreateStatus.Success)
                        {
                            // WE HAVE TO VALIDATE CREDENTIALS SO A MODIFIED FORM POST CANNOT ACCESS THIS CODE
                            if (Membership.ValidateUser(userName, Password.Text))
                            {
                                // SET A DEFAULT BILLING ADDRESS FOR THE USER
                                newUser.PrimaryAddress.Email       = userName;
                                newUser.PrimaryAddress.CountryCode = AbleContext.Current.Store.DefaultWarehouse.CountryCode;
                                newUser.PrimaryAddress.Residence   = true;
                                newUser.Save();

                                // SET COOKIE TO REMEMBER USERNAME IF INDICATED
                                if (RememberUserName.Checked)
                                {
                                    HttpCookie cookie = new HttpCookie("UserName", userName);
                                    cookie.Expires = DateTime.MaxValue;
                                    Response.Cookies.Add(cookie);
                                }
                                else
                                {
                                    Response.Cookies.Add(new HttpCookie("UserName", ""));
                                }

                                //MIGRATE USER IF NEEDED
                                int newUserId = UserDataSource.GetUserIdByUserName(userName);
                                if ((AbleContext.Current.UserId != newUserId) && (newUserId != 0))
                                {
                                    User.Migrate(AbleContext.Current.User, newUser, false, true);
                                    AbleContext.Current.UserId = newUserId;
                                }

                                //REDIRECT TO APPROPRIATE PAGE
                                FormsAuthentication.SetAuthCookie(UserName.Text, false);
                                Response.Redirect(NavigationHelper.GetReturnUrl(NavigationHelper.GetMobileStoreUrl("~/Default.aspx")));
                            }
                        }
                        else
                        {
                            InvalidRegistration.IsValid = false;
                            switch (status)
                            {
                            case MembershipCreateStatus.DuplicateUserName:
                            case MembershipCreateStatus.DuplicateEmail:
                                InvalidRegistration.ErrorMessage = "The user-name you have provided is already registered.  Sign in to access your account.";
                                break;

                            case MembershipCreateStatus.InvalidEmail:
                                InvalidRegistration.ErrorMessage = "The email address you have provided is not valid.";
                                break;

                            case MembershipCreateStatus.InvalidUserName:
                                InvalidRegistration.ErrorMessage = "The user-name you have provided is not valid.";
                                break;

                            case MembershipCreateStatus.InvalidPassword:
                                InvalidRegistration.ErrorMessage = "The password you have provided is not valid.";
                                break;

                            default:
                                InvalidRegistration.ErrorMessage = "Unexpected error in registration (" + status.ToString() + ")";
                                break;
                            }
                        }
                    }
                    else
                    {
                        DuplicateEmailValidator.IsValid = false;
                    }
                }
                else
                {
                    //CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE
                    CustomValidator invalidInput = new CustomValidator();
                    invalidInput.ID           = Guid.NewGuid().ToString();
                    invalidInput.Text         = "*";
                    invalidInput.ErrorMessage = "You did not input the verification number correctly.";
                    invalidInput.IsValid      = false;
                    phCaptchaValidators.Controls.Add(invalidInput);
                    CaptchaInput.Text = "";
                    Password.Attributes.Add("value", string.Empty);
                    RefreshCaptcha();
                }
            }
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            string provinceName = string.Empty;

            if (!ValidateProvince(out provinceName))
            {
                return;
            }

            // NEED TO REGISTER USER
            if (AbleContext.Current.User.IsAnonymousOrGuest)
            {
                if (CreateAccountPh.Visible)
                {
                    bool result = false;
                    result = ValidatePassword();
                    if (result)
                    {
                        // PERFORM CUSTOM VALIDATION TO ENSURE EMAIL IS NOT ALREADY REGISTERED
                        string userName = StringHelper.StripHtml(Email.Text);
                        if (!UserDataSource.IsEmailRegistered(userName))
                        {
                            // CHECK IF THE USER GUEST ACCOUNT EXISTS ALREADY
                            if (AbleContext.Current.User.IsGuest)
                            {
                                // MIGRATE ACTIVE USER TO NEW ACCOUNT
                                AbleContext.Current.User.UserName = userName;
                                AbleContext.Current.User.SetPassword(Password.Text);
                                AbleContext.Current.User.Save();
                                FormsAuthentication.SetAuthCookie(userName, false);
                            }
                            else
                            {
                                // NO USER REGISTERED WITH THAT USERNAME OR EMAIL
                                MembershipCreateStatus status;
                                User newUser = UserDataSource.CreateUser(userName, userName, Password.Text, string.Empty, string.Empty, true, 0, out status);
                                if (status == MembershipCreateStatus.Success)
                                {
                                    // WE HAVE TO VALIDATE CREDENTIALS SO A MODIFIED FORM POST CANNOT ACCESS THIS CODE
                                    if (Membership.ValidateUser(userName, Password.Text))
                                    {
                                        // MIGRATE ACTIVE USER TO NEW ACCOUNT
                                        CommerceBuilder.Users.User.Migrate(AbleContext.Current.User, newUser, true, true, true);
                                        AbleContext.Current.User = newUser;
                                        FormsAuthentication.SetAuthCookie(userName, false);
                                    }
                                }
                                else
                                {
                                    result = false;
                                    InvalidRegistration.IsValid = result;
                                    switch (status)
                                    {
                                    case MembershipCreateStatus.DuplicateUserName:
                                    case MembershipCreateStatus.DuplicateEmail:
                                        InvalidRegistration.ErrorMessage = "The user-name you have provided is already registered.  Sign in to access your account.";
                                        break;

                                    case MembershipCreateStatus.InvalidEmail:
                                        InvalidRegistration.ErrorMessage = "The email address you have provided is not valid.";
                                        break;

                                    case MembershipCreateStatus.InvalidUserName:
                                        InvalidRegistration.ErrorMessage = "The user-name you have provided is not valid.";
                                        break;

                                    case MembershipCreateStatus.InvalidPassword:
                                        InvalidRegistration.ErrorMessage = "The password you have provided is not valid.";
                                        break;

                                    default:
                                        InvalidRegistration.ErrorMessage = "Unexpected error in registration (" + status.ToString() + ")";
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            result = false;
                            DuplicateEmailValidator.IsValid = false;
                        }
                    }

                    if (!result)
                    {
                        return;
                    }
                }
                else if (AbleContext.Current.User.IsAnonymous)
                {
                    // VALIDATE EMAIL, IF EMAIL IS ALREADY REGISTERED, ASK FOR LOGIN
                    string newEmail = StringHelper.StripHtml(Email.Text);
                    if (UserDataSource.IsEmailRegistered(newEmail))
                    {
                        InvalidRegistration.IsValid      = false;
                        InvalidRegistration.ErrorMessage = "The email address you have provided is already registered. Please sign in to access your account.";
                        return;
                    }

                    // ANONYMOUS USER SELECTING GUEST CHECKOUT, CREATE TEMPORARY ACCOUNT
                    User   oldUser     = AbleContext.Current.User;
                    string newUserName = "******" + Guid.NewGuid().ToString("N") + "@domain.xyz";
                    string newPassword = Guid.NewGuid().ToString("N");
                    MembershipCreateStatus createStatus;
                    User newUser = UserDataSource.CreateUser(newUserName, newEmail, newPassword, string.Empty, string.Empty, true, 0, out createStatus);

                    // IF THE CREATE FAILS, IGNORE AND CONTINUE CREATING THE ORDER
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        // CHANGE THE NAME AND EMAIL TO SOMETHING MORE FRIENDLY THAN GUID
                        newUser.UserName = "******" + newUser.Id.ToString() + "@domain.xyz";
                        newUser.Save();
                        CommerceBuilder.Users.User.Migrate(oldUser, newUser, true, true);
                        AbleContext.Current.User = newUser;
                        FormsAuthentication.SetAuthCookie(newUser.UserName, false);
                    }
                }
            }

            string address1  = StringHelper.StripHtml(Address1.Text);
            string address2  = StringHelper.StripHtml(Address2.Text);
            string city      = StringHelper.StripHtml(City.Text);
            string postColde = StringHelper.StripHtml(PostalCode.Text);

            if (_address.Address1 != address1 || _address.Address2 != address2 || _address.City != city || _address.Province != provinceName || _address.PostalCode != postColde)
            {
                _address.Validated = false;
            }
            _address.FirstName = StringHelper.StripHtml(FirstName.Text);
            _address.LastName  = StringHelper.StripHtml(LastName.Text);
            if (CollectEmail)
            {
                _address.Email = StringHelper.StripHtml(Email.Text);
            }
            _address.Address1    = address1;
            _address.Address2    = address2;
            _address.Company     = StringHelper.StripHtml(Company.Text);
            _address.City        = city;
            _address.Province    = provinceName;
            _address.PostalCode  = postColde;
            _address.CountryCode = Country.SelectedValue;
            _address.Phone       = StringHelper.StripHtml(Telephone.Text);
            _address.Fax         = StringHelper.StripHtml(Fax.Text);
            _address.Residence   = Residence.SelectedIndex == 0;

            if (OnAddressUpdate != null)
            {
                OnAddressUpdate(this, new AddressEventArgs(_address));
            }
        }
Пример #5
0
        protected void CheckingOut(object sender, CheckingOutEventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                e.Cancel = true;
                return;
            }

            if (Page.IsValid)
            {
                if (!string.IsNullOrEmpty(Comments.Text))
                {
                    foreach (BasketShipment shipment in _basket.Shipments)
                    {
                        shipment.ShipMessage = StringHelper.StripHtml(Comments.Text);
                        shipment.Save();
                    }
                }
            }

            //Make sure basket hasn't changed during checkout
            if (_CurrentBasketHash != _SavedBasketHash)
            {
                e.Cancel = true;
                CheckoutMessagePanel.Visible = true;
                CheckoutMessage.Text         = "Your order has not been completed and payment was not processed.<br /><br />Your cart appears to have been modified during checkout.  Please verify the contents of your order and resubmit your payment.";
                RecalculateBasket(true);

                return;
            }

            //Make sure that a valid billing address is set
            User user = AbleContext.Current.User;

            if (user.PrimaryAddress == null || !user.PrimaryAddress.IsValid)
            {
                e.Cancel = true;

                CheckoutMessagePanel.Visible = true;
                CheckoutMessage.Text         = "Your order has not been completed and payment was not processed.<br /><br />The billing address is invalid.  Please correct the address and resubmit your payment.";

                return;
            }

            if (AbleContext.Current.User.IsAnonymous)
            {
                // ANONYMOUS USER SELECTING GUEST CHECKOUT, CREATE TEMPORARY ACCOUNT
                User   oldUser     = AbleContext.Current.User;
                string newUserName = "******" + Guid.NewGuid().ToString("N") + "@domain.xyz";
                string newEmail    = StringHelper.StripHtml(oldUser.PrimaryAddress.Email);
                string newPassword = Guid.NewGuid().ToString("N");
                MembershipCreateStatus createStatus;
                User newUser = UserDataSource.CreateUser(newUserName, newEmail, newPassword, string.Empty, string.Empty, true, 0, out createStatus);

                // IF THE CREATE FAILS, IGNORE AND CONTINUE CREATING THE ORDER
                if (createStatus == MembershipCreateStatus.Success)
                {
                    // CHANGE THE NAME AND EMAIL TO SOMETHING MORE FRIENDLY THAN GUID
                    newUser.UserName = "******" + newUser.Id.ToString() + "@domain.xyz";
                    newUser.Save();
                    CommerceBuilder.Users.User.Migrate(oldUser, newUser, true, true, true);
                    AbleContext.Current.User = newUser;
                    FormsAuthentication.SetAuthCookie(newUser.UserName, false);
                }
            }
        }
Пример #6
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            // CHECK IF PAGE IS VALID
            if (Page.IsValid)
            {
                // MAKE SURE PASSWORD VALIDATES AGAINST POLICY
                if (ValidatePassword())
                {
                    // ATTEMPT TO CREATE THE USER
                    MembershipCreateStatus status;
                    User newUser = UserDataSource.CreateUser(AddEmail.Text, AddEmail.Text, AddPassword.Text, string.Empty, string.Empty, true, 0, out status);
                    if (status == MembershipCreateStatus.Success)
                    {
                        // FORCE PASSWORD EXPIRATION
                        newUser.Passwords[0].ForceExpiration = ForceExpiration.Checked;
                        newUser.Passwords[0].Save();

                        // ASSIGN GROUPS TO NEW USER
                        IList <Group> availableGroups = SecurityUtility.GetManagableGroups();
                        int           groupId         = AlwaysConvert.ToInt(AddGroup.SelectedValue);
                        if (groupId > 0)
                        {
                            int index = availableGroups.IndexOf(groupId);
                            if (groupId > -1)
                            {
                                // ADD THE GROUP ASSOCIATION FOR THE NEW USER
                                newUser.UserGroups.Add(new UserGroup(newUser, availableGroups[index]));
                                newUser.Save();
                            }
                        }

                        // REDIRECT TO EDIT FORM IF INDICATED
                        if (((Button)sender).ID == "AddEditButton")
                        {
                            Response.Redirect("EditUser.aspx?UserId=" + newUser.Id.ToString());
                        }

                        // NO REDIRECT, DISPLAY A CONFIRMATION FOR CREATED USER
                        UserAddedMessage.Text    = string.Format(UserAddedMessage.Text, newUser.UserName);
                        UserAddedMessage.Visible = true;

                        // RESET THE ADD FORM FIELDS
                        AddEmail.Text           = String.Empty;
                        AddPassword.Text        = String.Empty;
                        AddConfirmPassword.Text = String.Empty;
                        AddGroup.SelectedIndex  = -1;

                        //REBIND THE SEARCH
                        UserGrid.DataBind();
                    }
                    else
                    {
                        // CREATE USER FAILED WITHIN THE API
                        switch (status)
                        {
                        case MembershipCreateStatus.DuplicateEmail:
                        case MembershipCreateStatus.DuplicateUserName:
                            AddCustomValidationError(phEmailValidation, AddEmail, "The email address is already registered.");
                            break;

                        case MembershipCreateStatus.InvalidEmail:
                        case MembershipCreateStatus.InvalidUserName:
                            AddCustomValidationError(phEmailValidation, AddEmail, "The email address is invalid.");
                            break;

                        case MembershipCreateStatus.InvalidPassword:
                            AddCustomValidationError(phPasswordValidation, AddPassword, "The password is invalid.");
                            break;

                        default:
                            AddCustomValidationError(phEmailValidation, AddEmail, "Unexpected error: " + status.ToString());
                            break;
                        }
                        AddPopup.Show();
                    }
                }
                else
                {
                    AddPopup.Show();
                }
            }
            else
            {
                AddPopup.Show();
            }
        }
        protected void BillingPageContinue_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string nextPageUrl = "Payment.aspx";

                // NEED TO REGISTER USER
                if (AbleContext.Current.User.IsAnonymous)
                {
                    if (CreateNewAccountPanel.Visible)
                    {
                        if (!CreateNewAccount())
                        {
                            return;
                        }
                    }
                    else
                    {
                        // VALIDATE EMAIL, IF EMAIL IS ALREADY REGISTERED, ASK FOR LOGIN
                        string newEmail = StringHelper.StripHtml(BillToEmail.Text);
                        if (UserDataSource.IsEmailRegistered(newEmail))
                        {
                            InvalidRegistration.IsValid      = false;
                            InvalidRegistration.ErrorMessage = "The email address you have provided is already registered. Please sign in to access your account.";
                            return;
                        }

                        // ANONYMOUS USER SELECTING GUEST CHECKOUT, CREATE TEMPORARY ACCOUNT
                        User   oldUser     = AbleContext.Current.User;
                        string newUserName = "******" + Guid.NewGuid().ToString("N") + "@domain.xyz";
                        string newPassword = Guid.NewGuid().ToString("N");
                        MembershipCreateStatus createStatus;
                        User newUser = UserDataSource.CreateUser(newUserName, newEmail, newPassword, string.Empty, string.Empty, true, 0, out createStatus);

                        // IF THE CREATE FAILS, IGNORE AND CONTINUE CREATING THE ORDER
                        if (createStatus == MembershipCreateStatus.Success)
                        {
                            // CHANGE THE NAME AND EMAIL TO SOMETHING MORE FRIENDLY THAN GUID
                            newUser.UserName = "******" + newUser.Id.ToString() + "@domain.xyz";
                            newUser.Save();
                            CommerceBuilder.Users.User.Migrate(oldUser, newUser, true, true);
                            AbleContext.Current.User = newUser;
                            FormsAuthentication.SetAuthCookie(newUser.UserName, false);
                        }
                    }
                }

                // MAILING LIST SIGNUP
                if (EmailLists.Visible && EmailLists.Items.Count > 0)
                {
                    string            email      = AbleContext.Current.User.Email;
                    int               listIndex  = 0;
                    IList <EmailList> emailLists = GetPublicEmailLists();
                    if (emailLists != null && emailLists.Count > 0)
                    {
                        foreach (ListViewDataItem item in EmailLists.Items)
                        {
                            EmailList list     = emailLists[listIndex];
                            CheckBox  selected = (CheckBox)item.FindControl("Selected");
                            if (selected != null)
                            {
                                if (selected.Checked)
                                {
                                    list.ProcessSignupRequest(email);
                                }
                                else
                                {
                                    list.RemoveMember(email);
                                }
                            }
                            else
                            {
                                list.RemoveMember(email);
                            }
                            listIndex++;
                        }
                    }
                }

                string provinceName;
                if (ValidateProvince(out provinceName))
                {
                    Address address = AbleContext.Current.User.PrimaryAddress;
                    address.FirstName   = StringHelper.StripHtml(FirstName.Text);
                    address.LastName    = StringHelper.StripHtml(LastName.Text);
                    address.Address1    = StringHelper.StripHtml(Address1.Text);
                    address.Address2    = StringHelper.StripHtml(Address2.Text);
                    address.Company     = StringHelper.StripHtml(Company.Text);
                    address.Email       = CreateNewAccountPanel.Visible ? StringHelper.StripHtml(UserName.Text) : StringHelper.StripHtml(BillToEmail.Text);
                    address.City        = StringHelper.StripHtml(City.Text);
                    address.Province    = provinceName;
                    address.PostalCode  = StringHelper.StripHtml(PostalCode.Text);
                    address.CountryCode = Country.SelectedValue;
                    address.Phone       = StringHelper.StripHtml(Telephone.Text);
                    address.Fax         = StringHelper.StripHtml(Fax.Text);
                    address.Residence   = !IsBusinessAddress.Checked;
                    address.Save();
                }
                else
                {
                    Province2Invalid.IsValid = false;
                    UpdateCountry();
                }

                if (ShippingAddressPanel.Visible)
                {
                    nextPageUrl = "ShipAddress.aspx";
                }

                Response.Redirect(nextPageUrl);
            }
        }
        protected bool CreateNewAccount()
        {
            bool result = false;

            if (Page.IsValid && ValidatePassword())
            {
                if ((!trCaptchaField.Visible) || CaptchaImage.Authenticate(CaptchaInput.Text))
                {
                    // PERFORM CUSTOM VALIDATION TO ENSURE EMAIL IS NOT ALREADY REGISTERED
                    string userName = StringHelper.StripHtml(UserName.Text.Trim());
                    if (!UserDataSource.IsEmailRegistered(userName))
                    {
                        // NO USER REGISTERED WITH THAT USERNAME OR EMAIL
                        MembershipCreateStatus status;
                        User newUser = UserDataSource.CreateUser(userName, userName, Password.Text, string.Empty, string.Empty, true, 0, out status);
                        if (status == MembershipCreateStatus.Success)
                        {
                            // WE HAVE TO VALIDATE CREDENTIALS SO A MODIFIED FORM POST CANNOT ACCESS THIS CODE
                            if (Membership.ValidateUser(userName, Password.Text))
                            {
                                // SET A DEFAULT BILLING ADDRESS FOR THE USER
                                newUser.PrimaryAddress.Email       = userName;
                                newUser.PrimaryAddress.CountryCode = AbleContext.Current.Store.DefaultWarehouse.CountryCode;
                                newUser.PrimaryAddress.Residence   = true;
                                newUser.Save();

                                // MIGRATE ACTIVE USER TO NEW ACCOUNT
                                CommerceBuilder.Users.User.Migrate(AbleContext.Current.User, newUser, false, true);
                                AbleContext.Current.User = newUser;
                                FormsAuthentication.SetAuthCookie(userName, false);
                                result = true;
                            }
                        }
                        else
                        {
                            InvalidRegistration.IsValid = false;
                            switch (status)
                            {
                            case MembershipCreateStatus.DuplicateUserName:
                            case MembershipCreateStatus.DuplicateEmail:
                                InvalidRegistration.ErrorMessage = "The user-name you have provided is already registered.  Sign in to access your account.";
                                break;

                            case MembershipCreateStatus.InvalidEmail:
                                InvalidRegistration.ErrorMessage = "The email address you have provided is not valid.";
                                break;

                            case MembershipCreateStatus.InvalidUserName:
                                InvalidRegistration.ErrorMessage = "The user-name you have provided is not valid.";
                                break;

                            case MembershipCreateStatus.InvalidPassword:
                                InvalidRegistration.ErrorMessage = "The password you have provided is not valid.";
                                break;

                            default:
                                InvalidRegistration.ErrorMessage = "Unexpected error in registration (" + status.ToString() + ")";
                                break;
                            }
                        }
                    }
                    else
                    {
                        DuplicateEmailValidator.IsValid = false;
                    }
                }
                else
                {
                    //CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE
                    CustomValidator invalidInput = new CustomValidator();
                    invalidInput.ID           = Guid.NewGuid().ToString();
                    invalidInput.Text         = "*";
                    invalidInput.ErrorMessage = "You did not input the verification number correctly.";
                    invalidInput.IsValid      = false;
                    phCaptchaValidators.Controls.Add(invalidInput);
                    CaptchaInput.Text = "";
                    Password.Attributes.Add("value", string.Empty);
                    RefreshCaptcha();
                }
            }

            return(result);
        }
Пример #9
0
        private bool UpdateAddress(bool validate)
        {
            // NEED TO REGISTER USER
            if (AbleContext.Current.User.IsAnonymous)
            {
                if (CreateNewAccountPanel.Visible)
                {
                    if (!CreateNewAccount())
                    {
                        return(false);
                    }
                    else
                    {
                        CreateNewAccountPanel.Visible = false;
                    }
                }
                else
                {
                    // VALIDATE EMAIL, IF EMAIL IS ALREADY REGISTERED, ASK FOR LOGIN
                    string newEmail = StringHelper.StripHtml(BillToEmail.Text);
                    if (UserDataSource.IsEmailRegistered(newEmail))
                    {
                        InvalidRegistration.IsValid      = false;
                        InvalidRegistration.ErrorMessage = "The email address you have provided is already registered. Please sign in to access your account.";
                        return(false);
                    }

                    // ANONYMOUS USER SELECTING GUEST CHECKOUT, CREATE TEMPORARY ACCOUNT
                    User   oldUser     = AbleContext.Current.User;
                    string newUserName = "******" + Guid.NewGuid().ToString("N") + "@domain.xyz";
                    string newPassword = Guid.NewGuid().ToString("N");
                    MembershipCreateStatus createStatus;
                    User newUser = UserDataSource.CreateUser(newUserName, newEmail, newPassword, string.Empty, string.Empty, true, 0, out createStatus);

                    // IF THE CREATE FAILS, IGNORE AND CONTINUE CREATING THE ORDER
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        // CHANGE THE NAME AND EMAIL TO SOMETHING MORE FRIENDLY THAN GUID
                        newUser.UserName = "******" + newUser.Id.ToString() + "@domain.xyz";
                        newUser.Save();
                        CommerceBuilder.Users.User.Migrate(oldUser, newUser, true, true);
                        AbleContext.Current.User = newUser;
                        FormsAuthentication.SetAuthCookie(newUser.UserName, false);
                    }
                }
            }

            // MAILING LIST SIGNUP
            if (EmailLists.Visible && EmailLists.Items.Count > 0)
            {
                string            email      = AbleContext.Current.User.Email;
                int               listIndex  = 0;
                IList <EmailList> emailLists = GetPublicEmailLists();
                if (emailLists != null && emailLists.Count > 0)
                {
                    foreach (ListViewDataItem item in EmailLists.Items)
                    {
                        EmailList list     = emailLists[listIndex];
                        CheckBox  selected = (CheckBox)item.FindControl("Selected");
                        if (selected != null)
                        {
                            if (selected.Checked)
                            {
                                EmailListSignup signup = EmailListSignupDataSource.Load(list.Id, email);
                                if (signup == null || signup.SignupDate < LocaleHelper.LocalNow.AddMinutes(-5))
                                {
                                    list.ProcessSignupRequest(email);
                                }
                            }
                            else
                            {
                                list.RemoveMember(email);
                            }
                        }
                        else
                        {
                            list.RemoveMember(email);
                        }
                        listIndex++;
                    }
                }
            }

            string provinceName = string.Empty;

            if (ValidateProvince(out provinceName))
            {
                Address address   = AbleContext.Current.User.PrimaryAddress;
                string  address1  = StringHelper.StripHtml(Address1.Text);
                string  address2  = StringHelper.StripHtml(Address2.Text);
                string  city      = StringHelper.StripHtml(City.Text);
                string  postColde = StringHelper.StripHtml(PostalCode.Text);
                if (address.Address1 != address1 || address.Address2 != address2 || address.City != city || address.Province != provinceName || address.PostalCode != postColde)
                {
                    address.Validated = false;
                }
                address.FirstName   = StringHelper.StripHtml(FirstName.Text);
                address.LastName    = StringHelper.StripHtml(LastName.Text);
                address.Address1    = address1;
                address.Address2    = address2;
                address.Company     = StringHelper.StripHtml(Company.Text);
                address.Email       = trEmail.Visible ? StringHelper.StripHtml(BillToEmail.Text) : StringHelper.StripHtml(UserName.Text);
                address.City        = city;
                address.Province    = provinceName;
                address.PostalCode  = postColde;
                address.CountryCode = Country.SelectedValue;
                address.Phone       = StringHelper.StripHtml(Telephone.Text);
                address.Fax         = StringHelper.StripHtml(Fax.Text);
                address.Residence   = !IsBusinessAddress.Checked;
                address.Save();

                if (validate && !address.Validated && _addressValidator != null)
                {
                    AddressValidationResponse avr = _addressValidator.ValidateAddress(address);
                    if (avr != null)
                    {
                        if (!avr.IsValid.HasValue || !avr.IsValid.Value)
                        {
                            ValidAddresses = avr.Addresses;
                            if (ValidAddresses != null)
                            {
                                int index = 0;
                                foreach (ValidAddress validAddress in ValidAddresses)
                                {
                                    validAddress.Id = ++index;
                                }

                                ValidAddressesList.DataSource = ValidAddresses;
                                ValidAddressesList.DataBind();
                                ValidAddressesPanel.Visible = true;
                                ValidAddressesList.Items.Add(new ListItem("Use the address exactly as I entered it", "0"));
                                ValidAddressesList.Items[0].Selected = true;
                                if (ValidAddressesList.Items.Count > 1)
                                {
                                    PHAddressFound.Visible = true;
                                    PHNoAddress.Visible    = false;
                                }
                                else
                                {
                                    PHAddressFound.Visible = false;
                                    PHNoAddress.Visible    = true;
                                }

                                return(false);
                            }
                        }
                    }
                }
            }
            else
            {
                Province2Invalid.IsValid = false;
                UpdateCountry();
                return(false);
            }

            return(true);
        }
        public GetExpressCheckoutResult GetExpressCheckout()
        {
            HttpContext            context         = HttpContext.Current;
            ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current;

            if (existingSession == null)
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "SESSION";
                customError.ShortMessage = "Missing Token";
                customError.LongMessage  = "The PayPal session token was expired or unavailable.  Please try again.";
                customErrorList[0]       = customError;
                return(new GetExpressCheckoutResult(null, customErrorList));
            }
            context.Trace.Write("Detected PayPal Token:" + existingSession.Token);
            context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString());

            GetExpressCheckoutDetailsRequestType expressCheckoutRequest = new GetExpressCheckoutDetailsRequestType();

            expressCheckoutRequest.Token   = existingSession.Token;
            expressCheckoutRequest.Version = "1.0";

            //EXECUTE REQUEST
            GetExpressCheckoutDetailsResponseType expressCheckoutResponse;

            expressCheckoutResponse = (GetExpressCheckoutDetailsResponseType)SoapCall("GetExpressCheckoutDetails", expressCheckoutRequest);
            if (expressCheckoutResponse == null)
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "NORESP";
                customError.ShortMessage = "No Response From Server";
                customError.LongMessage  = "The PayPal service is unavailable at this time.";
                customErrorList[0]       = customError;
                return(new GetExpressCheckoutResult(null, customErrorList));
            }

            //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS
            if (expressCheckoutResponse.Errors != null)
            {
                return(new GetExpressCheckoutResult(null, expressCheckoutResponse.Errors));
            }

            //GET THE DETAILS OF THE REQUEST
            GetExpressCheckoutDetailsResponseDetailsType expressCheckoutDetails;

            expressCheckoutDetails = expressCheckoutResponse.GetExpressCheckoutDetailsResponseDetails;

            //MAKE SURE CUSTOMER IDS MATCH
            User currentUser = Token.Instance.User;

            if (expressCheckoutDetails.Custom != ("UID" + currentUser.UserId.ToString()))
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "USER";
                customError.ShortMessage = "User Mismatch";
                customError.LongMessage  = "The PayPal basket did not have the expected user context.";
                customErrorList[0]       = customError;
                Logger.Warn("Error in PayPal GetExpressCheckout.  User ID detected in PayPal response: " + expressCheckoutDetails.Custom + ", Customer User ID: " + currentUser.UserId.ToString());
                return(new GetExpressCheckoutResult(null, customErrorList));
            }

            //CHECK WHETHER AN EXISTING USER IS ASSOCIATED WITH THE RETURNED PAYPAL ID
            //IF THE CURRENT USER DOES NOT MATCH, LOG IN THE PAYPAL USER ACCOUNT
            string paypalEmail   = expressCheckoutDetails.PayerInfo.Payer;
            string paypalPayerID = expressCheckoutDetails.PayerInfo.PayerID;
            //PAYER ID IS SUPPOSED TO BE UNIQUE REGARDLESS OF EMAIL ADDRESS, LOOK FOR ASSOCIATED ACCT
            User paypalUser = UserDataSource.LoadForPayPalId(paypalPayerID);

            //IF NOT FOUND, SEE IF AN ACCOUNT EXISTS WITH THAT EMAIL AS USERNAME
            if (paypalUser == null)
            {
                paypalUser = UserDataSource.LoadForUserName(paypalEmail);
            }
            if (paypalUser != null)
            {
                //WE FOUND AN ACCOUNT FOR THIS PAYPAL USER
                context.Trace.Write(this.GetType().ToString(), "PAYPAL USER FOUND IN DATABASE");
                if (currentUser.UserId != paypalUser.UserId)
                {
                    //THE PAYPAL USER IS NOT THE CURRENT USER CONTEXT, SO TRANSFER THE BASKET
                    context.Trace.Write(this.GetType().ToString(), "MOVE BASKET TO " + paypalUser.UserName);
                    Basket.Transfer(currentUser.UserId, paypalUser.UserId, true);
                    //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION
                    ExpressCheckoutSession.Delete(currentUser);
                }
            }
            else
            {
                //WE DID NOT FIND AN ACCOUNT
                context.Trace.Write(this.GetType().ToString(), "PAYPAL USER NOT FOUND IN DATABASE");
                if (currentUser.IsAnonymous)
                {
                    //CURRENT USER IS ANON, REGISTER A NEW USER ACCOUNT
                    context.Trace.Write(this.GetType().ToString(), "REGISTERING " + paypalEmail);
                    MembershipCreateStatus status;
                    paypalUser          = UserDataSource.CreateUser(paypalEmail, paypalEmail, StringHelper.RandomString(8), string.Empty, string.Empty, true, 0, out status);
                    paypalUser.PayPalId = paypalPayerID;
                    paypalUser.Save();
                    Basket.Transfer(currentUser.UserId, paypalUser.UserId, true);
                    //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION
                    ExpressCheckoutSession.Delete(currentUser);
                }
                else
                {
                    //UPDATE THE PAYPAL ID OF THE CURRENTLY AUTHENTICATED USER
                    context.Trace.Write(this.GetType().ToString(), "ASSIGNING CURRENT USER TO " + paypalEmail);
                    paypalUser          = currentUser;
                    paypalUser.PayPalId = paypalPayerID;
                    paypalUser.Save();
                }
            }

            //PAYPAL HAS AUTHENTICATED THE USER
            FormsAuthentication.SetAuthCookie(paypalUser.UserName, false);
            //UPDATE THE PRIMARY ADDRESS INFORMATION FOR THE USER
            Address billingAddress = paypalUser.PrimaryAddress;

            billingAddress.FirstName   = expressCheckoutDetails.PayerInfo.PayerName.FirstName;
            billingAddress.LastName    = expressCheckoutDetails.PayerInfo.PayerName.LastName;
            billingAddress.Company     = expressCheckoutDetails.PayerInfo.PayerBusiness;
            billingAddress.Address1    = expressCheckoutDetails.PayerInfo.Address.Street1;
            billingAddress.Address2    = expressCheckoutDetails.PayerInfo.Address.Street2;
            billingAddress.City        = expressCheckoutDetails.PayerInfo.Address.CityName;
            billingAddress.Province    = expressCheckoutDetails.PayerInfo.Address.StateOrProvince;
            billingAddress.PostalCode  = expressCheckoutDetails.PayerInfo.Address.PostalCode;
            billingAddress.CountryCode = expressCheckoutDetails.PayerInfo.Address.Country.ToString();
            if (!string.IsNullOrEmpty(expressCheckoutDetails.ContactPhone))
            {
                billingAddress.Phone = expressCheckoutDetails.ContactPhone;
            }
            billingAddress.Email     = expressCheckoutDetails.PayerInfo.Payer;
            billingAddress.Residence = (!string.IsNullOrEmpty(billingAddress.Company));
            paypalUser.Save();

            //UPDATE THE SHIPPING ADDRESS IN THE BASKET
            Basket basket = paypalUser.Basket;

            basket.Package();
            foreach (BasketShipment shipment in basket.Shipments)
            {
                shipment.AddressId = billingAddress.AddressId;
            }
            basket.Save();

            //PUT PAYPAL DETAILS INTO SESSION
            context.Trace.Write(this.GetType().ToString(), "Saving ExpressCheckoutSession");
            existingSession.Token           = expressCheckoutDetails.Token;
            existingSession.TokenExpiration = DateTime.UtcNow.AddHours(3);
            existingSession.PayerID         = paypalPayerID;
            existingSession.Payer           = expressCheckoutDetails.PayerInfo.Payer;
            existingSession.Save(paypalUser);
            context.Trace.Write("Saved PayPal Token:" + existingSession.Token);
            context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString());
            return(new GetExpressCheckoutResult(paypalUser, null));
        }