示例#1
0
 /// <inheritdoc/>
 public bool IsFileVersionEnabled(int portalId)
 {
     return(PortalController.GetPortalSettingAsBoolean("FileVersionEnabled", portalId, true));
 }
示例#2
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Searches for and indexes modified users for the given portal.
        /// </summary>
        /// <returns>Count of indexed records</returns>
        /// -----------------------------------------------------------------------------
        public override int IndexSearchDocuments(int portalId,
                                                 ScheduleHistoryItem schedule, DateTime startDateLocal, Action <IEnumerable <SearchDocument> > indexer)
        {
            Requires.NotNull("indexer", indexer);
            const int saveThreshold      = BatchSize;
            var       totalIndexed       = 0;
            var       checkpointModified = false;

            startDateLocal = GetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, startDateLocal);
            var searchDocuments = new Dictionary <string, SearchDocument>();

            var needReindex = PortalController.GetPortalSettingAsBoolean(UserIndexResetFlag, portalId, false);

            if (needReindex)
            {
                startDateLocal = SqlDateTime.MinValue.Value.AddDays(1);
            }

            var controller       = new ListController();
            var textDataType     = controller.GetListEntryInfo("DataType", "Text");
            var richTextDataType = controller.GetListEntryInfo("DataType", "RichText");

            var profileDefinitions = ProfileController.GetPropertyDefinitionsByPortal(portalId, false, false)
                                     .Cast <ProfilePropertyDefinition>()
                                     .Where(d => (textDataType != null && d.DataType == textDataType.EntryID) ||
                                            (richTextDataType != null && d.DataType == richTextDataType.EntryID))
                                     .ToList();

            try
            {
                int startUserId;
                var checkpointData = GetLastCheckpointData(portalId, schedule.ScheduleID);
                if (string.IsNullOrEmpty(checkpointData) || !int.TryParse(checkpointData, out startUserId))
                {
                    startUserId = Null.NullInteger;
                }

                int         rowsAffected;
                IList <int> indexedUsers;
                do
                {
                    rowsAffected = FindModifiedUsers(portalId, startDateLocal,
                                                     searchDocuments, profileDefinitions, out indexedUsers, ref startUserId);

                    if (rowsAffected > 0 && searchDocuments.Count >= saveThreshold)
                    {
                        //remove existing indexes
                        DeleteDocuments(portalId, indexedUsers);
                        var values = searchDocuments.Values;
                        totalIndexed += IndexCollectedDocs(indexer, values);
                        SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString());
                        SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, values.Last().ModifiedTimeUtc.ToLocalTime());
                        searchDocuments.Clear();
                        checkpointModified = true;
                    }
                } while (rowsAffected > 0);

                if (searchDocuments.Count > 0)
                {
                    //remove existing indexes
                    DeleteDocuments(portalId, indexedUsers);
                    var values = searchDocuments.Values;
                    totalIndexed      += IndexCollectedDocs(indexer, values);
                    checkpointModified = true;
                }

                if (needReindex)
                {
                    PortalController.DeletePortalSetting(portalId, UserIndexResetFlag);
                }
            }
            catch (Exception ex)
            {
                checkpointModified = false;
                Exceptions.Exceptions.LogException(ex);
            }

            if (checkpointModified)
            {
                // at last reset start user pointer
                SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString());
                SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now);
            }
            return(totalIndexed);
        }
        private void cmdChangePassword_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;

            if (MembershipProviderConfig.RequiresQuestionAndAnswer && string.IsNullOrEmpty(txtAnswer.Text))
            {
                return;
            }

            //1. Check New Password and Confirm are the same
            if (txtPassword.Text != txtConfirmPassword.Text)
            {
                resetMessages.Visible = true;
                var failed = Localization.GetString("PasswordMismatch");
                LogFailure(failed);
                lblHelp.Text = failed;
                return;
            }

            var newPassword = txtPassword.Text.Trim();

            if (UserController.ValidatePassword(newPassword) == false)
            {
                resetMessages.Visible = true;
                var failed = Localization.GetString("PasswordResetFailed");
                LogFailure(failed);
                lblHelp.Text = failed;
                return;
            }

            //Check New Password is not same as username or banned
            var settings = new MembershipPasswordSettings(User.PortalID);

            if (settings.EnableBannedList)
            {
                var m = new MembershipPasswordController();
                if (m.FoundBannedPassword(newPassword) || txtUsername.Text == newPassword)
                {
                    resetMessages.Visible = true;
                    var failed = Localization.GetString("PasswordResetFailed");
                    LogFailure(failed);
                    lblHelp.Text = failed;
                    return;
                }
            }

            if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
            {
                var testUser = UserController.GetUserByEmail(PortalId, username); // one additonal call to db to see if an account with that email actually exists
                if (testUser != null)
                {
                    username = testUser.Username; //we need the username of the account in order to change the password in the next step
                }
            }
            string errorMessage;
            string answer = String.Empty;

            if (MembershipProviderConfig.RequiresQuestionAndAnswer)
            {
                answer = txtAnswer.Text;
            }

            if (UserController.ChangePasswordByToken(PortalSettings.PortalId, username, newPassword, answer, ResetToken, out errorMessage) == false)
            {
                resetMessages.Visible = true;
                var failed = errorMessage;
                LogFailure(failed);
                lblHelp.Text = failed;
            }
            else
            {
                //check user has a valid profile
                var user        = UserController.GetUserByName(PortalSettings.PortalId, username);
                var validStatus = UserController.ValidateUser(user, PortalSettings.PortalId, false);
                if (validStatus == UserValidStatus.UPDATEPROFILE)
                {
                    LogSuccess();
                    ViewState.Add("PageNo", 3);
                    Response.Redirect(_navigationManager.NavigateURL(PortalSettings.ActiveTab.TabID, "Login"));
                }
                else
                {
                    //Log user in to site
                    LogSuccess();
                    var loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    UserController.UserLogin(PortalSettings.PortalId, username, txtPassword.Text, "", "", "", ref loginStatus, false);
                    RedirectAfterLogin();
                }
            }
        }
示例#4
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            //It validates whether the user will be reset your password.
            var listUser = Membership.GetAllUsers().Cast <MembershipUser>().Where(x => x.Email.ToLower().Trim() == txtUsername.Text.ToLower().Trim() && x.Comment == "ChangePassword").FirstOrDefault();

            if (listUser != null)
            {
                // Gets user information
                _user = UserController.GetUserByEmail(PortalSettings.PortalId, txtUsername.Text.Trim());

                // Validates if the user is not removed from the system
                if (!_user.IsDeleted)
                {
                    //Web config parameters are validated and the password reset token
                    if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled)
                    {
                        UserController.ResetPasswordToken(_user);
                    }

                    //The email is sent to the user and the Comment field is updated in the table asp [ aspnet_Membership ]
                    Mail.SendMail(_user, MessageType.PasswordReminder, PortalSettings);
                    listUser.Comment = string.Empty;
                    Membership.UpdateUser(listUser);
                    Response.Redirect(NexsoHelper.GetCulturedUrlByTabName("RessetSecurityPassword"));
                }
            }
            else
            {
                if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
                {
                    var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    string userName    = new PortalSecurity().InputFilter(txtUsername.Text,
                                                                          PortalSecurity.FilterFlag.NoScripting |
                                                                          PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                          PortalSecurity.FilterFlag.NoMarkup);

                    //DNN-6093
                    //check if we use email address here rather than username
                    if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                    {
                        var testUser = UserController.GetUserByEmail(PortalId, userName); // one additonal call to db to see if an account with that email actually exists
                        if (testUser != null)
                        {
                            userName = testUser.Username; //we need the username of the account in order to authenticate in the next step
                        }
                    }

                    var objUser       = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                    var authenticated = Null.NullBoolean;
                    var message       = Null.NullString;
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        message = "UserNotAuthorized";
                    }
                    else
                    {
                        authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                    }

                    if (loginStatus != UserLoginStatus.LOGIN_FAILURE && PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                    {
                        //make sure internal username matches current e-mail address
                        if (objUser.Username.ToLower() != objUser.Email.ToLower())
                        {
                            UserController.ChangeUsername(objUser.UserID, objUser.Email);
                        }

                        Response.Cookies.Remove("USERNAME_CHANGED");
                    }

                    //Raise UserAuthenticated Event
                    var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                    {
                        Authenticated = authenticated,
                        Message       = message,
                        RememberMe    = chkCookie.Checked
                    };
                    OnUserAuthenticated(eventArgs);
                }
            }
        }
