public ActionResult Register(RegisterModel model, string returnUrl, bool captchaValid) { //check whether registration is allowed if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled) return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }); if (_workContext.CurrentCustomer.IsRegistered()) { //Already registered customer. _authenticationService.SignOut(); //Save a new record _workContext.CurrentCustomer = _customerService.InsertGuestCustomer(); } var customer = _workContext.CurrentCustomer; //validate CAPTCHA if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid) { ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha")); } if (ModelState.IsValid) { if (_customerSettings.UsernamesEnabled && model.Username != null) { model.Username = model.Username.Trim(); } bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard; var registrationRequest = new CustomerRegistrationRequest(customer, model.Email, _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, _customerSettings.DefaultPasswordFormat, isApproved); var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest); if (registrationResult.Success) { //properties if (_dateTimeSettings.AllowCustomersToSetTimeZone) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId); } //VAT number if (_taxSettings.EuVatEnabled) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber); string vatName = ""; string vatAddress = ""; var vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out vatName, out vatAddress); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumberStatusId, (int)vatNumberStatus); //send VAT number admin notification if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted) _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId); } //form fields if (_customerSettings.GenderEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName); if (_customerSettings.DateOfBirthEnabled) { DateTime? dateOfBirth = null; try { dateOfBirth = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value); } catch { } _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth); } if (_customerSettings.CompanyEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company); if (_customerSettings.StreetAddressEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress); if (_customerSettings.StreetAddress2Enabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2); if (_customerSettings.ZipPostalCodeEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode); if (_customerSettings.CityEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City); if (_customerSettings.CountryEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId); if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId); if (_customerSettings.PhoneEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone); if (_customerSettings.FaxEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax); //newsletter if (_customerSettings.NewsletterEnabled) { //save newsletter value var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmail(model.Email); if (newsletter != null) { if (model.Newsletter) { newsletter.Active = true; _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter); } //else //{ //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list. //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter); //} } else { if (model.Newsletter) { _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription() { NewsLetterSubscriptionGuid = Guid.NewGuid(), Email = model.Email, Active = true, CreatedOnUtc = DateTime.UtcNow }); } } } //login customer now if (isApproved) _authenticationService.SignIn(customer, true); //associated with external account (if possible) TryAssociateAccountWithExternalAccount(customer); //insert default address (if possible) var defaultAddress = new Address() { FirstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName), LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName), Email = customer.Email, Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company), CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) > 0 ? (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) : null, StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) > 0 ? (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) : null, City = customer.GetAttribute<string>(SystemCustomerAttributeNames.City), Address1 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress), Address2 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress2), ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode), PhoneNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone), FaxNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Fax), CreatedOnUtc = customer.CreatedOnUtc }; if (this._addressService.IsAddressValid(defaultAddress)) { //some validation if (defaultAddress.CountryId == 0) defaultAddress.CountryId = null; if (defaultAddress.StateProvinceId == 0) defaultAddress.StateProvinceId = null; //set default address customer.Addresses.Add(defaultAddress); customer.BillingAddress = defaultAddress; customer.ShippingAddress = defaultAddress; _customerService.UpdateCustomer(customer); } //notifications if (_customerSettings.NotifyNewCustomerRegistration) _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId); switch (_customerSettings.UserRegistrationType) { case UserRegistrationType.EmailValidation: { //email validation message _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString()); _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id); //result return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }); } case UserRegistrationType.AdminApproval: { return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }); } case UserRegistrationType.Standard: { //send customer welcome message _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id); var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }); if (!String.IsNullOrEmpty(returnUrl)) redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null); return Redirect(redirectUrl); } default: { return RedirectToRoute("HomePage"); } } } else { foreach (var error in registrationResult.Errors) ModelState.AddModelError("", error); } } //If we got this far, something failed, redisplay form model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone; foreach (var tzi in _dateTimeHelper.GetSystemTimeZones()) model.AvailableTimeZones.Add(new SelectListItem() { Text = tzi.DisplayName, Value = tzi.Id, Selected = (tzi.Id == _dateTimeHelper.DefaultStoreTimeZone.Id) }); model.DisplayVatNumber = _taxSettings.EuVatEnabled; //form fields model.GenderEnabled = _customerSettings.GenderEnabled; model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled; model.CompanyEnabled = _customerSettings.CompanyEnabled; model.CompanyRequired = _customerSettings.CompanyRequired; model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled; model.StreetAddressRequired = _customerSettings.StreetAddressRequired; model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled; model.StreetAddress2Required = _customerSettings.StreetAddress2Required; model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled; model.ZipPostalCodeRequired = _customerSettings.ZipPostalCodeRequired; model.CityEnabled = _customerSettings.CityEnabled; model.CityRequired = _customerSettings.CityRequired; model.CountryEnabled = _customerSettings.CountryEnabled; model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled; model.PhoneEnabled = _customerSettings.PhoneEnabled; model.PhoneRequired = _customerSettings.PhoneRequired; model.FaxEnabled = _customerSettings.FaxEnabled; model.FaxRequired = _customerSettings.FaxRequired; model.NewsletterEnabled = _customerSettings.NewsletterEnabled; model.AcceptPrivacyPolicyEnabled = _customerSettings.AcceptPrivacyPolicyEnabled; model.UsernamesEnabled = _customerSettings.UsernamesEnabled; model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled; model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage; if (_customerSettings.CountryEnabled) { model.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" }); foreach (var c in _countryService.GetAllCountries()) { model.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (c.Id == model.CountryId) }); } if (_customerSettings.StateProvinceEnabled) { //states var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId).ToList(); if (states.Count > 0) { foreach (var s in states) model.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId) }); } else model.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" }); } } return View(model); }
/// <summary> /// Register customer /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.Customer == null) { throw new ArgumentException("Can't load current customer"); } var result = new CustomerRegistrationResult(); if (request.Customer.IsSearchEngineAccount()) { result.AddError("Search engine can't be registered"); return(result); } if (request.Customer.IsBackgroundTaskAccount()) { result.AddError("Background task account can't be registered"); return(result); } if (request.Customer.IsRegistered()) { result.AddError("Current customer is already registered"); return(result); } if (String.IsNullOrEmpty(request.Email)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided")); return(result); } if (!CommonHelper.IsValidEmail(request.Email)) { result.AddError(_localizationService.GetResource("Common.WrongEmail")); return(result); } if (String.IsNullOrWhiteSpace(request.Password)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided")); return(result); } if (_customerSettings.UsernamesEnabled) { if (String.IsNullOrEmpty(request.Username)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided")); return(result); } } //validate unique user if (_customerService.GetCustomerByEmail(request.Email) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists")); return(result); } if (_customerSettings.UsernamesEnabled) { if (_customerService.GetCustomerByUsername(request.Username) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists")); return(result); } } //at this point request is valid request.Customer.Username = request.Username; request.Customer.Email = request.Email; request.Customer.PasswordFormat = request.PasswordFormat; switch (request.PasswordFormat) { case PasswordFormat.Clear: { request.Customer.Password = request.Password; } break; case PasswordFormat.Encrypted: { request.Customer.Password = _encryptionService.EncryptText(request.Password); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); request.Customer.PasswordSalt = saltKey; request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat); } break; default: break; } request.Customer.Active = request.IsApproved; //add to 'Registered' role var registeredRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered); if (registeredRole == null) { throw new NasException("'Registered' role could not be loaded"); } request.Customer.CustomerRoles.Add(registeredRole); //remove from 'Guests' role var guestRole = request.Customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == SystemCustomerRoleNames.Guests); if (guestRole != null) { request.Customer.CustomerRoles.Remove(guestRole); } //Add reward points for customer registration (if enabled) if (_rewardPointsSettings.Enabled && _rewardPointsSettings.PointsForRegistration > 0) { request.Customer.AddRewardPointsHistoryEntry(_rewardPointsSettings.PointsForRegistration, _localizationService.GetResource("RewardPoints.Message.EarnedForRegistration")); } _customerService.UpdateCustomer(request.Customer); return(result); }
public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters) { var userFound = _openAuthenticationService.GetUser(parameters); var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null; if (AccountAlreadyExists(userFound, userLoggedIn)) { if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn)) { // The person is trying to log in as himself.. bit weird return new AuthorizationResult(OpenAuthenticationStatus.Authenticated); } var result = new AuthorizationResult(OpenAuthenticationStatus.Error); result.AddError("Account is already assigned"); return result; } if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn)) { ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters); if (AutoRegistrationIsEnabled()) { #region Register user var currentCustomer = _workContext.CurrentCustomer; var details = new RegistrationDetails(parameters); var randomPassword = CommonHelper.GenerateRandomDigitCode(20); bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard; var registrationRequest = new CustomerRegistrationRequest(currentCustomer, details.EmailAddress, _customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress, randomPassword, PasswordFormat.Clear, isApproved); var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest); if (registrationResult.Success) { //store other parameters (form fields) if (!String.IsNullOrEmpty(details.FirstName)) _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName); if (!String.IsNullOrEmpty(details.LastName)) _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName); userFound = currentCustomer; _openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters); ExternalAuthorizerHelper.RemoveParameters(); //code below is copied from CustomerController.Register method //authenticate if (isApproved) _authenticationService.SignIn(userFound ?? userLoggedIn, false); //notifications if (_customerSettings.NotifyNewCustomerRegistration) _workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId); switch (_customerSettings.UserRegistrationType) { case UserRegistrationType.EmailValidation: { //email validation message _genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString()); _workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id); //result return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation); } case UserRegistrationType.AdminApproval: { //result return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval); } case UserRegistrationType.Standard: { //send customer welcome message _workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id); //result return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard); } default: break; } } else { ExternalAuthorizerHelper.RemoveParameters(); var result = new AuthorizationResult(OpenAuthenticationStatus.Error); foreach (var error in registrationResult.Errors) result.AddError(string.Format(error)); return result; } #endregion } else if (RegistrationIsEnabled()) { return new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon); } else { ExternalAuthorizerHelper.RemoveParameters(); var result = new AuthorizationResult(OpenAuthenticationStatus.Error); result.AddError("Registration is disabled"); return result; } } if (userFound == null) { _openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters); } //migrate shopping cart _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn, true); //authenticate _authenticationService.SignIn(userFound ?? userLoggedIn, false); //activity log _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), userFound ?? userLoggedIn); return new AuthorizationResult(OpenAuthenticationStatus.Authenticated); }
/// <summary> /// Register customer /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request) { if (request == null) throw new ArgumentNullException("request"); if (request.Customer == null) throw new ArgumentException("Can't load current customer"); var result = new CustomerRegistrationResult(); if (request.Customer.IsSearchEngineAccount()) { result.AddError("Search engine can't be registered"); return result; } if (request.Customer.IsBackgroundTaskAccount()) { result.AddError("Background task account can't be registered"); return result; } if (request.Customer.IsRegistered()) { result.AddError("Current customer is already registered"); return result; } if (String.IsNullOrEmpty(request.Email)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided")); return result; } if (!CommonHelper.IsValidEmail(request.Email)) { result.AddError(_localizationService.GetResource("Common.WrongEmail")); return result; } if (String.IsNullOrWhiteSpace(request.Password)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided")); return result; } if (_customerSettings.UsernamesEnabled) { if (String.IsNullOrEmpty(request.Username)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided")); return result; } } //validate unique user if (_customerService.GetCustomerByEmail(request.Email) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists")); return result; } if (_customerSettings.UsernamesEnabled) { if (_customerService.GetCustomerByUsername(request.Username) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists")); return result; } } //at this point request is valid request.Customer.Username = request.Username; request.Customer.Email = request.Email; request.Customer.PasswordFormat = request.PasswordFormat; switch (request.PasswordFormat) { case PasswordFormat.Clear: { request.Customer.Password = request.Password; } break; case PasswordFormat.Encrypted: { request.Customer.Password = _encryptionService.EncryptText(request.Password); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); request.Customer.PasswordSalt = saltKey; request.Customer.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat); } break; default: break; } request.Customer.Active = request.IsApproved; //add to 'Registered' role var registeredRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered); if (registeredRole == null) throw new NasException("'Registered' role could not be loaded"); request.Customer.CustomerRoles.Add(registeredRole); //remove from 'Guests' role var guestRole = request.Customer.CustomerRoles.FirstOrDefault(cr => cr.SystemName == SystemCustomerRoleNames.Guests); if (guestRole != null) request.Customer.CustomerRoles.Remove(guestRole); //Add reward points for customer registration (if enabled) if (_rewardPointsSettings.Enabled && _rewardPointsSettings.PointsForRegistration > 0) request.Customer.AddRewardPointsHistoryEntry(_rewardPointsSettings.PointsForRegistration, _localizationService.GetResource("RewardPoints.Message.EarnedForRegistration")); _customerService.UpdateCustomer(request.Customer); return result; }