Esempio n. 1
0
        /// <summary>
        /// Sets a user email
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="newEmail">New email</param>
        /// <param name="requireValidation">Require validation of new email address</param>
        public virtual void SetEmail(User user, string newEmail, bool requireValidation)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (newEmail == null)
            {
                throw new SysException("Email cannot be null");
            }

            newEmail = newEmail.Trim();
            string oldEmail = user.Email;

            if (!CommonHelper.IsValidEmail(newEmail))
            {
                throw new SysException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));
            }

            if (newEmail.Length > 100)
            {
                throw new SysException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));
            }

            var user2 = _userService.GetUserByEmail(newEmail);

            if (user2 != null && user.Id != user2.Id)
            {
                throw new SysException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
            }

            if (requireValidation)
            {
                //re-validate email
                user.EmailToRevalidate = newEmail;
                _userService.UpdateUser(user);

                //email re-validation message
                _genericAttributeService.SaveAttribute(user, SystemUserAttributeNames.EmailRevalidationToken, Guid.NewGuid().ToString());
                _workflowMessageService.SendUserEmailRevalidationMessage(user, _workContext.WorkingLanguage.Id);
            }
            else
            {
                user.Email = newEmail;
                _userService.UpdateUser(user);

                //update newsletter subscription (if required)
                if (!String.IsNullOrEmpty(oldEmail) && !oldEmail.Equals(newEmail, StringComparison.InvariantCultureIgnoreCase))
                {
                    foreach (var application in _applicationService.GetAllApplications())
                    {
                        var subscriptionOld = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndApplicationId(oldEmail, application.Id);
                        if (subscriptionOld != null)
                        {
                            subscriptionOld.Email = newEmail;
                            _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
                        }
                    }
                }
            }
        }