示例#5
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// DataBind binds the data to the controls.
        /// </summary>
        public override void DataBind()
        {
            if (this.Page.IsPostBack == false)
            {
                string confirmString = Localization.GetString("DeleteItem");
                if (this.IsUser)
                {
                    confirmString = Localization.GetString("ConfirmUnRegister", this.LocalResourceFile);
                }

                ClientAPI.AddButtonConfirm(this.cmdDelete, confirmString);
                this.chkRandom.Checked = false;
            }

            this.cmdDelete.Visible  = false;
            this.cmdRemove.Visible  = false;
            this.cmdRestore.Visible = false;
            if (!this.AddUser)
            {
                var deletePermitted = (this.User.UserID != this.PortalSettings.AdministratorId) && !(this.IsUser && this.User.IsSuperUser);
                if (deletePermitted)
                {
                    if (this.User.IsDeleted)
                    {
                        this.cmdRemove.Visible  = true;
                        this.cmdRestore.Visible = true;
                    }
                    else
                    {
                        this.cmdDelete.Visible = true;
                    }
                }
            }

            this.cmdUpdate.Text = Localization.GetString(this.IsUser ? "Register" : "CreateUser", this.LocalResourceFile);
            this.cmdDelete.Text = Localization.GetString(this.IsUser ? "UnRegister" : "Delete", this.LocalResourceFile);
            if (this.AddUser)
            {
                this.pnlAddUser.Visible = true;
                if (this.IsRegister)
                {
                    this.AuthorizeNotify.Visible = false;
                    this.randomRow.Visible       = false;
                    if (this.ShowPassword)
                    {
                        this.questionRow.Visible  = MembershipProviderConfig.RequiresQuestionAndAnswer;
                        this.answerRow.Visible    = MembershipProviderConfig.RequiresQuestionAndAnswer;
                        this.lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", this.LocalResourceFile);
                    }
                }
                else
                {
                    this.lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", this.LocalResourceFile);
                }

                this.txtConfirm.Attributes.Add("value", this.txtConfirm.Text);
                this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
            }

            bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false);

            // only show username row once UseEmailAsUserName is disabled in site settings
            if (disableUsername)
            {
                this.userNameReadOnly.Visible = false;
                this.userName.Visible         = false;
            }
            else
            {
                this.userNameReadOnly.Visible = !this.AddUser;
                this.userName.Visible         = this.AddUser;
            }

            if (this.CanUpdateUsername() && !disableUsername)
            {
                this.renameUserName.Visible = true;

                this.userName.Visible         = false;
                this.userNameReadOnly.Visible = false;

                ArrayList portals = PortalController.GetPortalsByUser(this.User.UserID);
                if (portals.Count > 1)
                {
                    this.numSites.Text          = string.Format(Localization.GetString("UpdateUserName", this.LocalResourceFile), portals.Count.ToString());
                    this.cboSites.Visible       = true;
                    this.cboSites.DataSource    = portals;
                    this.cboSites.DataTextField = "PortalName";
                    this.cboSites.DataBind();

                    this.renameUserPortals.Visible = true;
                }
            }

            if (!string.IsNullOrEmpty(this.PortalSettings.Registration.UserNameValidator))
            {
                this.userName.ValidationExpression = this.PortalSettings.Registration.UserNameValidator;
            }

            if (!string.IsNullOrEmpty(this.PortalSettings.Registration.EmailValidator))
            {
                this.email.ValidationExpression = this.PortalSettings.Registration.EmailValidator;
            }

            if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat))
            {
                if (this.AddUser)
                {
                    this.displayNameReadOnly.Visible = false;
                    this.displayName.Visible         = false;
                }
                else
                {
                    this.displayNameReadOnly.Visible = true;
                    this.displayName.Visible         = false;
                }

                this.firstName.Visible = true;
                this.lastName.Visible  = true;
            }
            else
            {
                this.displayNameReadOnly.Visible = false;
                this.displayName.Visible         = true;
                this.firstName.Visible           = false;
                this.lastName.Visible            = false;
            }

            this.userForm.DataSource = this.User;
            if (!this.Page.IsPostBack)
            {
                this.userForm.DataBind();
                this.renameUserName.Value = this.User.Username;
            }
        }
