private UserCreateStatus ValidateForProfanity(UserInfo user)
        {
            var portalSecurity = new PortalSecurity();
            var createStatus = UserCreateStatus.AddUser;

            Hashtable settings = UserController.GetUserSettings(user.PortalID);
            bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]);

            //Validate Profanity
            if (useProfanityFilter)
            {
                if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity))
                {
                    createStatus = UserCreateStatus.InvalidUserName;
                }
                if (!String.IsNullOrEmpty(user.DisplayName))
                {
                    if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                    {
                        createStatus = UserCreateStatus.InvalidDisplayName;
                    }
                }
            }
            return createStatus;
        }
示例#2
0
        private bool Validate()
        {
            CreateStatus = UserCreateStatus.AddUser;
            var portalSecurity = new PortalSecurity();

            //Check User Editor
            bool _IsValid = userForm.IsValid;

            if (RegistrationFormType == 0)
            {
                //Update UserName
                if (UseEmailAsUserName)
                {
                    User.Username = User.Email;
                    if (String.IsNullOrEmpty(User.DisplayName))
                    {
                        User.DisplayName = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal));
                    }
                }

                //Check Password is valid
                if (!RandomPassword)
                {
                    //Check Password is Valid
                    if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(User.Membership.Password))
                    {
                        CreateStatus = UserCreateStatus.InvalidPassword;
                    }

                    if (RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType))
                    {
                        if (User.Membership.Password != User.Membership.PasswordConfirm)
                        {
                            CreateStatus = UserCreateStatus.PasswordMismatch;
                        }
                    }
                }
                else
                {
                    //Generate a random password for the user
                    User.Membership.Password        = UserController.GeneratePassword();
                    User.Membership.PasswordConfirm = User.Membership.Password;
                }
            }
            else
            {
                //Set Username to Email
                if (String.IsNullOrEmpty(User.Username))
                {
                    User.Username = User.Email;
                }

                //Set DisplayName
                if (String.IsNullOrEmpty(User.DisplayName))
                {
                    User.DisplayName = String.IsNullOrEmpty(User.FirstName + " " + User.LastName)
                                           ? User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal))
                                           : User.FirstName + " " + User.LastName;
                }

                //Random Password
                if (String.IsNullOrEmpty(User.Membership.Password))
                {
                    //Generate a random password for the user
                    User.Membership.Password = UserController.GeneratePassword();
                }

                //Password Confirm
                if (!String.IsNullOrEmpty(User.Membership.PasswordConfirm))
                {
                    if (User.Membership.Password != User.Membership.PasswordConfirm)
                    {
                        CreateStatus = UserCreateStatus.PasswordMismatch;
                    }
                }
            }

            ////Validate Exclude Terms
            //if (!String.IsNullOrEmpty(ExcludeTerms))
            //{
            //    string[] excludeTerms = ExcludeTerms.Split(',');
            //    foreach (string term in excludeTerms)
            //    {
            //        var trimmedTerm = term.Trim().ToLowerInvariant();
            //        if (User.Username.ToLowerInvariant().Contains(trimmedTerm))
            //        {
            //            CreateStatus = UserCreateStatus.InvalidUserName;
            //        }
            //        if (User.DisplayName.ToLowerInvariant().Contains(trimmedTerm))
            //        {
            //            CreateStatus = UserCreateStatus.InvalidDisplayName;
            //        }
            //    }
            //}

            //Validate Profanity
            if (UseProfanityFilter)
            {
                if (!portalSecurity.ValidateInput(User.Username, PortalSecurity.FilterFlag.NoProfanity))
                {
                    CreateStatus = UserCreateStatus.InvalidUserName;
                }
                if (!String.IsNullOrEmpty(User.DisplayName))
                {
                    if (!portalSecurity.ValidateInput(User.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                    {
                        CreateStatus = UserCreateStatus.InvalidDisplayName;
                    }
                }
            }

            //Validate Unique User Name
            UserInfo user = UserController.GetUserByName(PortalId, User.Username);

            if (user != null)
            {
                if (UseEmailAsUserName)
                {
                    CreateStatus = UserCreateStatus.DuplicateEmail;
                }
                else
                {
                    CreateStatus = UserCreateStatus.DuplicateUserName;
                    int    i        = 1;
                    string userName = null;
                    while (user != null)
                    {
                        userName = User.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                        user     = UserController.GetUserByName(PortalId, userName);
                        i++;
                    }
                    User.Username = userName;
                }
            }

            //Validate Unique Display Name
            if (CreateStatus == UserCreateStatus.AddUser && RequireUniqueDisplayName)
            {
                user = TestableUserController.Instance.GetUserByDisplayname(PortalId, User.DisplayName);
                if (user != null)
                {
                    CreateStatus = UserCreateStatus.DuplicateDisplayName;
                    int    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                        user        = TestableUserController.Instance.GetUserByDisplayname(PortalId, displayName);
                        i++;
                    }
                    User.DisplayName = displayName;
                }
            }

            //Check Question/Answer
            if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer)
            {
                if (string.IsNullOrEmpty(User.Membership.PasswordQuestion))
                {
                    //Invalid Question
                    CreateStatus = UserCreateStatus.InvalidQuestion;
                }
                if (CreateStatus == UserCreateStatus.AddUser)
                {
                    if (string.IsNullOrEmpty(User.Membership.PasswordAnswer))
                    {
                        //Invalid Question
                        CreateStatus = UserCreateStatus.InvalidAnswer;
                    }
                }
            }

            if (CreateStatus != UserCreateStatus.AddUser)
            {
                _IsValid = false;
            }
            return(_IsValid);
        }
            //public static ActionResult Register(RegisterationDetails registerationDetails)
            //{
            //    ActionResult actionResult = new ActionResult();
            //    var portalSettings = registerationDetails.PortalSettings;
            //    var username = registerationDetails.UserName;
            //    var email = registerationDetails.Email;

            //    Requires.NotNullOrEmpty("email", email);

            //    var disallowRegistration = !registerationDetails.IgnoreRegistrationMode && ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) || (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration));

            //    if (disallowRegistration)
            //        throw new Exception(Localization.GetString("RegistrationNotAllowed", Components.Constants.LocalResourcesFile));

            //    //initial creation of the new User object
            //    var newUser = new UserInfo
            //    {
            //        PortalID = portalSettings.PortalId,
            //        Email = email
            //    };

            //    var cleanUsername = PortalSecurity.Instance.InputFilter(username,
            //                                              PortalSecurity.FilterFlag.NoScripting |
            //                                              PortalSecurity.FilterFlag.NoAngleBrackets |
            //                                              PortalSecurity.FilterFlag.NoMarkup);

            //    if (!cleanUsername.Equals(username))
            //        throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));

            //    var valid = UserController.Instance.IsValidUserName(username);

            //    if (!valid)
            //        throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));

            //    //ensure this user doesn't exist
            //    if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null)
            //        throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent", Components.Constants.LocalResourcesFile));

            //    //set username as email if not specified
            //    newUser.Username = string.IsNullOrEmpty(username) ? email : username;

            //    if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword)
            //        newUser.Membership.Password = registerationDetails.Password;
            //    else
            //        //Generate a random password for the user
            //        newUser.Membership.Password = UserController.GeneratePassword();

            //    newUser.Membership.PasswordConfirm = newUser.Membership.Password;

            //    //set other profile properties
            //    newUser.Profile.PreferredLocale = new Localization().CurrentUICulture;
            //    newUser.Profile.InitialiseProfile(portalSettings.PortalId);
            //    newUser.Profile.PreferredTimeZone = portalSettings.TimeZone;

            //    //derive display name from supplied firstname, lastname or from email
            //    if (!string.IsNullOrEmpty(registerationDetails.FirstName) && !string.IsNullOrEmpty(registerationDetails.LastName))
            //    {
            //        newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName;
            //        newUser.FirstName = registerationDetails.FirstName;
            //        newUser.LastName = registerationDetails.LastName;
            //    }
            //    else
            //        newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));

            //    //read all the user account settings
            //    var settings = UserController.GetUserSettings(portalSettings.PortalId);

            //    //Verify Profanity filter
            //    if (GetBoolSetting(settings, "Registration_UseProfanityFilter"))
            //    {
            //        var portalSecurity = PortalSecurity.Instance;
            //        if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
            //            throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed", Components.Constants.LocalResourcesFile));
            //    }

            //    //Email Address Validation
            //    var emailValidator = GetStringSetting(settings, "Security_EmailValidation");
            //    if (!string.IsNullOrEmpty(emailValidator))
            //    {
            //        var regExp = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            //        var matches = regExp.Matches(newUser.Email);
            //        if (matches.Count == 0)
            //            throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed", Components.Constants.LocalResourcesFile));
            //    }

            //    //Excluded Terms Verification
            //    var excludeRegex = GetExcludeTermsRegex(settings);
            //    if (!string.IsNullOrEmpty(excludeRegex))
            //    {
            //        var regExp = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            //        var matches = regExp.Matches(newUser.Username);
            //        if (matches.Count > 0)
            //            throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed", Components.Constants.LocalResourcesFile));
            //    }

            //    //User Name Validation
            //    var userNameValidator = GetStringSetting(settings, "Security_UserNameValidation");
            //    if (!string.IsNullOrEmpty(userNameValidator))
            //    {
            //        var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            //        var matches = regExp.Matches(newUser.Username);
            //        if (matches.Count == 0)
            //            throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed", Components.Constants.LocalResourcesFile));
            //    }

            //    //ensure unique username
            //    var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username);
            //    if (user != null)
            //    {
            //        if (GetBoolSetting(settings, "Registration_UseEmailAsUserName"))
            //            throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail));

            //        var i = 1;
            //        string userName = null;
            //        while (user != null)
            //        {
            //            userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
            //            user = UserController.GetUserByName(portalSettings.PortalId, userName);
            //            i++;
            //        }
            //        newUser.Username = userName;
            //    }

            //    //ensure unique display name
            //    if (GetBoolSetting(settings, "Registration_RequireUniqueDisplayName"))
            //    {
            //        user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName);
            //        if (user != null)
            //        {
            //            var i = 1;
            //            string displayName = null;
            //            while (user != null)
            //            {
            //                displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
            //                user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName);
            //                i++;
            //            }
            //            newUser.DisplayName = displayName;
            //        }
            //    }

            //    //Update display name format
            //    var displaynameFormat = GetStringSetting(settings, "Security_DisplayNameFormat");
            //    if (!string.IsNullOrEmpty(displaynameFormat))
            //        newUser.UpdateDisplayName(displaynameFormat);

            //    //membership is approved only for public registration
            //    newUser.Membership.Approved = (registerationDetails.IgnoreRegistrationMode || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize;
            //    newUser.Membership.PasswordQuestion = registerationDetails.Question;
            //    newUser.Membership.PasswordAnswer = registerationDetails.Answer;
            //    //final creation of user
            //    var createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify);

            //    //clear cache
            //    if (createStatus == UserCreateStatus.Success)
            //        CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId));

            //    if (createStatus != UserCreateStatus.Success)
            //        throw new Exception(UserController.GetUserCreateStatus(createStatus));

            //    //            if (registerationDetails.IgnoreRegistrationMode)
            //    //            {
            //    //                Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
            //    //                return UserBasicDto.FromUserInfo(newUser);
            //    //            }

            //    //send notification to portal administrator of new user registration
            //    //check the receive notification setting first, but if register type is Private, we will always send the notification email.
            //    //because the user need administrators to do the approve action so that he can continue use the website.
            //    if (!registerationDetails.IgnoreRegistrationMode && (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration))
            //    {
            //        Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings);
            //        SendAdminNotification(newUser, portalSettings);
            //    }
            //    if (actionResult.IsSuccess)
            //        actionResult.Data = UserBasicDto.FromUserInfo(newUser);
            //    return actionResult;
            //}

            public static UserBasicDto Register(RegisterationDetails registerationDetails)
            {
                PortalSettings portalSettings = registerationDetails.PortalSettings;
                string         username       = registerationDetails.UserName;
                string         email          = registerationDetails.Email;

                Requires.NotNullOrEmpty("email", email);

                bool disallowRegistration = !registerationDetails.IgnoreRegistrationMode &&
                                            ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) ||
                                             (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration));

                if (disallowRegistration)
                {
                    throw new Exception(Localization.GetString("RegistrationNotAllowed", Components.Constants.LocalResourcesFile));
                }

                //initial creation of the new User object
                UserInfo newUser = new UserInfo
                {
                    PortalID = portalSettings.PortalId,
                    Email    = email
                };

                string cleanUsername = PortalSecurity.Instance.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup);

                if (!cleanUsername.Equals(username))
                {
                    throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
                }

                bool valid = UserController.Instance.IsValidUserName(username);

                if (!valid)
                {
                    throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
                }

                //ensure this user doesn't exist
                if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null)
                {
                    throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent", Components.Constants.LocalResourcesFile));
                }

                //set username as email if not specified
                newUser.Username = string.IsNullOrEmpty(username) ? email : username;

                if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword)
                {
                    newUser.Membership.Password = registerationDetails.Password;
                }
                else
                {
                    //Generate a random password for the user
                    newUser.Membership.Password = UserController.GeneratePassword();
                }

                newUser.Membership.PasswordConfirm = newUser.Membership.Password;

                //set other profile properties
                newUser.Profile.PreferredLocale = new Localization().CurrentUICulture;
                newUser.Profile.InitialiseProfile(portalSettings.PortalId);
                newUser.Profile.PreferredTimeZone = portalSettings.TimeZone;

                //derive display name from supplied firstname, lastname or from email
                if (!string.IsNullOrEmpty(registerationDetails.FirstName))
                {
                    newUser.DisplayName = registerationDetails.FirstName.Trim();
                    if (registerationDetails.FirstName.Trim().Split(' ').Length > 0)
                    {
                        newUser.FirstName = registerationDetails.FirstName.Split(' ')[0].Trim();
                    }

                    if (registerationDetails.FirstName.Trim().Split(' ').Length > 1)
                    {
                        newUser.LastName = registerationDetails.FirstName.Split(' ')[1].Trim();
                    }
                }
                else
                {
                    newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));
                }

                //read all the user account settings
                Hashtable settings = UserController.GetUserSettings(portalSettings.PortalId);

                //Verify Profanity filter
                if (GetBoolSetting(settings, "Registration_UseProfanityFilter"))
                {
                    PortalSecurity portalSecurity = PortalSecurity.Instance;
                    if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                    {
                        throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed", Components.Constants.LocalResourcesFile));
                    }
                }

                //Email Address Validation
                string emailValidator = GetStringSetting(settings, "Security_EmailValidation");

                if (!string.IsNullOrEmpty(emailValidator))
                {
                    Regex           regExp  = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    MatchCollection matches = regExp.Matches(newUser.Email);
                    if (matches.Count == 0)
                    {
                        throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed", Components.Constants.LocalResourcesFile));
                    }
                }

                //Excluded Terms Verification
                string excludeRegex = GetExcludeTermsRegex(settings);

                if (!string.IsNullOrEmpty(excludeRegex))
                {
                    Regex           regExp  = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    MatchCollection matches = regExp.Matches(newUser.Username);
                    if (matches.Count > 0)
                    {
                        throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed", Components.Constants.LocalResourcesFile));
                    }
                }

                //User Name Validation
                string userNameValidator = GetStringSetting(settings, "Security_UserNameValidation");

                if (!string.IsNullOrEmpty(userNameValidator))
                {
                    Regex           regExp  = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    MatchCollection matches = regExp.Matches(newUser.Username);
                    if (matches.Count == 0)
                    {
                        throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed", Components.Constants.LocalResourcesFile));
                    }
                }

                //ensure unique username
                UserInfo user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username);

                if (user != null)
                {
                    if (GetBoolSetting(settings, "Registration_UseEmailAsUserName"))
                    {
                        throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail));
                    }

                    int    i        = 1;
                    string userName = null;
                    while (user != null)
                    {
                        userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                        user     = UserController.GetUserByName(portalSettings.PortalId, userName);
                        i++;
                    }
                    newUser.Username = userName;
                }

                //ensure unique display name
                if (GetBoolSetting(settings, "Registration_RequireUniqueDisplayName"))
                {
                    user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName);
                    if (user != null)
                    {
                        int    i           = 1;
                        string displayName = null;
                        while (user != null)
                        {
                            displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                            user        = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName);
                            i++;
                        }
                        newUser.DisplayName = displayName;
                    }
                }

                //Update display name format
                string displaynameFormat = GetStringSetting(settings, "Security_DisplayNameFormat");

                if (!string.IsNullOrEmpty(displaynameFormat))
                {
                    newUser.UpdateDisplayName(displaynameFormat);
                }

                //membership is approved only for public registration
                newUser.Membership.Approved         = (registerationDetails.IgnoreRegistrationMode || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize;
                newUser.Membership.PasswordQuestion = registerationDetails.Question;
                newUser.Membership.PasswordAnswer   = registerationDetails.Answer;
                //final creation of user
                UserCreateStatus createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify);

                //clear cache
                if (createStatus == UserCreateStatus.Success)
                {
                    CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId));
                }

                if (createStatus != UserCreateStatus.Success)
                {
                    throw new Exception(UserController.GetUserCreateStatus(createStatus));
                }

                //            if (registerationDetails.IgnoreRegistrationMode)
                //            {
                //                Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
                //                return UserBasicDto.FromUserInfo(newUser);
                //            }

                //send notification to portal administrator of new user registration
                //check the receive notification setting first, but if register type is Private, we will always send the notification email.
                //because the user need administrators to do the approve action so that he can continue use the website.
                if (!registerationDetails.IgnoreRegistrationMode && (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration))
                {
                    Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings);
                    SendAdminNotification(newUser, portalSettings);
                }

                return(UserBasicDto.FromUserInfo(newUser));
            }
        private bool Validate()
        {
            if (!string.IsNullOrEmpty(gotcha.Value))
            {
                return(false);
            }

            CreateStatus = UserCreateStatus.AddUser;
            var portalSecurity = new PortalSecurity();

            //Check User Editor
            bool _IsValid = userForm.IsValid;

            if (PortalSettings.Registration.RegistrationFormType == 0)
            {
                //Update UserName
                if (PortalSettings.Registration.UseEmailAsUserName)
                {
                    User.Username = User.Email;
                    if (String.IsNullOrEmpty(User.DisplayName))
                    {
                        User.DisplayName = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal));
                    }
                }

                //Check Password is valid
                if (!PortalSettings.Registration.RandomPassword)
                {
                    //Check Password is Valid
                    if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(User.Membership.Password))
                    {
                        CreateStatus = UserCreateStatus.InvalidPassword;
                    }

                    if (PortalSettings.Registration.RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType))
                    {
                        if (User.Membership.Password != User.Membership.PasswordConfirm)
                        {
                            CreateStatus = UserCreateStatus.PasswordMismatch;
                        }
                    }
                }
                else
                {
                    //Generate a random password for the user
                    User.Membership.Password        = UserController.GeneratePassword();
                    User.Membership.PasswordConfirm = User.Membership.Password;
                }
            }
            else
            {
                //Set Username to Email
                if (String.IsNullOrEmpty(User.Username))
                {
                    User.Username = User.Email;
                }

                //Set DisplayName
                if (String.IsNullOrEmpty(User.DisplayName))
                {
                    User.DisplayName = String.IsNullOrEmpty(User.FirstName + " " + User.LastName)
                                                                                   ? User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal))
                                                                                   : User.FirstName + " " + User.LastName;
                }

                //Random Password
                if (String.IsNullOrEmpty(User.Membership.Password))
                {
                    //Generate a random password for the user
                    User.Membership.Password = UserController.GeneratePassword();
                }

                //Password Confirm
                if (!String.IsNullOrEmpty(User.Membership.PasswordConfirm))
                {
                    if (User.Membership.Password != User.Membership.PasswordConfirm)
                    {
                        CreateStatus = UserCreateStatus.PasswordMismatch;
                    }
                }
            }

            //Validate banned password
            var settings = new MembershipPasswordSettings(User.PortalID);

            if (settings.EnableBannedList)
            {
                var m = new MembershipPasswordController();
                if (m.FoundBannedPassword(User.Membership.Password) || User.Username == User.Membership.Password)
                {
                    CreateStatus = UserCreateStatus.BannedPasswordUsed;
                }
            }
            //Validate Profanity
            if (PortalSettings.Registration.UseProfanityFilter)
            {
                if (!portalSecurity.ValidateInput(User.Username, PortalSecurity.FilterFlag.NoProfanity))
                {
                    CreateStatus = UserCreateStatus.InvalidUserName;
                }
                if (!String.IsNullOrEmpty(User.DisplayName))
                {
                    if (!portalSecurity.ValidateInput(User.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                    {
                        CreateStatus = UserCreateStatus.InvalidDisplayName;
                    }
                }
            }

            //Validate Unique User Name
            UserInfo user = UserController.GetUserByName(PortalId, User.Username);

            if (user != null)
            {
                if (PortalSettings.Registration.UseEmailAsUserName)
                {
                    CreateStatus = UserCreateStatus.DuplicateEmail;
                }
                else
                {
                    CreateStatus = UserCreateStatus.DuplicateUserName;
                    int    i        = 1;
                    string userName = null;
                    while (user != null)
                    {
                        userName = User.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                        user     = UserController.GetUserByName(PortalId, userName);
                        i++;
                    }
                    User.Username = userName;
                }
            }

            //Validate Unique Display Name
            if (CreateStatus == UserCreateStatus.AddUser && PortalSettings.Registration.RequireUniqueDisplayName)
            {
                user = UserController.Instance.GetUserByDisplayname(PortalId, User.DisplayName);
                if (user != null)
                {
                    CreateStatus = UserCreateStatus.DuplicateDisplayName;
                    int    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                        user        = UserController.Instance.GetUserByDisplayname(PortalId, displayName);
                        i++;
                    }
                    User.DisplayName = displayName;
                }
            }

            //Check Question/Answer
            if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer)
            {
                if (string.IsNullOrEmpty(User.Membership.PasswordQuestion))
                {
                    //Invalid Question
                    CreateStatus = UserCreateStatus.InvalidQuestion;
                }
                if (CreateStatus == UserCreateStatus.AddUser)
                {
                    if (string.IsNullOrEmpty(User.Membership.PasswordAnswer))
                    {
                        //Invalid Question
                        CreateStatus = UserCreateStatus.InvalidAnswer;
                    }
                }
            }

            if (CreateStatus != UserCreateStatus.AddUser)
            {
                _IsValid = false;
            }
            return(_IsValid);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="AuthenticationType"></param>
        /// <param name="newUser"></param>
        /// <returns></returns>
        public UserCreateStatus Validate(int portalId, string AuthenticationType, UserInfo newUser)
        {
            var membUtils = new DnnMembershipUtilities(portalId);

            UserCreateStatus CreateStatus = UserCreateStatus.AddUser;
            var portalSecurity            = new PortalSecurity();

            //Check User Editor
            //bool _IsValid = base.View.RegistrationForm.IsValid;

            if (membUtils.RegistrationFormType == 0)
            {
                //Update UserName
                if (membUtils.UseEmailAsUserName)
                {
                    newUser.Username = newUser.Email;
                    if (String.IsNullOrEmpty(newUser.DisplayName))
                    {
                        newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));
                    }
                }

                //Check Password is valid
                if (!membUtils.RandomPassword)
                {
                    //Check Password is Valid
                    if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(newUser.Membership.Password))
                    {
                        CreateStatus = UserCreateStatus.InvalidPassword;
                    }

                    if (membUtils.RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType))
                    {
                        if (newUser.Membership.Password != newUser.Membership.PasswordConfirm)
                        {
                            CreateStatus = UserCreateStatus.PasswordMismatch;
                        }
                    }
                }
                else
                {
                    //Generate a random password for the user
                    newUser.Membership.Password        = UserController.GeneratePassword();
                    newUser.Membership.PasswordConfirm = newUser.Membership.Password;
                }
            }
            else
            {
                //Set Username to Email
                if (String.IsNullOrEmpty(newUser.Username))
                {
                    newUser.Username = newUser.Email;
                }

                //Set DisplayName
                if (String.IsNullOrEmpty(newUser.DisplayName))
                {
                    newUser.DisplayName = String.IsNullOrEmpty(String.Format("{0} {1}", newUser.FirstName, newUser.LastName))
                                           ? newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal))
                                           : String.Format("{0} {1}", newUser.FirstName, newUser.LastName);
                }

                //Random Password
                if (String.IsNullOrEmpty(newUser.Membership.Password))
                {
                    //Generate a random password for the user
                    newUser.Membership.Password = UserController.GeneratePassword();
                }

                //Password Confirm
                if (!String.IsNullOrEmpty(newUser.Membership.PasswordConfirm))
                {
                    if (newUser.Membership.Password != newUser.Membership.PasswordConfirm)
                    {
                        CreateStatus = UserCreateStatus.PasswordMismatch;
                    }
                }
            }

            //Validate banned password
            var settings = new MembershipPasswordSettings(newUser.PortalID);

            if (settings.EnableBannedList)
            {
                var m = new MembershipPasswordController();
                if (m.FoundBannedPassword(newUser.Membership.Password) || newUser.Username == newUser.Membership.Password)
                {
                    CreateStatus = UserCreateStatus.BannedPasswordUsed;
                }
            }
            //Validate Profanity
            if (UseProfanityFilter)
            {
                if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity))
                {
                    CreateStatus = UserCreateStatus.InvalidUserName;
                }
                if (!String.IsNullOrEmpty(newUser.DisplayName))
                {
                    if (!portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                    {
                        CreateStatus = UserCreateStatus.InvalidDisplayName;
                    }
                }
            }

            //Validate Unique User Name
            UserInfo user = UserController.GetUserByName(portalId, newUser.Username);

            if (user != null)
            {
                if (membUtils.UseEmailAsUserName)
                {
                    CreateStatus = UserCreateStatus.DuplicateEmail;
                }
                else
                {
                    CreateStatus = UserCreateStatus.DuplicateUserName;
                    int    i        = 1;
                    string userName = null;
                    while (user != null)
                    {
                        userName = String.Format("{0}0{1}", newUser.Username, i.ToString(CultureInfo.InvariantCulture));
                        user     = UserController.GetUserByName(portalId, userName);
                        i++;
                    }
                    newUser.Username = userName;
                }
            }

            //Validate Unique Display Name
            if (CreateStatus == UserCreateStatus.AddUser && RequireUniqueDisplayName)
            {
                user = TestableUserController.Instance.GetUserByDisplayname(portalId, newUser.DisplayName);
                if (user != null)
                {
                    CreateStatus = UserCreateStatus.DuplicateDisplayName;
                    int    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = String.Format("{0} 0{1}", newUser.DisplayName, i.ToString(CultureInfo.InvariantCulture));
                        user        = TestableUserController.Instance.GetUserByDisplayname(portalId, displayName);
                        i++;
                    }
                    newUser.DisplayName = displayName;
                }
            }

            //Check Question/Answer
            if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer)
            {
                if (string.IsNullOrEmpty(newUser.Membership.PasswordQuestion))
                {
                    //Invalid Question
                    CreateStatus = UserCreateStatus.InvalidQuestion;
                }
                if (CreateStatus == UserCreateStatus.AddUser)
                {
                    if (string.IsNullOrEmpty(newUser.Membership.PasswordAnswer))
                    {
                        //Invalid Question
                        CreateStatus = UserCreateStatus.InvalidAnswer;
                    }
                }
            }

            return(CreateStatus);
        }
        //NOTE - While making modifications in this method, developer must refer to call tree in Register.ascx.cs.
        //Especially Validate and CreateUser methods. Register class inherits from UserModuleBase, which also contains bunch of logic.
        //This method can easily be modified to pass passowrd, display name, etc.
        //It is recommended to write unit tests.
        public UserBasicDto Register(RegisterationDetails registerationDetails)
        {
            var portalSettings = registerationDetails.PortalSettings;
            var username       = registerationDetails.UserName;
            var email          = registerationDetails.Email;

            Requires.NotNullOrEmpty("email", email);

            var disallowRegistration = !registerationDetails.IgnoreRegistrationMode &&
                                       ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) ||
                                        (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration));

            if (disallowRegistration)
            {
                throw new Exception(Localization.GetString("RegistrationNotAllowed", Library.Constants.SharedResources));
            }

            //initial creation of the new User object
            var newUser = new UserInfo
            {
                PortalID = portalSettings.PortalId,
                Email    = email
            };

            //ensure this user doesn't exist
            if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null)
            {
                throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent",
                                                           Library.Constants.SharedResources));
            }

            //set username as email if not specified
            newUser.Username = string.IsNullOrEmpty(username) ? email : username;

            if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword)
            {
                newUser.Membership.Password = registerationDetails.Password;
            }
            else
            {
                //Generate a random password for the user
                newUser.Membership.Password = UserController.GeneratePassword();
            }

            newUser.Membership.PasswordConfirm = newUser.Membership.Password;

            //set other profile properties
            newUser.Profile.PreferredLocale = new Localization().CurrentUICulture;
            newUser.Profile.InitialiseProfile(portalSettings.PortalId);
            newUser.Profile.PreferredTimeZone = portalSettings.TimeZone;

            //derive display name from supplied firstname, lastname or from email
            if (!string.IsNullOrEmpty(registerationDetails.FirstName) &&
                !string.IsNullOrEmpty(registerationDetails.LastName))
            {
                newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName;
                newUser.FirstName   = registerationDetails.FirstName;
                newUser.LastName    = registerationDetails.LastName;
            }
            else
            {
                newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));
            }

            //read all the user account settings
            var settings = UserController.GetUserSettings(portalSettings.PortalId);

            //Verify Profanity filter
            if (GetBoolSetting(settings, "Registration_UseProfanityFilter"))
            {
                var portalSecurity = new PortalSecurity();
                if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                {
                    throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Email Address Validation
            var emailValidator = GetStringSetting(settings, "Security_EmailValidation");

            if (!string.IsNullOrEmpty(emailValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Email);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Excluded Terms Verification
            var excludeRegex = GetExcludeTermsRegex(settings);

            if (!string.IsNullOrEmpty(excludeRegex))
            {
                var regExp  = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count > 0)
                {
                    throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //User Name Validation
            var userNameValidator = GetStringSetting(settings, "Security_UserNameValidation");

            if (!string.IsNullOrEmpty(userNameValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //ensure unique username
            var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username);

            if (user != null)
            {
                if (GetBoolSetting(settings, "Registration_UseEmailAsUserName"))
                {
                    throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail));
                }

                var    i        = 1;
                string userName = null;
                while (user != null)
                {
                    userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                    user     = UserController.GetUserByName(portalSettings.PortalId, userName);
                    i++;
                }
                newUser.Username = userName;
            }

            //ensure unique display name
            if (GetBoolSetting(settings, "Registration_RequireUniqueDisplayName"))
            {
                user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName);
                if (user != null)
                {
                    var    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                        user        = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName);
                        i++;
                    }
                    newUser.DisplayName = displayName;
                }
            }

            //Update display name format
            var displaynameFormat = GetStringSetting(settings, "Security_DisplayNameFormat");

            if (!string.IsNullOrEmpty(displaynameFormat))
            {
                newUser.UpdateDisplayName(displaynameFormat);
            }

            //membership is approved only for public registration
            newUser.Membership.Approved =
                (registerationDetails.IgnoreRegistrationMode ||
                 portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize;

            //final creation of user
            var createStatus = UserController.CreateUser(ref newUser);

            //clear cache
            if (createStatus == UserCreateStatus.Success)
            {
                DataCache.ClearPortalCache(portalSettings.PortalId, true);
            }

            if (createStatus != UserCreateStatus.Success)
            {
                throw new Exception(UserController.GetUserCreateStatus(createStatus));
            }

//            if (registerationDetails.IgnoreRegistrationMode)
//            {
//                Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
//                return UserBasicDto.FromUserInfo(newUser);
//            }

            //send notification to portal administrator of new user registration
            //check the receive notification setting first, but if register type is Private, we will always send the notification email.
            //because the user need administrators to do the approve action so that he can continue use the website.
            if (!registerationDetails.IgnoreRegistrationMode &&
                (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration))
            {
                Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings);
                SendAdminNotification(newUser, portalSettings);
            }

            //send email to user
            if (registerationDetails.Notify)
            {
                switch (portalSettings.UserRegistration)
                {
                case (int)Globals.PortalRegistrationType.PrivateRegistration:
                    Mail.SendMail(newUser, MessageType.UserRegistrationPrivate, portalSettings);
                    break;

                case (int)Globals.PortalRegistrationType.PublicRegistration:
                    Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
                    break;

                case (int)Globals.PortalRegistrationType.VerifiedRegistration:
                    Mail.SendMail(newUser, MessageType.UserRegistrationVerified, portalSettings);
                    break;
                }
            }

            return(UserBasicDto.FromUserInfo(newUser));
        }