/// <summary> /// Loads profile for the given user /// </summary> /// <param name="userName">Name of the user to load profile for</param> /// <param name="createMissing">If <b>true</b> a profile will be created if it does not already exist.</param> /// <returns></returns> public static Profile LoadForUserName(string userName, bool createMissing) { User user = UserDataSource.LoadForUserName(userName, createMissing); if (user == null) { return(null); } return(user.Profile); }
/// <summary> /// Initializes the user context for this token. /// </summary> /// <param name="context">The HttpContext to obtain the user data from</param> public void InitUserContext(HttpContext context) { //INITIALIZE THE TOKEN FOR THIS REQUEST if (context != null) { //GET THE USER CONTEXT HttpRequest request = context.Request; if (request.IsAuthenticated) { //FOR MULTISTORE, IF AUTHENTICATED MAKE SURE THE USER IS VALID FOR THE STORE _User = UserDataSource.LoadForUserName(context.User.Identity.Name); if ((_User == null) || (_User.StoreId != this.StoreId)) { //store mismatch, expire the forms ticket User.Logout(); //redirect to this page to start over context.Response.Redirect(request.RawUrl, true); } } else { _User = UserDataSource.LoadForUserName(request.AnonymousID, true); } // UPDATE LAST ACTIVITY DATE _User.LastActivityDate = LocaleHelper.LocalNow; // CHECK FOR AN AFFILIATE INDICATOR Affiliate affiliate = AffiliateDataSource.Load(AlwaysConvert.ToInt(context.Request.QueryString[Store.GetCachedSettings().AffiliateParameterName])); if (affiliate != null && affiliate.AffiliateId != _User.AffiliateId) { // A VALID AFFILIATE WAS PASSED AND IS NOT THE ONE ASSOCIATED WITH USER // SHOULD WE UPDATE THE USER? StoreSettingCollection settings = Store.GetCachedSettings(); if (settings.AffiliateReferralRule == ReferralRule.NewSignupsOrExistingUsersOverrideAffiliate || _User.AffiliateId == 0) { // THE RULE IS TO ALWAYS OVERRIDE // OR AN EXISTING USER WITH NO AFFILIATE SET WITH EXISTING USERS NO OVERRIDE OPTION // (IF IT WERE A NEW USER CREATED BY THIS REQUEST, AFFILIATEID WOULD ALREADY BE SET) // AFFILIATE SHOULD BE UPDATED FOR THE TARGET USER _User.AffiliateId = affiliate.AffiliateId; _User.AffiliateReferralDate = _User.LastActivityDate; } } this.UserId = _User.UserId; if (_User.UserId != 0) { _User.Save(); } } }
protected void ForgotPasswordNextButton_Click(object sender, EventArgs e) { if (Page.IsValid) { User user = UserDataSource.LoadForUserName(ForgotPasswordUserName.Text); if (user != null) { user.GeneratePasswordRequest(); ForgotPasswordPanel.Visible = false; EmailSentPanel.Visible = true; EmailSentHelpText.Text = string.Format(EmailSentHelpText.Text, user.Email); } else { ForgotPasswordUserNameValidator.IsValid = false; } } }
protected void LoginButton_Click(object sender, EventArgs e) { _LastPasswordValue = Password.Text; if (Page.IsValid) { //VALIDATE CAPTCHA if (!trCaptchaField.Visible || (CaptchaImage.Authenticate(CaptchaInput.Text))) { if (Membership.ValidateUser(UserName.Text, Password.Text)) { //MIGRATE USER IF NEEDED int newUserId = UserDataSource.GetUserId(UserName.Text); if ((AbleContext.Current.UserId != newUserId) && (newUserId != 0)) { CommerceBuilder.Users.User.Migrate(AbleContext.Current.User, UserDataSource.Load(newUserId)); AbleContext.Current.UserId = newUserId; } //HANDLE LOGIN PROCESSING if (RememberUserName.Checked) { HttpCookie cookie = new HttpCookie("UserName", UserName.Text); cookie.Expires = DateTime.MaxValue; Response.Cookies.Add(cookie); } else { Response.Cookies.Add(new HttpCookie("UserName", "")); } // CHECK PASSWORD FOR EXPIRATION User newUser = UserDataSource.Load(newUserId); MerchantPasswordPolicy policy = new MerchantPasswordPolicy(); if (policy.IsPasswordExpired(newUser)) { ShowPasswordExpired(); } else { // LOGIN SUCCESSFUL, REDIRECT FormsAuthentication.RedirectFromLoginPage(UserName.Text, false); } } else { User user = UserDataSource.LoadForUserName(UserName.Text); if (user != null) { if (!user.IsApproved) { AccountDisabled.IsValid = false; } else { MerchantPasswordPolicy policy = new MerchantPasswordPolicy(); int remainingTries = policy.MaxAttempts - user.FailedPasswordAttemptCount; if (!user.IsLockedOut && remainingTries > 0) { InvalidLogin.ErrorMessage += " You have {0} tries remaining."; InvalidLogin.ErrorMessage = String.Format(InvalidLogin.ErrorMessage, remainingTries); InvalidLogin.IsValid = false; } else { AccountLocked.ErrorMessage = String.Format(AccountLocked.ErrorMessage, policy.LockoutPeriod); AccountLocked.IsValid = false; } } } else { InvalidLogin.IsValid = false; } RefreshCaptcha(); } } else { CustomValidator invalidInput = new CustomValidator(); invalidInput.ValidationGroup = "Login"; invalidInput.Text = "*"; invalidInput.ErrorMessage = "You did not input the verification number correctly."; invalidInput.IsValid = false; phCaptchaValidators.Controls.Add(invalidInput); RefreshCaptcha(); } } }
protected void ChangePasswordButton_Click(object sender, EventArgs e) { if (Page.IsValid) { //VERIFY THE GIVEN USERNAME IS VALID User user = UserDataSource.LoadForUserName(UserName.Text); if ((user != null) && !string.IsNullOrEmpty(UserName.Text) && !string.IsNullOrEmpty(_LastPasswordValue)) { //VERIFY CURRENT PASSWORD IS CORRECT if (Membership.ValidateUser(UserName.Text, _LastPasswordValue)) { //VERIFY THE NEW PASSWORD MEETS POLICY MerchantPasswordPolicy policy = new MerchantPasswordPolicy(); PasswordTestResult result = policy.TestPasswordWithFeedback(user, NewPassword.Text); if ((result & PasswordTestResult.Success) == PasswordTestResult.Success && !NewPassword.Text.Equals(_LastPasswordValue)) { // PASSWORD CHANGE SUCCEEDED, REDIRECT TO THE MERCHANT ADMIN user.SetPassword(NewPassword.Text); FormsAuthentication.SetAuthCookie(UserName.Text, false); Response.Redirect("~/Admin/Default.aspx"); } else { //REDISPLAY THE PASSWORD REQUIREMENST ShowPasswordExpired(); //"Your new password did not meet the following minimum requirements:<br/>"; if ((result & PasswordTestResult.PasswordTooShort) == PasswordTestResult.PasswordTooShort) { AddPasswordExpiredValidator(string.Format(PasswordPolicyLength.Text, policy.MinLength)); } if ((result & PasswordTestResult.RequireLower) == PasswordTestResult.RequireLower) { AddPasswordExpiredValidator("New password must contain at least one lowercase letter.<br/>"); } if ((result & PasswordTestResult.RequireUpper) == PasswordTestResult.RequireUpper) { AddPasswordExpiredValidator("New password must contain at least one uppercase letter.<br/> "); } if ((result & PasswordTestResult.RequireNonAlpha) == PasswordTestResult.RequireNonAlpha) { AddPasswordExpiredValidator("New password must contain at least one non-letter.<br/> "); } if ((result & PasswordTestResult.RequireNumber) == PasswordTestResult.RequireNumber) { AddPasswordExpiredValidator("New password must contain at least one number.<br/> "); } if ((result & PasswordTestResult.RequireSymbol) == PasswordTestResult.RequireSymbol) { AddPasswordExpiredValidator("New password must contain at least one symbol.<br/> "); } if ((result & PasswordTestResult.PasswordHistoryLimitation) == PasswordTestResult.PasswordHistoryLimitation) { AddPasswordExpiredValidator("You have recently used this password.<br/>"); } if (NewPassword.Text.Equals(_LastPasswordValue)) { AddPasswordExpiredValidator("You new password must be different from your current password.<br/>"); } } } } } }
protected void LoginButton_Click(object sender, EventArgs e) { _LastPasswordValue = Password.Text; User loginUser = UserDataSource.LoadForUserName(UserName.Text); if (loginUser != null) { bool stillNeedsCaptcha = false; if ((loginUser.IsAdmin) && (!trCaptchaField.Visible)) { stillNeedsCaptcha = (new MerchantPasswordPolicy()).ImageCaptcha; } if (!stillNeedsCaptcha) { //EITHER THIS IS NOT AN ADMIN USER, OR THE CAPTCHA IS ALREADY VISIBLE if ((!trCaptchaField.Visible) || (CaptchaImage.Authenticate(CaptchaInput.Text))) { //CAPTCHA IS HIDDEN OR VALIDATED, PROCEED WITH LOGIN ATTEMPT if (Membership.ValidateUser(UserName.Text, Password.Text)) { //LOGIN SUCCEEDED, MIGRATE USER IF NEEDED int newUserId = loginUser.Id; int oldUserId = AbleContext.Current.UserId; if ((oldUserId != newUserId) && (newUserId != 0)) { User.Migrate(AbleContext.Current.User, UserDataSource.Load(newUserId)); AbleContext.Current.UserId = newUserId; } //HANDLE LOGIN PROCESSING if (trRememberMe.Visible && RememberUserName.Checked) { HttpCookie cookie = new HttpCookie("UserName", UserName.Text); cookie.Expires = DateTime.MaxValue; Response.Cookies.Add(cookie); } else { Response.Cookies.Add(new HttpCookie("UserName", "")); } //CHECK FOR EXPIRED PASSWORDS PasswordPolicy policy; if (loginUser.IsAdmin) { policy = new MerchantPasswordPolicy(); } else { policy = new CustomerPasswordPolicy(); } if (policy.IsPasswordExpired(loginUser)) { ShowPasswordExpired(policy, loginUser); } else { switch (AbleContext.Current.Store.Settings.RestrictStoreAccess) { case AccessRestrictionType.AuthorizedGroupsOnly: if (!loginUser.IsAdmin && !loginUser.IsAuthorizedUser) { // STORE ACCESS IS RESTRICTED TO AUTHORIZED USERS ONLY LoginPanel.Visible = false; PasswordExpiredPanel.Visible = false; StoreFrontAccessDeniedPanel.Visible = true; } else { FormsAuthentication.RedirectFromLoginPage(UserName.Text, false); } break; case AccessRestrictionType.RegisteredUsersOnly: case AccessRestrictionType.None: //REDIRECT TO THE STANDARD PAGE FormsAuthentication.RedirectFromLoginPage(UserName.Text, false); break; } } } else { if (loginUser != null) { if (!loginUser.IsApproved) { AccountDisabled.IsValid = false; } else { PasswordPolicy policy; if (loginUser.IsAdmin) { policy = new MerchantPasswordPolicy(); } else { policy = new CustomerPasswordPolicy(); } int remainingTries = policy.MaxAttempts - loginUser.FailedPasswordAttemptCount; if (!loginUser.IsLockedOut && remainingTries > 0) { InvalidLogin.ErrorMessage += " You have {0} tries remaining."; InvalidLogin.ErrorMessage = String.Format(InvalidLogin.ErrorMessage, remainingTries); InvalidLogin.IsValid = false; } else { AccountLocked.ErrorMessage = String.Format(AccountLocked.ErrorMessage, policy.LockoutPeriod); AccountLocked.IsValid = false; } } } else { InvalidLogin.IsValid = false; } } } else { //CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE CustomValidator invalidInput = new CustomValidator(); invalidInput.ValidationGroup = "Login"; 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(); } } else { //THIS IS AN ADMIN USER AND CAPTCHA IS NOT DISPLAYED YET trCaptchaField.Visible = true; trCaptchaImage.Visible = true; trRememberMe.Visible = _EnableAdminRememberMe; CaptchaImage.ChallengeText = StringHelper.RandomNumber(6); CustomValidator needsCaptcha = new CustomValidator(); needsCaptcha.ValidationGroup = "Login"; needsCaptcha.Text = "*"; needsCaptcha.ErrorMessage = "Please type the verification number to log in."; needsCaptcha.IsValid = false; phCaptchaValidators.Controls.Add(needsCaptcha); Password.Attributes.Add("value", Password.Text); } } else { //THIS IS AN INVALID USER NAME InvalidLogin.IsValid = false; } }
protected void LoginButton_Click(object sender, EventArgs e) { _LastPasswordValue = Password.Text; User loginUser = UserDataSource.LoadForUserName(UserName.Text); if (loginUser != null) { bool stillNeedsCaptcha = false; if ((loginUser.IsAdmin) && (!trCaptchaField.Visible)) { stillNeedsCaptcha = (new MerchantPasswordPolicy()).ImageCaptcha; } if (!stillNeedsCaptcha) { // IF CAPTCHA IS REQUIRED CHECK IF THE ENTRY IS VALID if ((!trCaptchaField.Visible) || (CaptchaImage.Authenticate(CaptchaInput.Text))) { // CAPTCHA IS HIDDEN OR VALIDATED, PROCEED WITH LOGIN ATTEMPT if (Membership.ValidateUser(UserName.Text, Password.Text)) { //LOGIN SUCCEEDED, MIGRATE USER IF NEEDED int newUserId = loginUser.Id; int oldUserId = AbleContext.Current.UserId; if ((oldUserId != newUserId) && (newUserId != 0)) { CommerceBuilder.Users.User.Migrate(AbleContext.Current.User, UserDataSource.Load(newUserId)); AbleContext.Current.UserId = newUserId; } //HANDLE LOGIN PROCESSING if (RememberUserName.Checked) { HttpCookie cookie = new HttpCookie("UserName", UserName.Text); cookie.Expires = DateTime.MaxValue; Response.Cookies.Add(cookie); } else { Response.Cookies.Add(new HttpCookie("UserName", "")); } //CHECK FOR EXPIRED PASSWORDS PasswordPolicy policy; if (loginUser.IsAdmin) { policy = new MerchantPasswordPolicy(); } else { policy = new CustomerPasswordPolicy(); } if (policy.IsPasswordExpired(loginUser)) { ShowPasswordExpired(policy, loginUser); } else { //REDIRECT TO THE STANDARD PAGE FormsAuthentication.SetAuthCookie(UserName.Text, false); Response.Redirect("EditBillAddress.aspx"); } } else { if (loginUser != null) { if (!loginUser.IsApproved) { AccountDisabled.IsValid = false; } else { PasswordPolicy policy; if (loginUser.IsAdmin) { policy = new MerchantPasswordPolicy(); } else { policy = new CustomerPasswordPolicy(); } int remainingTries = policy.MaxAttempts - loginUser.FailedPasswordAttemptCount; if (!loginUser.IsLockedOut && remainingTries > 0) { InvalidLogin.ErrorMessage += " You have {0} tries remaining."; InvalidLogin.ErrorMessage = String.Format(InvalidLogin.ErrorMessage, remainingTries); InvalidLogin.IsValid = false; } else { AccountLocked.ErrorMessage = String.Format(AccountLocked.ErrorMessage, policy.LockoutPeriod); AccountLocked.IsValid = false; } } } else { InvalidLogin.IsValid = false; } } } else { // CAPTCHA IS VISIBLE AND DID NOT AUTHENTICATE trCaptchaImage.Visible = true; trCaptchaField.Visible = true; CustomValidator invalidInput = new CustomValidator(); invalidInput.ID = Guid.NewGuid().ToString(); invalidInput.ValidationGroup = "Login"; 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(); } } else { // CAPTCHA IS REQUIRED BUT IT IS NOT DISPLAYED YET trCaptchaField.Visible = true; trCaptchaImage.Visible = true; CaptchaImage.ChallengeText = StringHelper.RandomNumber(6); CustomValidator needsCaptcha = new CustomValidator(); needsCaptcha.ID = "CaptchaRequiredValidator"; needsCaptcha.ValidationGroup = "Login"; needsCaptcha.Text = "*"; needsCaptcha.ErrorMessage = "Please type the verification number to log in."; needsCaptcha.IsValid = false; phCaptchaValidators.Controls.Add(needsCaptcha); Password.Attributes.Add("value", Password.Text); } } else { //THIS IS AN INVALID USER NAME InvalidLogin.IsValid = false; } }
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)); }