示例#6
0
        /// <summary>
        /// ShowRequiredFields sets up displaying which fields are required.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void ShowRequiredFields()
        {
            var reqStreet    = PortalController.GetPortalSettingAsBoolean("addressstreet", this.PortalSettings.PortalId, true);
            var reqCity      = PortalController.GetPortalSettingAsBoolean("addresscity", this.PortalSettings.PortalId, true);
            var reqCountry   = PortalController.GetPortalSettingAsBoolean("addresscountry", this.PortalSettings.PortalId, true);
            var reqRegion    = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true);
            var reqPostal    = PortalController.GetPortalSettingAsBoolean("addresspostal", this.PortalSettings.PortalId, true);
            var reqTelephone = PortalController.GetPortalSettingAsBoolean("addresstelephone", this.PortalSettings.PortalId, true);
            var reqCell      = PortalController.GetPortalSettingAsBoolean("addresscell", this.PortalSettings.PortalId, true);
            var reqFax       = PortalController.GetPortalSettingAsBoolean("addressfax", this.PortalSettings.PortalId, true);

            if (TabPermissionController.CanAdminPage())
            {
                if (reqCountry)
                {
                    this.chkCountry.Checked  = true;
                    this.valCountry.Enabled  = true;
                    this.cboCountry.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCountry.Enabled  = false;
                    this.cboCountry.CssClass = string.Empty;
                }

                if (reqRegion)
                {
                    this.chkRegion.Checked  = true;
                    this.txtRegion.CssClass = "dnnFormRequired";
                    this.cboRegion.CssClass = "dnnFormRequired";

                    if (this.cboRegion.Visible)
                    {
                        this.valRegion1.Enabled = true;
                        this.valRegion2.Enabled = false;
                    }
                    else
                    {
                        this.valRegion1.Enabled = false;
                        this.valRegion2.Enabled = true;
                    }
                }
                else
                {
                    this.valRegion1.Enabled = false;
                    this.valRegion2.Enabled = false;
                    this.txtRegion.CssClass = string.Empty;
                    this.cboRegion.CssClass = string.Empty;
                }

                if (reqCity)
                {
                    this.chkCity.Checked  = true;
                    this.valCity.Enabled  = true;
                    this.txtCity.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCity.Enabled  = false;
                    this.txtCity.CssClass = string.Empty;
                }

                if (reqStreet)
                {
                    this.chkStreet.Checked  = true;
                    this.valStreet.Enabled  = true;
                    this.txtStreet.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valStreet.Enabled  = false;
                    this.txtStreet.CssClass = string.Empty;
                }

                if (reqPostal)
                {
                    this.chkPostal.Checked  = true;
                    this.valPostal.Enabled  = true;
                    this.txtPostal.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valPostal.Enabled  = false;
                    this.txtPostal.CssClass = string.Empty;
                }

                if (reqTelephone)
                {
                    this.chkTelephone.Checked  = true;
                    this.valTelephone.Enabled  = true;
                    this.txtTelephone.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valTelephone.Enabled  = false;
                    this.txtTelephone.CssClass = string.Empty;
                }

                if (reqCell)
                {
                    this.chkCell.Checked  = true;
                    this.valCell.Enabled  = true;
                    this.txtCell.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCell.Enabled  = false;
                    this.txtCell.CssClass = string.Empty;
                }

                if (reqFax)
                {
                    this.chkFax.Checked  = true;
                    this.valFax.Enabled  = true;
                    this.txtFax.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valFax.Enabled  = false;
                    this.txtFax.CssClass = string.Empty;
                }
            }
        }
        private void BindData()
        {
            if (this.User != null)
            {
                // If trying to add a SuperUser - check that user is a SuperUser
                if (this.VerifyUserPermissions() == false)
                {
                    return;
                }

                if (!this.Page.IsPostBack)
                {
                    if (this.Request.QueryString["pageno"] != null)
                    {
                        this.PageNo = int.Parse(this.Request.QueryString["pageno"]);
                    }
                    else
                    {
                        this.PageNo = 0;
                    }
                }

                this.userForm.DataSource = this.User;

                // hide username field in UseEmailAsUserName mode
                bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false);
                if (disableUsername)
                {
                    this.userForm.Items[0].Visible = false;
                }

                if (!this.Page.IsPostBack)
                {
                    this.userForm.DataBind();
                }

                this.ctlPassword.User = this.User;
                this.ctlPassword.DataBind();

                if (!this.DisplayServices)
                {
                    this.servicesTab.Visible = false;
                }
                else
                {
                    this.ctlServices.User = this.User;
                    this.ctlServices.DataBind();
                }

                this.BindUser();
                this.ctlProfile.User = this.User;
                this.ctlProfile.DataBind();

                this.dnnServicesDetails.Visible = this.DisplayServices;

                var urlSettings   = new DotNetNuke.Entities.Urls.FriendlyUrlSettings(this.PortalSettings.PortalId);
                var showVanityUrl = (Config.GetFriendlyUrlProvider() == "advanced") && !this.User.IsSuperUser;
                if (showVanityUrl)
                {
                    this.VanityUrlRow.Visible = true;
                    if (string.IsNullOrEmpty(this.User.VanityUrl))
                    {
                        // Clean Display Name
                        bool modified;
                        var  options   = UrlRewriterUtils.GetOptionsFromSettings(urlSettings);
                        var  cleanUrl  = FriendlyUrlController.CleanNameForUrl(this.User.DisplayName, options, out modified);
                        var  uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, this.PortalSettings, out modified).ToLowerInvariant();

                        this.VanityUrlAlias.Text   = string.Format("{0}/{1}/", this.PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix);
                        this.VanityUrlTextBox.Text = uniqueUrl;
                        this.ShowVanityUrl         = true;
                    }
                    else
                    {
                        this.VanityUrl.Text = string.Format("{0}/{1}/{2}", this.PortalSettings.PortalAlias.HTTPAlias, urlSettings.VanityUrlPrefix, this.User.VanityUrl);
                        this.ShowVanityUrl  = false;
                    }
                }
            }
            else
            {
                this.AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true);
                this.DisableForm();
            }
        }
        /// <summary>
        /// Initialiser for FriendlyUrlSettings provider object.  Initialises values by reading in from the web.config file
        /// </summary>
        public FriendlyUrlSettings(int portalId)
        {
            PortalId = portalId;

            PortalValues = new List <string>();

            IncludePageName    = GetBooleanSetting("includePageName", true);
            RegexMatch         = GetStringSetting(ValidFriendlyUrlRegexSetting, @"[^\w\d _-]");
            RedirectUnfriendly = GetBooleanSetting(RedirectUnfriendlySetting, true);
            UrlFormat          = GetStringSetting(UrlFormatSetting, "advanced");

            //541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code
            DoNotRedirectRegex       = GetStringSetting(DoNotRedirectUrlRegexSetting, @"(\.axd)|/Rss\.aspx|/SiteMap\.aspx|\.ashx|/LinkClick\.aspx|/Providers/|/DesktopModules/|ctl=MobilePreview|/ctl/MobilePreview");
            DoNotRedirectSecureRegex = GetStringSetting(DoNotRedirectHttpsUrlRegexSetting, String.Empty);

            DoNotRewriteRegex = GetStringSetting(DoNotRewriteRegExSetting, @"/DesktopModules/|/Providers/|/LinkClick\.aspx|/profilepic\.ashx");

            RedirectDefaultPage = GetBooleanSetting("redirectDefaultPage", false);
            PageExtension       = GetStringSetting(PageExtensionSetting, ".aspx");
            _pageExtensionUsage = GetStringSetting(PageExtensionUsageSetting, PageExtensionUsageType.Never.ToString());

            IgnoreRegex      = GetStringSetting(IgnoreRegexSetting, @"(?<!linkclick\.aspx.+)(?:(?<!\?.+)(\.pdf$|\.gif$|\.png($|\?)|\.css($|\?)|\.js($|\?)|\.jpg$|\.axd($|\?)|\.swf$|\.flv$|\.ico$|\.xml($|\?)|\.txt$))");
            UseSiteUrlsRegex = GetStringSetting(SiteUrlsOnlyRegexSetting, @"/rss\.aspx|Telerik.RadUploadProgressHandler\.ashx|BannerClickThrough\.aspx|(?:/[^/]+)*/Tabid/\d+/.*default\.aspx");

            ForceLowerCase      = GetBooleanSetting(ForceLowerCaseSetting, false);
            ForceLowerCaseRegex = GetStringSetting(PreventLowerCaseUrlRegexSetting, String.Empty);

            RedirectWrongCase = GetBooleanSetting(RedirectMixedCaseSetting, false);
            SSLClientRedirect = GetBooleanSetting("sslClientRedirect", true);
            LogCacheMessages  = GetBooleanSetting(LogCacheMessagesSetting, false);

            //791 : use threadlocking option
            ReplaceSpaceWith = GetStringSetting(ReplaceSpaceWithSetting, "-");
            var replaceCharwithChar = GetStringSetting(ReplaceCharWithCharSetting, String.Empty);

            ReplaceCharacterDictionary = CollectionExtensions.CreateDictionaryFromString(replaceCharwithChar == "[]" ? string.Empty : replaceCharwithChar, ';', ',');

            SpaceEncodingValue = GetStringSetting(SpaceEncodingValueSetting, SpaceEncodingHex);


            //893 : new extensionless Urls check for validating urls which have no extension but aren't 404
            ValidExtensionlessUrlsRegex = GetStringSetting(UrlsWithNoExtensionRegexSetting, @"\.asmx/|\.ashx/|\.svc/|\.aspx/|\.axd/");

            //922 : new options for allowing user-configured replacement of characters
            ReplaceChars       = GetStringSetting(ReplaceCharsSetting, @" &$+,/?~#<>()¿¡«»!""");
            IllegalChars       = GetStringSetting("illegalChars", @"<>/\?:&=+|%#");
            ReplaceDoubleChars = GetBooleanSetting("replaceDoubleChars", true);

            //793 : checkforDupUrls not being read
            CheckForDuplicateUrls = GetBooleanSetting(CheckForDuplicatedUrlsSetting, true);

            /* 454 New 404 error handling */
            Regex404 = GetStringSetting("regex404", String.Empty);
            TabId404 = PortalController.GetPortalSettingAsInteger(ErrorPage404Setting, PortalId, -1);
            Url404   = GetStringSetting("url404", String.Empty);

            //get the 500 error values, if not supplied, use the 404 values
            TabId500 = PortalController.GetPortalSettingAsInteger(ErrorPage500Setting, PortalId, -1);
            if (TabId500 == -1)
            {
                TabId500 = TabId404;
            }
            Url500 = GetStringSetting("url500", null) ?? Url404;

            _deletedTabHandling = PortalController.GetPortalSetting(DeletedTabHandlingTypeSetting, PortalId, DeletedTabHandlingType.Do404Error.ToString());

            UseBaseFriendlyUrls = GetStringSetting("useBaseFriendlyUrls", "/SearchResults;/ModuleDefinitions");
            if (UseBaseFriendlyUrls.EndsWith(";") == false)
            {
                UseBaseFriendlyUrls += ";";
            }

            //655 : new noFriendlyUrlRegex value to ignore generation of certain urls
            NoFriendlyUrlRegex = GetStringSetting(DoNotUseFriendlyUrlRegexSetting, @"/Rss\.aspx");

            //703 default debug code to false
            AllowDebugCode = GetBooleanSetting(AllowDebugCodeSetting, false);
            //allow reporting value for checking for updates and reporting usage data
            AllowReporting = GetBooleanSetting("allowReporting", true);

            //737 : integrate mobile alias
            UseMobileAlias = GetStringSetting("useMobileAlias", null);

            VanityUrlPrefix = GetStringSetting(VanityUrlPrefixSetting, "users");

            // allow for a list of internal aliases
            _internalAliases = GetStringSetting("internalAliases", null);
            ParseInternalAliases();

            //661 : do not include in path
            //742 : was not reading and saving value when 'doNotIncludeInPathRegex' used
            DoNotIncludeInPathRegex = GetStringSetting(KeepInQueryStringRegexSetting, @"/nomo/\d+|/runningDefault/[^/]+|/popup/(?:true|false)|/(?:page|category|sort|tags)/[^/]+");

            string processRequests = GetStringSetting("processRequests", null);

            if (processRequests != null)
            {
                processRequests    = processRequests.ToLower();
                ProcessRequestList = !string.IsNullOrEmpty(processRequests)
                        ? new List <string>(processRequests.Split(';'))
                        : null;
            }

            //urls to be modified in the output html stream
            AutoAsciiConvert = GetBooleanSetting(AutoAsciiConvertSetting, false);

            //810 : allow forcing of default language in rewrites
            ForcePortalDefaultLanguage = GetBooleanSetting(UsePortalDefaultLanguageSetting, true);
            FriendlyAdminHostUrls      = GetBooleanSetting(FriendlyAdminHostUrlsSetting, true);
            //894 : new switch to disable custom providers if necessary
            EnableCustomProviders = GetBooleanSetting(EnableCustomProvidersSetting, true);

            CacheTime = new TimeSpan(0, GetIntegerSetting("cacheTime", 1440), 0);

            RedirectOldProfileUrl = PortalController.GetPortalSettingAsBoolean(RedirectOldProfileUrlSetting, PortalId, true);
        }
示例#9
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns the collection of SearchDocuments populated with Tab MetaData for the given portal.
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        /// <history>
        ///     [vnguyen]   04/16/2013  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public override IEnumerable <SearchDocument> GetSearchDocuments(int portalId, DateTime startDate)
        {
            var searchDocuments = new Dictionary <string, SearchDocument>();

            var needReindex = PortalController.GetPortalSettingAsBoolean(UserIndexResetFlag, portalId, false);

            if (needReindex)
            {
                startDate = SqlDateTime.MinValue.Value;
            }

            try
            {
                var startUserId = Null.NullInteger;
                while (true)
                {
                    var reader       = DataProvider.Instance().GetAvailableUsersForIndex(portalId, startDate, startUserId, BatchSize);
                    int rowsAffected = 0;
                    var indexedUsers = new List <int>();

                    while (reader.Read())
                    {
                        var userId         = Convert.ToInt32(reader["UserId"]);
                        var displayName    = reader["DisplayName"].ToString();
                        var firstName      = reader["FirstName"].ToString();
                        var propertyName   = reader["PropertyName"].ToString();
                        var propertyValue  = reader["PropertyValue"].ToString();
                        var visibilityMode = ((UserVisibilityMode)Convert.ToInt32(reader["Visibility"]));
                        var modifiedTime   = Convert.ToDateTime(reader["ModifiedTime"]).ToUniversalTime();
                        //log the userid so that it can get the correct user collection next time.
                        if (userId > startUserId)
                        {
                            startUserId = userId;
                        }

                        var uniqueKey = string.Format("{0}_{1}", userId, visibilityMode).ToLowerInvariant();
                        if (visibilityMode == UserVisibilityMode.FriendsAndGroups)
                        {
                            uniqueKey = string.Format("{0}_{1}", uniqueKey, reader["ExtendedVisibility"]);
                        }

                        if (searchDocuments.ContainsKey(uniqueKey))
                        {
                            var document = searchDocuments[uniqueKey];
                            document.Body += string.Format(" {0}", propertyValue);

                            if (modifiedTime > document.ModifiedTimeUtc)
                            {
                                document.ModifiedTimeUtc = modifiedTime;
                            }
                        }
                        else
                        {
                            //Need remove use exists index for all visibilities.
                            if (!indexedUsers.Contains(userId))
                            {
                                indexedUsers.Add(userId);
                            }

                            if (!string.IsNullOrEmpty(propertyValue))
                            {
                                var searchDoc = new SearchDocument
                                {
                                    SearchTypeId    = UserSearchTypeId,
                                    UniqueKey       = uniqueKey,
                                    PortalId        = portalId,
                                    ModifiedTimeUtc = modifiedTime,
                                    Body            = propertyValue,
                                    Description     = firstName,
                                    Title           = displayName
                                };

                                searchDocuments.Add(uniqueKey, searchDoc);
                            }
                            else if (!searchDocuments.ContainsKey(string.Format("{0}_{1}", userId, UserVisibilityMode.AllUsers).ToLowerInvariant()))
                            {
                                if (!indexedUsers.Contains(userId))
                                {
                                    indexedUsers.Add(userId);
                                }
                                //if the user doesn't exist in search collection, we need add it with ALLUsers mode,
                                //so that can make sure DisplayName will be indexed
                                var searchDoc = new SearchDocument
                                {
                                    SearchTypeId    = UserSearchTypeId,
                                    UniqueKey       = string.Format("{0}_{1}", userId, UserVisibilityMode.AllUsers).ToLowerInvariant(),
                                    PortalId        = portalId,
                                    ModifiedTimeUtc = modifiedTime,
                                    Body            = string.Empty,
                                    Description     = firstName,
                                    Title           = displayName
                                };

                                searchDocuments.Add(searchDoc.UniqueKey, searchDoc);
                            }
                        }
                        rowsAffected++;
                    }

                    //close the data reader
                    reader.Close();

                    //remov exists indexes
                    DeleteDocuments(portalId, indexedUsers);

                    if (rowsAffected == 0)
                    {
                        break;
                    }
                }

                if (needReindex)
                {
                    PortalController.DeletePortalSetting(portalId, UserIndexResetFlag);
                }
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
            }

            return(searchDocuments.Values);
        }
        public HttpResponseMessage GetRegistrationSettings()
        {
            try
            {
                var userRegistrationOptions = new List <KeyValuePair <string, int> >();
                userRegistrationOptions.Add(new KeyValuePair <string, int>(Localization.GetString("None", Components.Constants.LocalResourcesFile), 0));
                userRegistrationOptions.Add(new KeyValuePair <string, int>(Localization.GetString("Private", Components.Constants.LocalResourcesFile), 1));
                userRegistrationOptions.Add(new KeyValuePair <string, int>(Localization.GetString("Public", Components.Constants.LocalResourcesFile), 2));
                userRegistrationOptions.Add(new KeyValuePair <string, int>(Localization.GetString("Verified", Components.Constants.LocalResourcesFile), 3));

                var registrationFormTypeOptions = new List <KeyValuePair <string, int> >();
                registrationFormTypeOptions.Add(new KeyValuePair <string, int>(Localization.GetString("Standard", Components.Constants.LocalResourcesFile), 0));
                registrationFormTypeOptions.Add(new KeyValuePair <string, int>(Localization.GetString("Custom", Components.Constants.LocalResourcesFile), 1));

                var activeLanguage = LocaleController.Instance.GetDefaultLocale(PortalId).Code;
                var portal         = PortalController.Instance.GetPortal(PortalId, activeLanguage);

                var response = new
                {
                    Success = true,
                    Results = new
                    {
                        Settings = new
                        {
                            portal.UserRegistration,
                            EnableRegisterNotification = PortalController.GetPortalSettingAsBoolean("EnableRegisterNotification", PortalId, true),
                            UseAuthenticationProviders = PortalController.GetPortalSettingAsBoolean("Registration_UseAuthProviders", PortalId, false),
                            ExcludedTerms      = PortalController.GetPortalSetting("Registration_ExcludeTerms", PortalId, string.Empty),
                            UseProfanityFilter = PortalController.GetPortalSettingAsBoolean("Registration_UseProfanityFilter", PortalId, false),
                            PortalSettings.Registration.RegistrationFormType,
                            PortalSettings.Registration.RegistrationFields,
                            UseEmailAsUsername               = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false),
                            RequireUniqueDisplayName         = PortalController.GetPortalSettingAsBoolean("Registration_RequireUniqueDisplayName", PortalId, false),
                            DisplayNameFormat                = PortalController.GetPortalSetting("Security_DisplayNameFormat", PortalId, string.Empty),
                            UserNameValidation               = PortalController.GetPortalSetting("Security_UserNameValidation", PortalId, Globals.glbUserNameRegEx),
                            EmailAddressValidation           = PortalController.GetPortalSetting("Security_EmailValidation", PortalId, Globals.glbEmailRegEx),
                            UseRandomPassword                = PortalController.GetPortalSettingAsBoolean("Registration_RandomPassword", PortalId, false),
                            RequirePasswordConfirmation      = PortalController.GetPortalSettingAsBoolean("Registration_RequireConfirmPassword", PortalId, true),
                            RequireValidProfile              = PortalController.GetPortalSettingAsBoolean("Security_RequireValidProfile", PortalId, false),
                            UseCaptchaRegister               = PortalController.GetPortalSettingAsBoolean("Security_CaptchaRegister", PortalId, false),
                            RedirectAfterRegistrationTabId   = ValidateTabId(PortalSettings.Registration.RedirectAfterRegistration),
                            RedirectAfterRegistrationTabName = GetTabName(PortalSettings.Registration.RedirectAfterRegistration),
                            RedirectAfterRegistrationTabPath = GetTabPath(PortalSettings.Registration.RedirectAfterRegistration),
                            RequiresUniqueEmail              = MembershipProviderConfig.RequiresUniqueEmail.ToString(CultureInfo.InvariantCulture),
                            PasswordFormat               = MembershipProviderConfig.PasswordFormat.ToString(),
                            PasswordRetrievalEnabled     = MembershipProviderConfig.PasswordRetrievalEnabled.ToString(CultureInfo.InvariantCulture),
                            PasswordResetEnabled         = MembershipProviderConfig.PasswordResetEnabled.ToString(CultureInfo.InvariantCulture),
                            MinPasswordLength            = MembershipProviderConfig.MinPasswordLength.ToString(CultureInfo.InvariantCulture),
                            MinNonAlphanumericCharacters = MembershipProviderConfig.MinNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture),
                            RequiresQuestionAndAnswer    = MembershipProviderConfig.RequiresQuestionAndAnswer.ToString(CultureInfo.InvariantCulture),
                            MembershipProviderConfig.PasswordStrengthRegularExpression,
                            MaxInvalidPasswordAttempts = MembershipProviderConfig.MaxInvalidPasswordAttempts.ToString(CultureInfo.InvariantCulture),
                            PasswordAttemptWindow      = MembershipProviderConfig.PasswordAttemptWindow.ToString(CultureInfo.InvariantCulture)
                        },
                        UserRegistrationOptions     = userRegistrationOptions,
                        RegistrationFormTypeOptions = registrationFormTypeOptions
                    }
                };

                return(Request.CreateResponse(HttpStatusCode.OK, response));
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
示例#11
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// DataBind binds the data to the controls
        /// </summary>
        /// <history>
        ///     [cnurse]	03/01/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public override void DataBind()
        {
            if (Page.IsPostBack == false)
            {
                string confirmString = Localization.GetString("DeleteItem");
                if (IsUser)
                {
                    confirmString = Localization.GetString("ConfirmUnRegister", LocalResourceFile);
                }
                ClientAPI.AddButtonConfirm(cmdDelete, confirmString);
                chkRandom.Checked = false;
            }

            cmdDelete.Visible  = false;
            cmdRemove.Visible  = false;
            cmdRestore.Visible = false;
            if (!AddUser)
            {
                var deletePermitted = (User.UserID != PortalSettings.AdministratorId) && !(IsUser && User.IsSuperUser);
                if ((deletePermitted))
                {
                    if ((User.IsDeleted))
                    {
                        cmdRemove.Visible  = true;
                        cmdRestore.Visible = true;
                    }
                    else
                    {
                        cmdDelete.Visible = true;
                    }
                }
            }

            cmdUpdate.Text = Localization.GetString(IsUser ? "Register" : "CreateUser", LocalResourceFile);
            cmdDelete.Text = Localization.GetString(IsUser ? "UnRegister" : "Delete", LocalResourceFile);
            if (AddUser)
            {
                pnlAddUser.Visible = true;
                if ((IsRegister == true) && (ModulePermissionController.CanAdminModule(this.ModuleConfiguration) == false))
                {
                    AuthorizeNotify.Visible = false;
                    randomRow.Visible       = false;
                    if (ShowPassword)
                    {
                        questionRow.Visible  = MembershipProviderConfig.RequiresQuestionAndAnswer;
                        answerRow.Visible    = MembershipProviderConfig.RequiresQuestionAndAnswer;
                        lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", LocalResourceFile);
                    }
                }
                else
                {
                    lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", LocalResourceFile);
                }
                txtConfirm.Attributes.Add("value", txtConfirm.Text);
                txtPassword.Attributes.Add("value", txtPassword.Text);
            }


            bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false);

            //only show username row once UseEmailAsUserName is disabled in site settings
            if (disableUsername)
            {
                userNameReadOnly.Visible = false;
                userName.Visible         = false;
            }
            else
            {
                userNameReadOnly.Visible = !AddUser;
                userName.Visible         = AddUser;
            }

            if (CanUpdateUsername() && !disableUsername)
            {
                renameUserName.Visible = true;

                userName.Visible         = false;
                userNameReadOnly.Visible = false;

                ArrayList portals = PortalController.GetPortalsByUser(User.UserID);
                if (portals.Count > 1)
                {
                    numSites.Text          = String.Format(Localization.GetString("UpdateUserName", LocalResourceFile), portals.Count.ToString());
                    cboSites.Visible       = true;
                    cboSites.DataSource    = portals;
                    cboSites.DataTextField = "PortalName";
                    cboSites.DataBind();

                    renameUserPortals.Visible = true;
                }
            }

            if (!string.IsNullOrEmpty(PortalSettings.Registration.UserNameValidator))
            {
                userName.ValidationExpression = PortalSettings.Registration.UserNameValidator;
            }

            if (!string.IsNullOrEmpty(PortalSettings.Registration.EmailValidator))
            {
                email.ValidationExpression = PortalSettings.Registration.EmailValidator;
            }

            if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat))
            {
                if (AddUser)
                {
                    displayNameReadOnly.Visible = false;
                    displayName.Visible         = false;
                }
                else
                {
                    displayNameReadOnly.Visible = true;
                    displayName.Visible         = false;
                }
                firstName.Visible = true;
                lastName.Visible  = true;
            }
            else
            {
                displayNameReadOnly.Visible = false;
                displayName.Visible         = true;
                firstName.Visible           = false;
                lastName.Visible            = false;
            }

            userForm.DataSource = User;
            if (!Page.IsPostBack)
            {
                userForm.DataBind();
                renameUserName.Value = User.Username;
            }
        }
 /// <summary>
 /// Determines whether the authentication is enabled for the specified portal.
 /// </summary>
 /// <param name="authentication">The authentication.</param>
 /// <param name="portalId">The portal identifier.</param>
 /// <returns><c>true</c> if OAuth Provider and it is enabled for the portal, Otherwise <c>false</c>.</returns>
 public static bool IsEnabledForPortal(AuthenticationInfo authentication, int portalId)
 {
     return(!string.IsNullOrEmpty(PortalController.GetPortalSetting(authentication.AuthenticationType + "_Enabled", portalId, ""))
         ? PortalController.GetPortalSettingAsBoolean(authentication.AuthenticationType + "_Enabled", portalId, false)
         : HostController.Instance.GetBoolean(authentication.AuthenticationType + "_Enabled", false));
 }
示例#13
0
        /// <summary>
        /// cmdSendPassword_Click runs when the Password Reminder button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        protected void OnSendPasswordClick(Object sender, EventArgs e)
        {
            //pretty much alwasy display the same message to avoid hinting on the existance of a user name
            var message           = Localization.GetString("PasswordSent", LocalResourceFile);
            var moduleMessageType = ModuleMessage.ModuleMessageType.GreenSuccess;
            var canSend           = true;

            if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha))
            {
                if (String.IsNullOrEmpty(txtUsername.Text.Trim()))
                {
                    //No UserName provided
                    if (ShowEmailField)
                    {
                        if (String.IsNullOrEmpty(txtEmail.Text.Trim()))
                        {
                            //No email address either (cannot retrieve password)
                            canSend           = false;
                            message           = Localization.GetString("EnterUsernameEmail", LocalResourceFile);
                            moduleMessageType = ModuleMessage.ModuleMessageType.RedError;
                        }
                    }
                    else
                    {
                        //Cannot retrieve password
                        canSend           = false;
                        message           = Localization.GetString("EnterUsername", LocalResourceFile);
                        moduleMessageType = ModuleMessage.ModuleMessageType.RedError;
                    }
                }

                if (string.IsNullOrEmpty(Host.SMTPServer))
                {
                    //SMTP Server is not configured
                    canSend           = false;
                    message           = Localization.GetString("OptionUnavailable", LocalResourceFile);
                    moduleMessageType = ModuleMessage.ModuleMessageType.YellowWarning;

                    var logMessage = Localization.GetString("SMTPNotConfigured", LocalResourceFile);

                    LogResult(logMessage);
                }

                if (canSend)
                {
                    GetUser();
                    if (_user != null)
                    {
                        if (_user.IsDeleted)
                        {
                            canSend = false;
                        }
                        else
                        {
                            if (_user.Membership.Approved == false)
                            {
                                Mail.SendMail(_user, MessageType.PasswordReminderUserIsNotApproved, PortalSettings);
                                canSend = false;
                            }
                            if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled)
                            {
                                UserController.ResetPasswordToken(_user);
                            }
                            if (canSend)
                            {
                                if (Mail.SendMail(_user, MessageType.PasswordReminder, PortalSettings) != string.Empty)
                                {
                                    canSend = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (_userCount > 1)
                        {
                            message = Localization.GetString("MultipleUsers", LocalResourceFile);
                        }

                        canSend = false;
                    }

                    if (canSend)
                    {
                        LogSuccess();
                        lnkCancel.Attributes["resourcekey"] = "cmdClose";
                    }
                    else
                    {
                        LogFailure(message);
                    }

                    //always hide panel so as to not reveal if username exists.
                    pnlRecover.Visible = false;
                    UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType);
                    liSend.Visible   = false;
                    liCancel.Visible = true;

                    // don't hide panel when e-mail only in use and error occured. We must provide negative feedback to the user, in case he doesn't rember what e-mail address he has used
                    if (!canSend && _user == null && MembershipProviderConfig.RequiresUniqueEmail && PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                    {
                        message            = Localization.GetString("EmailNotFound", LocalResourceFile);
                        pnlRecover.Visible = true;
                        UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType);
                        liSend.Visible   = true;
                        liCancel.Visible = true;
                    }
                }
                else
                {
                    UI.Skins.Skin.AddModuleMessage(this, message, moduleMessageType);
                }
            }
        }
        public dynamic Index(Entities.ResetPassword PasswordReset)
        {
            dynamic actionResult = new ExpandoObject();

            try
            {
                PasswordReset.ResetToken = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.Split('/')[HttpContext.Current.Request.UrlReferrer.AbsoluteUri.Split('/').Length - 1];
                UserInfo UserInfo = UserController.GetUserByPasswordResetToken(PortalSettings.Current.PortalId, PasswordReset.ResetToken);
                _ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
                string username = PasswordReset.Username;
                if (PasswordReset.Password != PasswordReset.ConfirmPassword)
                {
                    string failed = Localization.GetString("PasswordMismatch");
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }
                string newPassword = PasswordReset.Password.Trim();
                if (UserController.ValidatePassword(newPassword) == false)
                {
                    string failed = Localization.GetString("PasswordResetFailed");
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }

                MembershipPasswordSettings settings = new MembershipPasswordSettings(PortalSettings.Current.PortalId);
                if (settings.EnableBannedList)
                {
                    MembershipPasswordController m = new MembershipPasswordController();
                    if (m.FoundBannedPassword(newPassword) || username == newPassword)
                    {
                        string failed = Localization.GetString("PasswordResetFailed");
                        LogFailure(failed, UserInfo);
                        actionResult.IsSuccess = false;
                        actionResult.Message   = failed;
                        return(actionResult);
                    }
                }
                if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalSettings.Current.PortalId, false))
                {
                    UserInfo testUser = UserController.GetUserByEmail(PortalSettings.Current.PortalId, username); // one additonal call to db to see if an account with that email actually exists
                    if (testUser != null)
                    {
                        username = testUser.Username; //we need the username of the account in order to change the password in the next step
                    }
                }
                if (UserController.ChangePasswordByToken(PortalSettings.PortalId, username, newPassword, null, PasswordReset.ResetToken, out string errorMessage) == false)
                {
                    string failed = errorMessage;
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }
                else
                {
                    //check user has a valid profile
                    UserInfo        user        = UserController.GetUserByName(PortalSettings.PortalId, username);
                    UserValidStatus validStatus = UserController.ValidateUser(user, PortalSettings.PortalId, false);
                    if (validStatus == UserValidStatus.UPDATEPROFILE)
                    {
                        LogSuccess(UserInfo);
                    }
                    else
                    {
                        //Log user in to site
                        LogSuccess(UserInfo);
                        UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                        UserController.UserLogin(PortalSettings.PortalId, username, PasswordReset.Password, "", "", "", ref loginStatus, false);
                        actionResult.Message = Localization.GetString("ChangeSuccessful", LocalResourceFile);
                    }
                }
                actionResult.IsSuccess   = true;
                actionResult.IsRedirect  = true;
                actionResult.RedirectURL = Managers.ResetPasswordManager.RedirectAfterLogin();
            }
            catch (Exception ex)
            {
                actionResult.IsSuccess = false;
                actionResult.Message   = ex.Message;
            }
            return(actionResult);
        }
示例#15
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdLogin.Click += OnLoginClick;

            cmdCancel.Click += OnCancelClick;

            ClientAPI.RegisterKeyCapture(Parent, cmdLogin, 13);

            if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration)
            {
                liRegister.Visible = false;
            }
            lblLogin.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_LOGIN_INSTRUCTIONS");

            var    returnUrl = Globals.NavigateURL();
            string url;

            if (PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration)
            {
                if (!string.IsNullOrEmpty(UrlUtils.ValidReturnUrl(Request.QueryString["returnurl"])))
                {
                    returnUrl = Request.QueryString["returnurl"];
                }
                returnUrl = HttpUtility.UrlEncode(returnUrl);

                url = Globals.RegisterURL(returnUrl, Null.NullString);
                registerLink.NavigateUrl = url;
                if (PortalSettings.EnablePopUps && PortalSettings.RegisterTabId == Null.NullInteger &&
                    !HasSocialAuthenticationEnabled())
                {
                    registerLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 600, 950));
                }
            }
            else
            {
                registerLink.Visible = false;
            }

            //see if the portal supports persistant cookies
            chkCookie.Visible = Host.RememberCheckbox;

            url = Globals.NavigateURL("SendPassword", "returnurl=" + returnUrl);
            passwordLink.NavigateUrl = url;
            if (PortalSettings.EnablePopUps)
            {
                passwordLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 300, 650));
            }


            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["verificationcode"]) && PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration)
                {
                    if (Request.IsAuthenticated)
                    {
                        Controls.Clear();
                    }

                    var verificationCode = Request.QueryString["verificationcode"];


                    try
                    {
                        UserController.VerifyUser(verificationCode.Replace(".", "+").Replace("-", "/").Replace("_", "="));

                        var redirectTabId = Convert.ToInt32(GetSetting(PortalId, "Redirect_AfterRegistration"));

                        if (Request.IsAuthenticated)
                        {
                            Response.Redirect(Globals.NavigateURL(redirectTabId > 0 ? redirectTabId : PortalSettings.HomeTabId, string.Empty, "VerificationSuccess=true"), true);
                        }
                        else
                        {
                            if (redirectTabId > 0)
                            {
                                var redirectUrl = Globals.NavigateURL(redirectTabId, string.Empty, "VerificationSuccess=true");
                                redirectUrl = redirectUrl.Replace(Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias), string.Empty);
                                Response.Cookies.Add(new HttpCookie("returnurl", redirectUrl));
                            }

                            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("VerificationSuccess", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                        }
                    }
                    catch (UserAlreadyVerifiedException)
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserAlreadyVerified", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
                    }
                    catch (InvalidVerificationCodeException)
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    catch (UserDoesNotExistException)
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDoesNotExist", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                    catch (Exception)
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    }
                }
            }

            if (!Request.IsAuthenticated)
            {
                if (!Page.IsPostBack)
                {
                    try
                    {
                        if (Request.QueryString["username"] != null)
                        {
                            txtUsername.Text = Request.QueryString["username"];
                        }
                    }
                    catch (Exception ex)
                    {
                        //control not there
                        Logger.Error(ex);
                    }
                }
                try
                {
                    Globals.SetFormFocus(string.IsNullOrEmpty(txtUsername.Text) ? txtUsername : txtPassword);
                }
                catch (Exception ex)
                {
                    //Not sure why this Try/Catch may be necessary, logic was there in old setFormFocus location stating the following
                    //control not there or error setting focus
                    Logger.Error(ex);
                }
            }

            var  registrationType = PortalController.GetPortalSettingAsInteger("Registration_RegistrationFormType", PortalId, 0);
            bool useEmailAsUserName;

            if (registrationType == 0)
            {
                useEmailAsUserName = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false);
            }
            else
            {
                var registrationFields = PortalController.GetPortalSetting("Registration_RegistrationFields", PortalId, String.Empty);
                useEmailAsUserName = !registrationFields.Contains("Username");
            }

            plUsername.Text     = LocalizeString(useEmailAsUserName ? "Email" : "Username");
            divCaptcha1.Visible = UseCaptcha;
            divCaptcha2.Visible = UseCaptcha;
        }
示例#16
0
        private void cmdChangePassword_Click(object sender, EventArgs e)
        {
            //1. Check New Password and Confirm are the same
            if (txtPassword.Text != txtConfirmPassword.Text)
            {
                resetMessages.Visible = true;
                var failed = Localization.GetString("PasswordMismatch");
                LogFailure(failed);
                lblHelp.Text = failed;
                return;
            }

            if (UserController.ValidatePassword(txtPassword.Text) == false)
            {
                resetMessages.Visible = true;
                var failed = Localization.GetString("PasswordResetFailed");
                LogFailure(failed);
                lblHelp.Text = failed;
                return;
            }

            //Check New Password is not same as username or banned
            var settings = new MembershipPasswordSettings(User.PortalID);

            if (settings.EnableBannedList)
            {
                var m = new MembershipPasswordController();
                if (m.FoundBannedPassword(txtPassword.Text) || txtUsername.Text == txtPassword.Text)
                {
                    resetMessages.Visible = true;
                    var failed = Localization.GetString("PasswordResetFailed");
                    LogFailure(failed);
                    lblHelp.Text = failed;
                    return;
                }
            }

            string username = txtUsername.Text;

            if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
            {
                var testUser = UserController.GetUserByEmail(PortalId, username); // one additonal call to db to see if an account with that email actually exists
                if (testUser != null)
                {
                    username = testUser.Username; //we need the username of the account in order to change the password in the next step
                }
            }

            if (UserController.ChangePasswordByToken(PortalSettings.PortalId, username, txtPassword.Text, ResetToken) == false)
            {
                resetMessages.Visible = true;
                var failed = Localization.GetString("PasswordResetFailed", LocalResourceFile);
                LogFailure(failed);
                lblHelp.Text = failed;
            }
            else
            {
                //Log user in to site
                LogSuccess();
                var loginStatus = UserLoginStatus.LOGIN_FAILURE;
                UserController.UserLogin(PortalSettings.PortalId, username, txtPassword.Text, "", "", "", ref loginStatus, false);
                RedirectAfterLogin();
            }
        }
示例#17
0
        /// <summary>
        /// Localize correctly sets up the control for US/Canada/Other Countries.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void Localize()
        {
            var countryCode = this.cboCountry.SelectedItem.Value;
            var ctlEntry    = new ListController();

            // listKey in format "Country.US:Region"
            var listKey         = "Country." + countryCode;
            var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey);

            if (entryCollection.Any())
            {
                this.cboRegion.Visible = true;
                this.txtRegion.Visible = false;
                {
                    this.cboRegion.Items.Clear();
                    this.cboRegion.DataSource = entryCollection;
                    this.cboRegion.DataBind();
                    this.cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty));
                }

                if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.valRegion1.Enabled      = true;
                    this.valRegion2.Enabled      = false;
                    this.valRegion1.ErrorMessage = Localization.GetString("StateRequired", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.Text           = Localization.GetString("plState", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.HelpText       = Localization.GetString("plState.Help", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.Text           = Localization.GetString("plZip", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.HelpText       = Localization.GetString("plZip.Help", Localization.GetResourceFile(this, MyFileName));
                }
                else
                {
                    this.valRegion1.ErrorMessage = Localization.GetString("ProvinceRequired", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.Text           = Localization.GetString("plProvince", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.HelpText       = Localization.GetString("plProvince.Help", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.Text           = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.HelpText       = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
                }

                this.valRegion1.Enabled = true;
                this.valRegion2.Enabled = false;
            }
            else
            {
                this.cboRegion.ClearSelection();
                this.cboRegion.Visible       = false;
                this.txtRegion.Visible       = true;
                this.valRegion1.Enabled      = false;
                this.valRegion2.Enabled      = true;
                this.valRegion2.ErrorMessage = Localization.GetString("RegionRequired", Localization.GetResourceFile(this, MyFileName));
                this.plRegion.Text           = Localization.GetString("plRegion", Localization.GetResourceFile(this, MyFileName));
                this.plRegion.HelpText       = Localization.GetString("plRegion.Help", Localization.GetResourceFile(this, MyFileName));
                this.plPostal.Text           = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                this.plPostal.HelpText       = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
            }

            var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true);

            if (reqRegion)
            {
                this.valRegion1.Enabled = false;
                this.valRegion2.Enabled = false;
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Returns the collection of SearchDocuments populated with Tab MetaData for the given portal.
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="startDateLocal"></param>
        /// <returns></returns>
        /// <history>
        ///     [vnguyen]   04/16/2013  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public override IEnumerable <SearchDocument> GetSearchDocuments(int portalId, DateTime startDateLocal)
        {
            var searchDocuments = new Dictionary <string, SearchDocument>();

            var needReindex = PortalController.GetPortalSettingAsBoolean(UserIndexResetFlag, portalId, false);

            if (needReindex)
            {
                startDateLocal = SqlDateTime.MinValue.Value.AddDays(1);
            }

            var controller       = new ListController();
            var textDataType     = controller.GetListEntryInfo("DataType", "Text");
            var richTextDataType = controller.GetListEntryInfo("DataType", "RichText");

            var profileDefinitions = ProfileController.GetPropertyDefinitionsByPortal(portalId, false, false)
                                     .Cast <ProfilePropertyDefinition>()
                                     .Where(d => (textDataType != null && d.DataType == textDataType.EntryID) ||
                                            (richTextDataType != null && d.DataType == richTextDataType.EntryID)).ToList();

            try
            {
                var startUserId = Null.NullInteger;
                while (true)
                {
                    var reader = DataProvider.Instance()
                                 .GetAvailableUsersForIndex(portalId, startDateLocal, startUserId, BatchSize);
                    int rowsAffected = 0;
                    var indexedUsers = new List <int>();

                    while (reader.Read())
                    {
                        var userSearch = GetUserSearch(reader);
                        AddBasicInformation(searchDocuments, indexedUsers, userSearch, portalId);

                        //log the userid so that it can get the correct user collection next time.
                        if (userSearch.UserId > startUserId)
                        {
                            startUserId = userSearch.UserId;
                        }

                        foreach (var definition in profileDefinitions)
                        {
                            var propertyName = definition.PropertyName;

                            if (!ContainsColumn(propertyName, reader))
                            {
                                continue;
                            }

                            var propertyValue = reader[propertyName].ToString();

                            if (string.IsNullOrEmpty(propertyValue) || !propertyValue.Contains(ValueSplitFlag))
                            {
                                continue;
                            }

                            var splitValues = Regex.Split(propertyValue, Regex.Escape(ValueSplitFlag));

                            propertyValue = splitValues[0];
                            var visibilityMode     = ((UserVisibilityMode)Convert.ToInt32(splitValues[1]));
                            var extendedVisibility = splitValues[2];
                            var modifiedTime       = Convert.ToDateTime(splitValues[3]).ToUniversalTime();

                            if (string.IsNullOrEmpty(propertyValue))
                            {
                                continue;
                            }

                            var uniqueKey = string.Format("{0}_{1}", userSearch.UserId, visibilityMode).ToLowerInvariant();
                            if (visibilityMode == UserVisibilityMode.FriendsAndGroups)
                            {
                                uniqueKey = string.Format("{0}_{1}", uniqueKey, extendedVisibility);
                            }

                            if (searchDocuments.ContainsKey(uniqueKey))
                            {
                                var document = searchDocuments[uniqueKey];
                                document.Keywords.Add(propertyName, propertyValue);

                                if (modifiedTime > document.ModifiedTimeUtc)
                                {
                                    document.ModifiedTimeUtc = modifiedTime;
                                }
                            }
                            else
                            {
                                //Need remove use exists index for all visibilities.
                                if (!indexedUsers.Contains(userSearch.UserId))
                                {
                                    indexedUsers.Add(userSearch.UserId);
                                }

                                if (!string.IsNullOrEmpty(propertyValue))
                                {
                                    var searchDoc = new SearchDocument
                                    {
                                        SearchTypeId    = UserSearchTypeId,
                                        UniqueKey       = uniqueKey,
                                        PortalId        = portalId,
                                        ModifiedTimeUtc = modifiedTime,
                                        Description     = userSearch.FirstName,
                                        Title           = userSearch.DisplayName
                                    };
                                    searchDoc.Keywords.Add(propertyName, propertyValue);
                                    searchDoc.NumericKeys.Add("superuser", Convert.ToInt32(userSearch.SuperUser));
                                    searchDocuments.Add(uniqueKey, searchDoc);
                                }
                            }
                        }

                        rowsAffected++;
                    }

                    //close the data reader
                    reader.Close();

                    //remov exists indexes
                    DeleteDocuments(portalId, indexedUsers);

                    if (rowsAffected == 0)
                    {
                        break;
                    }
                }

                if (needReindex)
                {
                    PortalController.DeletePortalSetting(portalId, UserIndexResetFlag);
                }
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
            }

            return(searchDocuments.Values);
        }
示例#19
0
        private void BindLogin()
        {
            List <AuthenticationInfo> authSystems         = AuthenticationController.GetEnabledAuthenticationServices();
            AuthenticationLoginBase   defaultLoginControl = null;

            foreach (AuthenticationInfo authSystem in authSystems)
            {
                try
                {
                    //Figure out if known Auth types are enabled (so we can improve perf and stop loading the control)
                    bool enabled = true;
                    if (authSystem.AuthenticationType == "Facebook" || authSystem.AuthenticationType == "Google" ||
                        authSystem.AuthenticationType == "Live" || authSystem.AuthenticationType == "Twitter")
                    {
                        enabled = PortalController.GetPortalSettingAsBoolean(authSystem.AuthenticationType + "_Enabled", PortalId, false);
                    }

                    if (enabled)
                    {
                        var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                        BindLoginControl(authLoginControl, authSystem);
                        if (authSystem.AuthenticationType == "DNN")
                        {
                            defaultLoginControl = authLoginControl;
                        }

                        //Check if AuthSystem is Enabled
                        if (authLoginControl.Enabled)
                        {
                            var oAuthLoginControl = authLoginControl as OAuthLoginBase;
                            if (oAuthLoginControl != null)
                            {
                                //Add Login Control to List
                                _oAuthControls.Add(oAuthLoginControl);
                            }
                            else
                            {
                                //Add Login Control to List
                                _loginControls.Add(authLoginControl);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                }
            }
            int authCount = _loginControls.Count;

            switch (authCount)
            {
            case 0:
                //No enabled controls - inject default dnn control
                if (defaultLoginControl == null)
                {
                    //No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN)
                    AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN");
                    var authLoginControl          = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                    BindLoginControl(authLoginControl, authSystem);
                    DisplayLoginControl(authLoginControl, false, false);
                }
                else
                {
                    //Portal has no login controls enabled so load default DNN control
                    DisplayLoginControl(defaultLoginControl, false, false);
                }
                break;

            case 1:
                //We don't want the control to render with tabbed interface
                DisplayLoginControl(_loginControls[0], false, false);
                break;

            default:
                foreach (AuthenticationLoginBase authLoginControl in _loginControls)
                {
                    DisplayTabbedLoginControl(authLoginControl, tsLogin.Tabs);
                }

                break;
            }
            BindOAuthControls();
        }
示例#20
0
 /// <summary>
 /// 获取站点设置
 /// </summary>
 /// <param name="SettingName"></param>
 /// <param name="defaultValue"></param>
 /// <returns></returns>
 public Boolean GetSetting(string SettingName, Boolean defaultValue)
 {
     return(PortalController.GetPortalSettingAsBoolean(SettingsFormat(SettingName), PortalSettings.PortalId, defaultValue));
 }
示例#21
0
        private void cmdUpdate_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                PortalController.PortalTemplateInfo template = LoadPortalTemplateInfoForSelectedItem();

                try
                {
                    bool   blnChild;
                    string strPortalAlias;
                    string strChildPath  = string.Empty;
                    var    closePopUpStr = string.Empty;

                    //check template validity
                    var    messages       = new ArrayList();
                    string schemaFilename = Server.MapPath(string.Concat(AppRelativeTemplateSourceDirectory, "portal.template.xsd"));
                    string xmlFilename    = template.TemplateFilePath;
                    var    xval           = new PortalTemplateValidator();
                    if (!xval.Validate(xmlFilename, schemaFilename))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, "", String.Format(Localization.GetString("InvalidTemplate", LocalResourceFile), Path.GetFileName(template.TemplateFilePath)), ModuleMessage.ModuleMessageType.RedError);
                        messages.AddRange(xval.Errors);
                        lstResults.Visible    = true;
                        lstResults.DataSource = messages;
                        lstResults.DataBind();
                        validationPanel.Visible = true;
                        return;
                    }

                    //Set Portal Name
                    txtPortalAlias.Text = txtPortalAlias.Text.ToLowerInvariant();
                    txtPortalAlias.Text = txtPortalAlias.Text.Replace("http://", "");

                    //Validate Portal Name
                    if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                    {
                        blnChild       = true;
                        strPortalAlias = txtPortalAlias.Text;
                    }
                    else
                    {
                        blnChild = (optType.SelectedValue == "C");

                        strPortalAlias = blnChild ? PortalController.GetPortalFolder(txtPortalAlias.Text) : txtPortalAlias.Text;
                    }

                    string message = String.Empty;
                    ModuleMessage.ModuleMessageType messageType = ModuleMessage.ModuleMessageType.RedError;
                    if (!PortalAliasController.ValidateAlias(strPortalAlias, blnChild))
                    {
                        message = Localization.GetString("InvalidName", LocalResourceFile);
                    }

                    //check whether have conflict between tab path and portal alias.
                    var checkTabPath = string.Format("//{0}", strPortalAlias);
                    if (TabController.GetTabByTabPath(PortalSettings.PortalId, checkTabPath, string.Empty) != Null.NullInteger ||
                        TabController.GetTabByTabPath(Null.NullInteger, checkTabPath, string.Empty) != Null.NullInteger)
                    {
                        message = Localization.GetString("DuplicateWithTab", LocalResourceFile);
                    }

                    //Validate Password
                    if (txtPassword.Text != txtConfirm.Text)
                    {
                        if (!String.IsNullOrEmpty(message))
                        {
                            message += "<br/>";
                        }
                        message += Localization.GetString("InvalidPassword", LocalResourceFile);
                    }
                    string strServerPath = Globals.GetAbsoluteServerPath(Request);

                    //Set Portal Alias for Child Portals
                    if (String.IsNullOrEmpty(message))
                    {
                        if (blnChild)
                        {
                            strChildPath = strServerPath + strPortalAlias;

                            if (Directory.Exists(strChildPath))
                            {
                                message = Localization.GetString("ChildExists", LocalResourceFile);
                            }
                            else
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    strPortalAlias = Globals.GetDomainName(Request, true) + "/" + strPortalAlias;
                                }
                                else
                                {
                                    strPortalAlias = txtPortalAlias.Text;
                                }
                            }
                        }
                    }

                    //Get Home Directory
                    string homeDir = txtHomeDirectory.Text != @"Portals/[PortalID]" ? txtHomeDirectory.Text : "";

                    //Validate Home Folder
                    if (!string.IsNullOrEmpty(homeDir))
                    {
                        if (string.IsNullOrEmpty(String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, homeDir).Replace("/", "\\")))
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                        if (homeDir.Contains("admin") || homeDir.Contains("DesktopModules") || homeDir.ToLowerInvariant() == "portals/")
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                    }

                    //Validate Portal Alias
                    if (!string.IsNullOrEmpty(strPortalAlias))
                    {
                        PortalAliasInfo portalAlias = null;
                        foreach (PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values)
                        {
                            if (String.Equals(alias.HTTPAlias, strPortalAlias, StringComparison.InvariantCultureIgnoreCase))
                            {
                                portalAlias = alias;
                                break;
                            }
                        }

                        if (portalAlias != null)
                        {
                            message = Localization.GetString("DuplicatePortalAlias", LocalResourceFile);
                        }
                    }

                    //Create Portal
                    if (String.IsNullOrEmpty(message))
                    {
                        //Attempt to create the portal
                        UserInfo adminUser = new UserInfo();
                        int      intPortalId;
                        try
                        {
                            if (useCurrent.Checked)
                            {
                                adminUser   = UserInfo;
                                intPortalId = PortalController.Instance.CreatePortal(txtPortalName.Text,
                                                                                     adminUser.UserID,
                                                                                     txtDescription.Text,
                                                                                     txtKeyWords.Text,
                                                                                     template,
                                                                                     homeDir,
                                                                                     strPortalAlias,
                                                                                     strServerPath,
                                                                                     strChildPath,
                                                                                     blnChild);
                            }
                            else
                            {
                                adminUser = new UserInfo
                                {
                                    FirstName   = txtFirstName.Text,
                                    LastName    = txtLastName.Text,
                                    Username    = txtUsername.Text,
                                    DisplayName = txtFirstName.Text + " " + txtLastName.Text,
                                    Email       = txtEmail.Text,
                                    IsSuperUser = false,
                                    Membership  =
                                    {
                                        Approved         = true,
                                        Password         = txtPassword.Text,
                                        PasswordQuestion = txtQuestion.Text,
                                        PasswordAnswer   = txtAnswer.Text
                                    },
                                    Profile =
                                    {
                                        FirstName = txtFirstName.Text,
                                        LastName  = txtLastName.Text
                                    }
                                };

                                intPortalId = PortalController.Instance.CreatePortal(txtPortalName.Text,
                                                                                     adminUser,
                                                                                     txtDescription.Text,
                                                                                     txtKeyWords.Text,
                                                                                     template,
                                                                                     homeDir,
                                                                                     strPortalAlias,
                                                                                     strServerPath,
                                                                                     strChildPath,
                                                                                     blnChild);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);

                            intPortalId = Null.NullInteger;
                            message     = ex.Message;
                        }

                        if (intPortalId != -1)
                        {
                            //Add new portal to Site Group
                            if (cboSiteGroups.SelectedValue != "-1")
                            {
                                var portal      = PortalController.Instance.GetPortal(intPortalId);
                                var portalGroup = PortalGroupController.Instance.GetPortalGroups().SingleOrDefault(g => g.PortalGroupId == Int32.Parse(cboSiteGroups.SelectedValue));
                                if (portalGroup != null)
                                {
                                    PortalGroupController.Instance.AddPortalToGroup(portal, portalGroup, args => { });
                                }
                            }

                            //Create a Portal Settings object for the new Portal
                            PortalInfo objPortal   = PortalController.Instance.GetPortal(intPortalId);
                            var        newSettings = new PortalSettings {
                                PortalAlias = new PortalAliasInfo {
                                    HTTPAlias = strPortalAlias
                                }, PortalId = intPortalId, DefaultLanguage = objPortal.DefaultLanguage
                            };
                            string webUrl = Globals.AddHTTP(strPortalAlias);
                            try
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    message = (String.IsNullOrEmpty(PortalSettings.Email) &&
                                               String.IsNullOrEmpty(Host.HostEmail)) ?
                                              string.Format(Localization.GetString("UnknownEmailAddress.Error", LocalResourceFile), message, webUrl, closePopUpStr):
                                              Mail.SendMail(PortalSettings.Email,
                                                            txtEmail.Text,
                                                            string.IsNullOrEmpty(PortalSettings.Email)? Host.HostEmail : string.IsNullOrEmpty(Host.HostEmail)? PortalSettings.Email : PortalSettings.Email + ";" + Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                                else
                                {
                                    message = String.IsNullOrEmpty(Host.HostEmail)?
                                              string.Format(Localization.GetString("UnknownEmailAddress.Error", LocalResourceFile), message, webUrl, closePopUpStr) :
                                              Mail.SendMail(Host.HostEmail,
                                                            txtEmail.Text,
                                                            Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                            }
                            catch (Exception exc)
                            {
                                Logger.Error(exc);

                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("UnknownSendMail.Error", LocalResourceFile), webUrl, closePopUpStr);
                            }
                            EventLogController.Instance.AddLog(PortalController.Instance.GetPortal(intPortalId), PortalSettings, UserId, "", EventLogController.EventLogType.PORTAL_CREATED);

                            // mark default language as published if content localization is enabled
                            bool ContentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", PortalId, false);
                            if (ContentLocalizationEnabled)
                            {
                                LocaleController lc = new LocaleController();
                                lc.PublishLanguage(intPortalId, objPortal.DefaultLanguage, true);
                            }

                            //Redirect to this new site
                            if (message == Null.NullString)
                            {
                                webUrl = (PortalSettings.EnablePopUps) ? UrlUtils.ClosePopUp(true, webUrl, false) : webUrl;
                                Response.Redirect(webUrl, true);
                            }
                            else
                            {
                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("SendMail.Error", LocalResourceFile), message, webUrl, closePopUpStr);
                                messageType   = ModuleMessage.ModuleMessageType.YellowWarning;
                            }
                        }
                    }
                    UI.Skins.Skin.AddModuleMessage(this, "", message, messageType);
                }
                catch (Exception exc) //Module failed to load
                {
                    Exceptions.ProcessModuleLoadException(this, exc);
                }
            }
        }
示例#22
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
            {
                var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                string userName    = PortalSecurity.Instance.InputFilter(txtUsername.Text,
                                                                         PortalSecurity.FilterFlag.NoScripting |
                                                                         PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                         PortalSecurity.FilterFlag.NoMarkup);

                //DNN-6093
                //check if we use email address here rather than username
                UserInfo userByEmail         = null;
                var      emailUsedAsUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false);

                if (emailUsedAsUsername)
                {
                    // one additonal call to db to see if an account with that email actually exists
                    userByEmail = UserController.GetUserByEmail(PortalId, userName);

                    if (userByEmail != null)
                    {
                        //we need the username of the account in order to authenticate in the next step
                        userName = userByEmail.Username;
                    }
                }

                UserInfo objUser = null;

                if (!emailUsedAsUsername || userByEmail != null)
                {
                    objUser = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                }

                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                if (objUser != null && loginStatus != UserLoginStatus.LOGIN_FAILURE && emailUsedAsUsername)
                {
                    //make sure internal username matches current e-mail address
                    if (objUser.Username.ToLower() != objUser.Email.ToLower())
                    {
                        UserController.ChangeUsername(objUser.UserID, objUser.Email);
                        userName = objUser.Username = objUser.Email;
                    }
                }

                //Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = chkCookie.Checked
                };
                OnUserAuthenticated(eventArgs);
            }
        }
示例#23
0
 private static bool IsLocalizationEnabled(int portalId)
 {
     return(PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false));
 }
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
            {
                var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                string userName    = new PortalSecurity().InputFilter(txtUsername.Text,
                                                                      PortalSecurity.FilterFlag.NoScripting |
                                                                      PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                      PortalSecurity.FilterFlag.NoMarkup);

                //DNN-6093
                //check if we use email address here rather than username
                if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                {
                    var testUser = UserController.GetUserByEmail(PortalId, userName); // one additonal call to db to see if an account with that email actually exists
                    if (testUser != null)
                    {
                        userName = testUser.Username; //we need the username of the account in order to authenticate in the next step
                    }
                }

                var objUser       = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                if (loginStatus != UserLoginStatus.LOGIN_FAILURE && PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                {
                    //make sure internal username matches current e-mail address
                    if (objUser.Username.ToLower() != objUser.Email.ToLower())
                    {
                        UserController.ChangeUsername(objUser.UserID, objUser.Email);
                    }

                    Response.Cookies.Remove("USERNAME_CHANGED");
                }

                //login success
                if (loginStatus != UserLoginStatus.LOGIN_FAILURE)
                {
                    //Administrator does not execute
                    if (!objUser.IsSuperUser)
                    {
                        //Get whether the user's two factor is enable
                        var EnableTwoFactor = ShowUserProfile(objUser, "EnableTwoFactor");
                        if (String.IsNullOrEmpty(EnableTwoFactor) || EnableTwoFactor.ToLower() == "true")
                        {
                            //go two factor page
                            try { Response.Redirect(LoginURL(objUser.UserID, objUser.LastModifiedOnDate)); }
                            finally { }
                        }
                    }
                }


                //Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = chkCookie.Checked
                };
                OnUserAuthenticated(eventArgs);
            }
        }