public UserCreateStatus AddDNNUser(UserInfo AuthenticationUser) { PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings(); PortalSecurity objSecurity = new PortalSecurity(); Entities.Users.UserController objDNNUsers = new Entities.Users.UserController(); UserController objAuthUsers = new UserController(); Entities.Users.UserInfo objDNNUser = (Entities.Users.UserInfo)AuthenticationUser; int AffiliateId = -1; if (HttpContext.Current.Request.Cookies["AffiliateId"] != null) { AffiliateId = int.Parse(HttpContext.Current.Request.Cookies["AffiliateId"].Value); } int UserID = -1; UserCreateStatus createStatus; createStatus = Entities.Users.UserController.CreateUser(ref objDNNUser); UserID = objDNNUser.UserID; if (AuthenticationUser.AuthenticationExists && UserID > -1) { AuthenticationUser.UserID = UserID; AddUserRoles(_portalSettings.PortalId, AuthenticationUser); } return createStatus; }
public static string DecryptParameter(string value, string encryptionKey) { PortalSecurity objSecurity = new PortalSecurity(); value = value.Replace("_", "/"); value = value.Replace("-", "+"); value = value.Replace("%3d", "="); return objSecurity.Decrypt(encryptionKey, value); }
public SubscriberInfo() { _id = System.Guid.NewGuid().ToString(); _name = ""; _description = ""; _address = ""; PortalSecurity oPortalSecurity = new PortalSecurity(); _privateKey = oPortalSecurity.CreateKey(16); }
private static void AddEventLog(int portalId, string username, int userId, string portalName, string Ip, UserLoginStatus loginStatus) { Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController(); Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo(); PortalSecurity objSecurity = new PortalSecurity(); objEventLogInfo.AddProperty("IP", Ip); objEventLogInfo.LogPortalID = portalId; objEventLogInfo.LogPortalName = portalName; objEventLogInfo.LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); objEventLogInfo.LogUserID = userId; objEventLogInfo.LogTypeKey = loginStatus.ToString(); objEventLog.AddLog(objEventLogInfo); }
/// <summary> /// Override CreateChildControls to create the control tree. /// </summary> protected override void CreateChildControls() { // Create an arraylist to fill with // the TabItems representing the Tree ArrayList crumbs; if (HttpContext.Current != null) { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; //Display breadcrumbs if the user has click a tab link (Without hit the Database again) if (portalSettings.ActivePage.PageID > 0) { ArrayList authorizedTabs = new ArrayList(); int addedTabs = 0; for (int i = 0; i < portalSettings.DesktopPages.Count; i++) { PageStripDetails tab = (PageStripDetails)portalSettings.DesktopPages[i]; if (PortalSecurity.IsInRoles(tab.AuthorizedRoles)) { authorizedTabs.Add(tab); } addedTabs++; } crumbs = GetBreadCrumbs(portalSettings.ActivePage, authorizedTabs); crumbs.Sort(); } else { crumbs = new ArrayList(); } } else //design time { crumbs = new ArrayList(); crumbs.Add("Item1"); crumbs.Add("Item2"); crumbs.Add("Item3"); } if (crumbs.Count > 1) { StringBuilder sb = new StringBuilder(); sb.Append("<div class='"); sb.Append(CssClass); sb.Append("'>"); int ct = 0; // Build the Breadcrumbs and add them to the div foreach (PageItem item in crumbs) { if (ct > 0) { sb.Append(Separator.ToString()); } if (ct != (crumbs.Count - 1)) { sb.Append("<a href='"); sb.Append(HttpUrlBuilder.BuildUrl(item.ID)); sb.Append("'>"); sb.Append(item.Name.ToString()); sb.Append("</a>"); } else { sb.Append(item.Name.ToString()); } ct++; } sb.Append("</div>"); Text = sb.ToString(); } else { Visible = false; } }
public HttpResponseMessage Create(CreateDTO postData) { try { var journalTypeId = 1; switch (postData.JournalType) { case "link": journalTypeId = 2; break; case "photo": journalTypeId = 3; break; case "file": journalTypeId = 4; break; } if (postData.ProfileId == -1) { postData.ProfileId = UserInfo.UserID; } if (postData.GroupId > 0) { postData.ProfileId = -1; RoleInfo roleInfo = RoleController.Instance.GetRoleById(ActiveModule.OwnerPortalID, postData.GroupId); if (roleInfo != null && !roleInfo.IsPublic) { postData.SecuritySet = "R"; } } var ji = new JournalItem { JournalId = -1, JournalTypeId = journalTypeId, PortalId = ActiveModule.OwnerPortalID, UserId = UserInfo.UserID, SocialGroupId = postData.GroupId, ProfileId = postData.ProfileId, Summary = postData.Text ?? "", SecuritySet = postData.SecuritySet }; ji.Title = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Title)); ji.Summary = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Summary)); var ps = new PortalSecurity(); ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoScripting); ji.Title = Utilities.RemoveHTML(ji.Title); ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoMarkup); ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoScripting); ji.Summary = Utilities.RemoveHTML(ji.Summary); ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoMarkup); //parse the mentions context in post data var originalSummary = ji.Summary; IDictionary <string, UserInfo> mentionedUsers = new Dictionary <string, UserInfo>(); ji.Summary = ParseMentions(ji.Summary, postData.Mentions, ref mentionedUsers); if (ji.Summary.Length > 2000) { ji.Body = ji.Summary; ji.Summary = null; } if (!string.IsNullOrEmpty(postData.ItemData)) { ji.ItemData = postData.ItemData.FromJson <ItemData>(); var originalImageUrl = ji.ItemData.ImageUrl; if (!IsImageFile(ji.ItemData.ImageUrl)) { ji.ItemData.ImageUrl = string.Empty; } ji.ItemData.Description = HttpUtility.UrlDecode(ji.ItemData.Description); if (!string.IsNullOrEmpty(ji.ItemData.Url) && ji.ItemData.Url.StartsWith("fileid=")) { var fileId = Convert.ToInt32(ji.ItemData.Url.Replace("fileid=", string.Empty).Trim()); var file = FileManager.Instance.GetFile(fileId); ji.ItemData.Title = file.FileName; ji.ItemData.Url = Globals.LinkClick(ji.ItemData.Url, Null.NullInteger, Null.NullInteger); if (string.IsNullOrEmpty(ji.ItemData.ImageUrl) && originalImageUrl.ToLower().StartsWith("/linkclick.aspx?") && AcceptedFileExtensions.Contains(file.Extension.ToLower())) { ji.ItemData.ImageUrl = originalImageUrl; } } } JournalController.Instance.SaveJournalItem(ji, ActiveModule); SendMentionNotifications(mentionedUsers, ji, originalSummary); return(Request.CreateResponse(HttpStatusCode.OK, ji)); } catch (Exception exc) { Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
private bool IsReviewer(UserInfo user, PortalSettings settings, IEnumerable <ContentWorkflowStatePermission> permissions) { var administratorRoleName = settings.AdministratorRoleName; return(user.IsSuperUser || PortalSecurity.IsInRoles(user, settings, administratorRoleName) || PortalSecurity.IsInRoles(user, settings, PermissionController.BuildPermissions(permissions.ToList(), "REVIEW"))); }
/// <summary> /// Handles the Load event of the DesktopDefault control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="System.EventArgs"/> instance containing the event data. /// </param> private void DesktopDefault_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request.Params["panelist"])) { this.RenderContentAreaList(); } // intento obtener el id de la pagina desde el query string query = Request.Url.Query; int pageId = 0; if (query.Contains("?") && query.ToLower().Contains("pageid")) { int index = query.IndexOf('?'); int indexPageId = query.ToLower().IndexOf("pageid") + 5; if (index < indexPageId - 5) { query = query.Substring(indexPageId + 2, query.Length - indexPageId - 2); index = query.IndexOf('&'); if (index > 0) // no va hasta el final el numero de pagina { query = query.Substring(0, index); } try { pageId = int.Parse(query); } catch (Exception) { pageId = 0; } } else { pageId = 0; } } else { pageId = this.PortalSettings.ActivePage.PageID; } if (pageId == 0) { pageId = Convert.ToInt32(SiteMap.RootNode.ChildNodes[0].Key); this.Response.Redirect(HttpUrlBuilder.BuildUrl(pageId)); } string urlToRedirect = ""; bool redirect = HttpUrlBuilder.ValidateProperUrl(pageId, ref urlToRedirect); if (!redirect) { this.Response.Redirect(urlToRedirect); } if (!PortalSecurity.IsInRoles(this.PortalSettings.ActivePage.AuthorizedRoles) && !this.User.IsInRole("Admins")) { PortalSecurity.AccessDenied(); } else { if (this.Request.Params["r"] == null || this.Request.Params["r"] != "0") { var user = Membership.GetUser(); } var userName = this.Request.Params["u"]; var pass = this.Request.Params["p"]; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pass)) { // PortalSecurity.SignOn(userName, pass, false, "~/DesktopDefault.aspx"); var rem = (this.Request.Params["rem"] ?? "0").Equals("1") ? true : false; PortalSecurity.SignOn(userName, pass, rem, "~/DesktopDefault.aspx"); this.Response.Redirect("~/DesktopDefault.aspx"); } if (string.IsNullOrEmpty(Request.Params["panelist"])) { this.LoadPage(); } } }
/// ----------------------------------------------------------------------------- /// <summary> /// UserLogin attempts to log the user in, and returns the User if successful /// </summary> /// <remarks> /// </remarks> /// <param name="portalId">The Id of the Portal the user belongs to</param> /// <param name="username">The user name of the User attempting to log in</param> /// <param name="password">The password of the User attempting to log in (may not be used by all Auth types)</param> /// <param name="authType">The type of Authentication Used</param> /// <param name="verificationCode">The verification code of the User attempting to log in</param> /// <param name="loginStatus">An enumerated value indicating the login status.</param> /// <returns>The User as a UserInfo object</returns> /// ----------------------------------------------------------------------------- public override UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus) { //For now, we are going to ignore the possibility that the User may exist in the //Global Data Store but not in the Local DataStore ie. A shared Global Data Store //Initialise Login Status to Failure loginStatus = UserLoginStatus.LOGIN_FAILURE; DataCache.ClearUserCache(portalId, username); DataCache.ClearCache(GetCacheKey(username)); //Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary UserInfo user = (authType == "DNN") ? GetUserByUserName(portalId, username) : GetUserByAuthToken(portalId, username, authType); if (user != null && !user.IsDeleted) { //Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); //Fill Membership Property from AspNet MembershipUser FillUserMembership(aspnetUser, user); //Check if the User is Locked Out (and unlock if AutoUnlock has expired) if (aspnetUser.IsLockedOut) { if (AutoUnlockUser(aspnetUser)) { //Unlock User user.Membership.LockedOut = false; } else { loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT; } } //Check in a verified situation whether the user is Approved if (user.Membership.Approved == false && user.IsSuperUser == false) { //Check Verification code var ps = new PortalSecurity(); if (verificationCode == ps.EncryptString(portalId + "-" + user.UserID, Config.GetDecryptionkey())) { UserController.ApproveUser(user); } else { loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; } } //Verify User Credentials bool bValid = false; loginStatus = ValidateLogin(username, authType, user, loginStatus, password, ref bValid, portalId); if (!bValid) { //Clear the user object user = null; } } else { //Clear the user object user = null; } return user; }
private UserCreateStatus ValidateForProfanity(UserInfo user) { var portalSecurity = new PortalSecurity(); var createStatus = UserCreateStatus.AddUser; Hashtable settings = UserController.GetUserSettings(user.PortalID); bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); //Validate Profanity if (useProfanityFilter) { if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity)) { createStatus = UserCreateStatus.InvalidUserName; } if (!String.IsNullOrEmpty(user.DisplayName)) { if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) { createStatus = UserCreateStatus.InvalidDisplayName; } } } return createStatus; }
/// <summary> /// CreateDNNUser persists the DNN User information to the Database /// </summary> /// <remarks> /// </remarks> /// <param name="user">The user to persist to the Data Store.</param> /// <returns>The UserId of the newly created user.</returns> /// <history> /// [cnurse] 12/13/2005 created /// </history> private UserCreateStatus CreateDNNUser( ref UserInfo user ) { PortalSecurity objSecurity = new PortalSecurity(); string userName = objSecurity.InputFilter( user.Username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string email = objSecurity.InputFilter( user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string lastName = objSecurity.InputFilter( user.LastName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string firstName = objSecurity.InputFilter( user.FirstName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); UserCreateStatus createStatus = UserCreateStatus.Success; string displayName = objSecurity.InputFilter( user.DisplayName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); bool updatePassword = user.Membership.UpdatePassword; bool isApproved = user.Membership.Approved; try { user.UserID = Convert.ToInt32( dataProvider.AddUser( user.PortalID, userName, firstName, lastName, user.AffiliateID, user.IsSuperUser, email, displayName, updatePassword, isApproved ) ); } catch( Exception ex ) { //Clear User (duplicate User information) user = null; createStatus = UserCreateStatus.ProviderError; } return createStatus; }
/// ----------------------------------------------------------------------------- /// <summary> /// CreateEditor creates the control collection. /// </summary> /// <history> /// [cnurse] 05/08/2006 created /// </history> /// ----------------------------------------------------------------------------- protected override void CreateEditor() { CategoryDataField = "PropertyCategory"; EditorDataField = "DataType"; NameDataField = "PropertyName"; RequiredDataField = "Required"; ValidationExpressionDataField = "ValidationExpression"; ValueDataField = "PropertyValue"; VisibleDataField = "Visible"; VisibilityDataField = "ProfileVisibility"; LengthDataField = "Length"; base.CreateEditor(); foreach (FieldEditorControl editor in Fields) { //Check whether Field is readonly string fieldName = editor.Editor.Name; ProfilePropertyDefinitionCollection definitions = editor.DataSource as ProfilePropertyDefinitionCollection; ProfilePropertyDefinition definition = definitions[fieldName]; if (definition != null && definition.ReadOnly && (editor.Editor.EditMode == PropertyEditorMode.Edit)) { PortalSettings ps = PortalController.Instance.GetCurrentPortalSettings(); if (!PortalSecurity.IsInRole(ps.AdministratorRoleName)) { editor.Editor.EditMode = PropertyEditorMode.View; } } //We need to wire up the RegionControl to the CountryControl if (editor.Editor is DNNRegionEditControl) { ListEntryInfo country = null; foreach (FieldEditorControl checkEditor in Fields) { if (checkEditor.Editor is DNNCountryEditControl) { var countryEdit = (DNNCountryEditControl)checkEditor.Editor; var objListController = new ListController(); var countries = objListController.GetListEntryInfoItems("Country"); foreach (ListEntryInfo checkCountry in countries) { if (checkCountry.Text == Convert.ToString(countryEdit.Value)) { country = checkCountry; break; } } } } //Create a ListAttribute for the Region string countryKey; if (country != null) { countryKey = "Country." + country.Value; } else { countryKey = "Country.Unknown"; } var attributes = new object[1]; attributes[0] = new ListAttribute("Region", countryKey, ListBoundField.Text, ListBoundField.Text); editor.Editor.CustomAttributes = attributes; } } }
/// <summary> /// UpdateUser persists a user to the Data Store /// </summary> /// <remarks> /// </remarks> /// <param name="user">The user to persist to the Data Store.</param> /// <history> /// [cnurse] 12/13/2005 created /// </history> public override void UpdateUser( UserInfo user ) { PortalSecurity objSecurity = new PortalSecurity(); string firstName = objSecurity.InputFilter( user.FirstName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string lastName = objSecurity.InputFilter( user.LastName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string email = objSecurity.InputFilter( user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); string displayName = objSecurity.InputFilter( user.DisplayName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); bool updatePassword = user.Membership.UpdatePassword; bool isApproved = user.Membership.Approved; if( displayName == "" ) { displayName = firstName + " " + lastName; } //Persist the DNN User to the Database dataProvider.UpdateUser( user.UserID, user.PortalID, firstName, lastName, email, displayName, updatePassword, isApproved ); //Persist the Membership to the Data Store UpdateUserMembership( user ); //Persist the Profile to the Data Store ProfileController.UpdateUserProfile( user ); }
/// <summary> /// UpdateUserMembership persists a user's Membership to the Data Store /// </summary> /// <remarks> /// </remarks> /// <param name="user">The user to persist to the Data Store.</param> /// <history> /// [cnurse] 12/13/2005 created /// </history> private void UpdateUserMembership( UserInfo user ) { PortalSecurity objSecurity = new PortalSecurity(); string email = objSecurity.InputFilter( user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup ); //Persist the Membership Properties to the AspNet Data Store MembershipUser objMembershipUser; objMembershipUser = System.Web.Security.Membership.GetUser( user.Username ); objMembershipUser.Email = email; objMembershipUser.LastActivityDate = DateTime.Now; objMembershipUser.IsApproved = user.Membership.Approved; System.Web.Security.Membership.UpdateUser( objMembershipUser ); }
/// <summary> /// TransferUsers transfers legacy users to the new ASP.NET MemberRole Architecture /// </summary> /// <remarks> /// </remarks> /// <param name="PortalID">Id of the Portal</param> /// <param name="arrUsers">An ArrayList of the Users</param> /// <param name="SuperUsers">A flag indicating whether the users are SuperUsers</param> /// <history> /// [cnurse] 11/6/2004 documented /// [cnurse] 12/15/2005 Moved to MembershipProvider /// </history> private void TransferUsers( int PortalID, ArrayList arrUsers, bool SuperUsers ) { UserController objUserCont = new UserController(); try { //Set the MemberRole API ApplicationName if( SuperUsers ) { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Start Transferring SuperUsers to MemberRole:<br>" ); } else { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Start Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>" ); } IDataReader dr; string EncryptionKey = ""; dr = DotNetNuke.Data.DataProvider.Instance().GetHostSetting( "EncryptionKey" ); if( dr.Read() ) { EncryptionKey = dr["SettingValue"].ToString(); } dr.Close(); int i; int iMin = 1; int iMax = 100; for( i = 0; i <= arrUsers.Count - 1; i++ ) { if( i%100 == 0 ) { if( iMin > arrUsers.Count ) { iMin = arrUsers.Count; } if( iMax > arrUsers.Count ) { iMax = arrUsers.Count; } HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Transferring Users:" + iMin.ToString() + " to " + iMax.ToString() + "<br>" ); iMin = iMin + 100; iMax = iMax + 100; } UserInfo objUser; objUser = (UserInfo)arrUsers[i]; MembershipCreateStatus objStatus; string strPassword; PortalSecurity objPortalSecurity = new PortalSecurity(); strPassword = objPortalSecurity.Decrypt( EncryptionKey, objUser.Membership.Password ); if( objUser.IsSuperUser ) { objUser.Membership.Approved = true; } MembershipUser objMembershipUser; objMembershipUser = System.Web.Security.Membership.CreateUser( objUser.Username, strPassword, objUser.Email, null, null, objUser.Membership.Approved, out objStatus ); if( objStatus != MembershipCreateStatus.Success ) { Exceptions.LogException( new Exception( objStatus.ToString() ) ); } else { try { ProfileBase objProfile; objProfile = ProfileBase.Create( objUser.Username, true ); objProfile["FirstName"] = objUser.Profile.FirstName; objProfile["LastName"] = objUser.Profile.LastName; objProfile["Unit"] = objUser.Profile.Unit; objProfile["Street"] = objUser.Profile.Street; objProfile["City"] = objUser.Profile.City; objProfile["Region"] = objUser.Profile.Region; objProfile["PostalCode"] = objUser.Profile.PostalCode; objProfile["Country"] = objUser.Profile.Country; objProfile["Telephone"] = objUser.Profile.Telephone; objProfile.Save(); } catch( Exception exc ) { Exceptions.LogException( exc ); } RoleController objDNNRoles = new RoleController(); string[] arrUserRoles = objDNNRoles.GetRolesByUser( objUser.UserID, PortalID ); if( arrUserRoles != null ) { try { System.Web.Security.Roles.AddUserToRoles( objUser.Username, arrUserRoles ); } catch( Exception exc ) { Exceptions.LogException( exc ); } } } } } finally { } if( SuperUsers ) { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Finish Transferring SuperUsers to MemberRole:<br>" ); } else { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Finish Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>" ); } }
public static void UpdateConfig(int PortalID, bool WindowsAuthentication, string RootDomain, string EmailDomain, string AuthenticationUserName, string AuthenticationPassword, bool SynchronizeRole, bool SynchronizePassword, string ProviderTypeName, string AuthenticationType) { PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings(); ModuleController objModules = new ModuleController(); PortalSecurity objSecurity = new PortalSecurity(); ModuleInfo objModuleInfo = objModules.GetModuleByDefinition(PortalID, "Site Settings"); int intModuleId = objModuleInfo.ModuleID; objModules.UpdateModuleSetting(intModuleId, "WindowsAuthentication", WindowsAuthentication.ToString()); objModules.UpdateModuleSetting(intModuleId, "SynchronizeRole", SynchronizeRole.ToString()); objModules.UpdateModuleSetting(intModuleId, "SynchronizePassword", SynchronizePassword.ToString()); objModules.UpdateModuleSetting(intModuleId, "RootDomain", RootDomain); objModules.UpdateModuleSetting(intModuleId, "EmailDomain", EmailDomain); objModules.UpdateModuleSetting(intModuleId, "UserName", AuthenticationUserName); objModules.UpdateModuleSetting(intModuleId, "ProviderTypeName", ProviderTypeName); objModules.UpdateModuleSetting(intModuleId, "AuthenticationType", AuthenticationType); //Only update password if it has been changed // HACK : Modified to not error if object is null. //if (AuthenticationPassword.Length > 0) if (!String.IsNullOrEmpty(AuthenticationPassword)) { objModules.UpdateModuleSetting(intModuleId, "AuthenticationPassword", Convert.ToString(objSecurity.Encrypt(AUTHENTICATION_KEY, AuthenticationPassword))); } }
/// <summary> /// Obtain Authentication settings from database /// </summary> /// <remarks> /// Setting records are stored in ModuleSettings table, separately for each portal, /// this method allows each portal could have different accessing method to Windows Active Directory /// </remarks> public Configuration() { PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings(); ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(AUTHENTICATION_KEY); mPortalId = _portalSettings.PortalId; PortalSecurity objSecurity = new PortalSecurity(); try { if (_providerConfiguration.DefaultProvider == null) { // No provider specified, so disable authentication feature return; } else { ModuleController objModules = new ModuleController(); ModuleInfo objModuleInfo = objModules.GetModuleByDefinition(mPortalId, "Site Settings"); Hashtable settings = PortalSettings.GetModuleSettings(objModuleInfo.ModuleID); mWindowsAuthentication = Convert.ToBoolean(Null.GetNull(settings["WindowsAuthentication"], mWindowsAuthentication)); mSynchronizeRole = Convert.ToBoolean(Null.GetNull(settings["SynchronizeRole"], mSynchronizeRole)); mSynchronizePassword = Convert.ToBoolean(Null.GetNull(settings["SynchronizePassword"], mSynchronizePassword)); mRootDomain = Convert.ToString(Null.GetNull(settings["RootDomain"], mRootDomain)); mEmailDomain = Convert.ToString(Null.GetNull(settings["EmailDomain"], mEmailDomain)); mUserName = Convert.ToString(Null.GetNull(settings["UserName"], mUserName)); mProviderTypeName = Convert.ToString(Null.GetNull(settings["ProviderTypeName"], mProviderTypeName)); mAuthenticationType = Convert.ToString(Null.GetNull(settings["AuthenticationType"], mAuthenticationType)); // Since DNN 3.0, HostSettings("EncryptionKey") is empty string, so we handle by AUTHENTICATION_KEY mPassword = objSecurity.Decrypt(AUTHENTICATION_KEY, Convert.ToString(Null.GetNull(settings["AuthenticationPassword"], mPassword.ToString()))); //mPassword = objSecurity.Decrypt(CStr(_portalSettings.HostSettings("EncryptionKey")), CType(GetValue(settings("AuthenticationPassword"), mPassword.ToString), String)) } } catch (Exception) { } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.selectCulture.SelectedIndexChanged += this.selectCulture_SelectedIndexChanged; this.rptLanguages.ItemDataBound += this.rptLanguages_ItemDataBound; try { var locales = new Dictionary <string, Locale>(); IEnumerable <ListItem> cultureListItems = DotNetNuke.Services.Localization.Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentCulture, string.Empty, false); foreach (Locale loc in LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).Values) { string defaultRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", loc.Code), this.PortalSettings.PortalId, "Administrators"); if (!this.PortalSettings.ContentLocalizationEnabled || (this.LocaleIsAvailable(loc) && (PortalSecurity.IsInRoles(this.PortalSettings.AdministratorRoleName) || loc.IsPublished || PortalSecurity.IsInRoles(defaultRoles)))) { locales.Add(loc.Code, loc); foreach (var cultureItem in cultureListItems) { if (cultureItem.Value == loc.Code) { this.selectCulture.Items.Add(cultureItem); } } } } if (this.ShowLinks) { if (locales.Count > 1) { this.rptLanguages.DataSource = locales.Values; this.rptLanguages.DataBind(); } else { this.rptLanguages.Visible = false; } } if (this.ShowMenu) { if (!string.IsNullOrEmpty(this.CssClass)) { this.selectCulture.CssClass = this.CssClass; } if (!this.IsPostBack) { // select the default item if (this.CurrentCulture != null) { ListItem item = this.selectCulture.Items.FindByValue(this.CurrentCulture); if (item != null) { this.selectCulture.SelectedIndex = -1; item.Selected = true; } } } // only show language selector if more than one language if (this.selectCulture.Items.Count <= 1) { this.selectCulture.Visible = false; } } else { this.selectCulture.Visible = false; } this.handleCommonTemplates(); } catch (Exception ex) { Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); } }
public virtual bool CanEditModuleContent(ModuleInfo objModule) { return(PortalSecurity.IsInRoles(objModule.ModulePermissions.ToString(ContentModulePermissionCode))); }
protected void Page_Load(object sender, EventArgs e) { try { //link for the Chat Archives //hlArchive.NavigateUrl = EditUrl("Archive",); StartMessage = Settings.Contains("StartMessage") ? Settings["StartMessage"].ToString() : Localization.GetString("DefaultStartMessage", LocalResourceFile); DefaultAvatarUrl = Settings.Contains("DefaultAvatarUrl") ? Settings["DefaultAvatarUrl"].ToString() : Localization.GetString("DefaultAvatarUrl", LocalResourceFile); var directRoom = string.Empty; var qs = Request.QueryString["rmid"]; if (qs != null) { directRoom = qs.ToString(); } if (Settings.Contains("DefaultRoomId") && directRoom == string.Empty) { DefaultRoomId = Settings["DefaultRoomId"].ToString(); } else if (directRoom != string.Empty) { //if a guid came in, let's put the user in that room. DefaultRoomId = directRoom; } else { //if we don't have a setting. go get the default room from the database. var rc = new RoomController(); var r = rc.GetRoom("Lobby"); if (r == null || (r.ModuleId > 0 && r.ModuleId != ModuleId)) { //todo: if there isn't a room we need display a message about creating one } else { //if the default room doesn't have a moduleid on it, set the module id if (r.ModuleId < 0) { r.ModuleId = ModuleId; } rc.UpdateRoom(r); } if (r != null) { DefaultRoomId = r.RoomId.ToString(); } } //encrypt the user's roles so we can ensure security var curRoles = UserInfo.Roles; var section = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey"); var pc = new PortalSecurity(); foreach (var c in curRoles) { EncryptedRoles += pc.Encrypt(section.ValidationKey, c) + ","; } if (UserInfo.IsSuperUser) { EncryptedRoles += pc.Encrypt(section.ValidationKey, "SuperUser"); } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
public virtual bool CanViewModule(ModuleInfo objModule) { return(PortalSecurity.IsInRoles(objModule.ModulePermissions.ToString(ViewModulePermissionCode))); }
protected void OnRolesGridItemDataBound(object sender, GridItemEventArgs e) { var item = e.Item; switch (item.ItemType) { case GridItemType.SelectedItem: case GridItemType.AlternatingItem: case GridItemType.Item: { var gridDataItem = (GridDataItem)item; var editLink = gridDataItem["EditButton"].Controls[0] as HyperLink; if (editLink != null) { var role = (RoleInfo)item.DataItem; editLink.Visible = role.RoleName != PortalSettings.AdministratorRoleName || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)); } var rolesLink = gridDataItem["RolesButton"].Controls[0] as HyperLink; if (rolesLink != null) { var role = (RoleInfo)item.DataItem; rolesLink.Visible = (role.Status == RoleStatus.Approved) && (role.RoleName != PortalSettings.AdministratorRoleName || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))); } } break; } }
public virtual bool CanViewPage(TabInfo objTab) { return(PortalSecurity.IsInRoles(objTab.TabPermissions.ToString(ViewPagePermissionCode))); }
private static UserCreateStatus CreateMemberhipUser(UserInfo user) { var portalSecurity = new PortalSecurity(); string userName = portalSecurity.InputFilter(user.Username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string email = portalSecurity.InputFilter(user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); MembershipCreateStatus status; if (MembershipProviderConfig.RequiresQuestionAndAnswer) { System.Web.Security.Membership.CreateUser(userName, user.Membership.Password, email, user.Membership.PasswordQuestion, user.Membership.PasswordAnswer, true, out status); } else { System.Web.Security.Membership.CreateUser(userName, user.Membership.Password, email, null, null, true, out status); } var createStatus = UserCreateStatus.Success; switch (status) { case MembershipCreateStatus.DuplicateEmail: createStatus = UserCreateStatus.DuplicateEmail; break; case MembershipCreateStatus.DuplicateProviderUserKey: createStatus = UserCreateStatus.DuplicateProviderUserKey; break; case MembershipCreateStatus.DuplicateUserName: createStatus = UserCreateStatus.DuplicateUserName; break; case MembershipCreateStatus.InvalidAnswer: createStatus = UserCreateStatus.InvalidAnswer; break; case MembershipCreateStatus.InvalidEmail: createStatus = UserCreateStatus.InvalidEmail; break; case MembershipCreateStatus.InvalidPassword: createStatus = UserCreateStatus.InvalidPassword; break; case MembershipCreateStatus.InvalidProviderUserKey: createStatus = UserCreateStatus.InvalidProviderUserKey; break; case MembershipCreateStatus.InvalidQuestion: createStatus = UserCreateStatus.InvalidQuestion; break; case MembershipCreateStatus.InvalidUserName: createStatus = UserCreateStatus.InvalidUserName; break; case MembershipCreateStatus.ProviderError: createStatus = UserCreateStatus.ProviderError; break; case MembershipCreateStatus.UserRejected: createStatus = UserCreateStatus.UserRejected; break; } return createStatus; }
public virtual bool HasTabPermission(Security.Permissions.TabPermissionCollection objTabPermissions, string permissionKey) { return(PortalSecurity.IsInRoles(objTabPermissions.ToString(permissionKey))); }
public static XmlDocument UpdateValidationKey(XmlDocument xmlConfig) { XmlNode xmlMachineKey; string strError = string.Empty; xmlMachineKey = xmlConfig.SelectSingleNode("configuration/system.web/machineKey"); if (xmlMachineKey.Attributes["validationKey"].Value == "F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902") { PortalSecurity objSecurity = new PortalSecurity(); string validationKey = objSecurity.CreateKey(20); XmlUtils.UpdateAttribute(xmlMachineKey, "validationKey", validationKey); } return xmlConfig; }
public override void DataBind() { // Get the report for this module if (!this.ValidateDataSource() || !this.ValidateResults()) { this.litContent.Visible = false; } else { this.litContent.Visible = true; // Get the extension objects IEnumerable <ExtensionObjectInfo> extensionObjects = ReportsController.GetXsltExtensionObjects(this.TabModuleId); var argList = new XsltArgumentList(); foreach (var extensionObject in extensionObjects) { object obj = this.CreateExtensionObject(extensionObject.ClrType); if (obj != null) { argList.AddExtensionObject(extensionObject.XmlNamespace, obj); } } // Get the Xslt Url var sXsl = SettingsUtil.GetDictionarySetting(this.Report.VisualizerSettings, ReportsController.SETTING_Xslt_TransformFile, string.Empty); if (string.IsNullOrEmpty(sXsl)) { return; } if (sXsl.ToLower().StartsWith("fileid=")) { sXsl = Utilities.MapFileIdPath(this.ParentModule.PortalSettings, sXsl); } else { sXsl = Path.Combine(this.ParentModule.PortalSettings.HomeDirectoryMapPath, sXsl.Replace("/", "\\")); } if (string.IsNullOrEmpty(sXsl)) { return; } // Serialize the results to Xml var sbSource = new StringBuilder(); using (var srcWriter = new StringWriter(sbSource)) { this.ReportResults.WriteXml(srcWriter); } // Load the Transform and transform the Xml var sbDest = new StringBuilder(); var xform = new XslCompiledTransform(); using (var destWriter = new XmlTextWriter(new StringWriter(sbDest))) { xform.Load(sXsl); xform.Transform(new XPathDocument(new StringReader(sbSource.ToString())), argList, destWriter); } var objSec = new PortalSecurity(); this.litContent.Text = objSec.InputFilter(sbDest.ToString(), PortalSecurity.FilterFlag.NoScripting); } base.DataBind(); }
private UserControl LoadSkin(string SkinPath) { UserControl ctlSkin = null; try { if (SkinPath.ToLower().IndexOf(Globals.ApplicationPath.ToLower()) != -1) { SkinPath = SkinPath.Remove(0, Globals.ApplicationPath.Length); } ctlSkin = (UserControl)LoadControl("~" + SkinPath); // call databind so that any server logic in the skin is executed ctlSkin.DataBind(); } catch (Exception exc) { if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName) || PortalSecurity.IsInRoles(PortalSettings.ActiveTab.AdministratorRoles.ToString())) { // only display the error to administrators SkinError.Text += "<div style=\"text-align:center\">Could Not Load Skin: " + SkinPath + " Error: " + Server.HtmlEncode(exc.Message) + "</div><br>"; SkinError.Visible = true; } } return(ctlSkin); }
protected void OnVersionsGridItemDataBound(object sender, GridItemEventArgs e) { if ((e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.SelectedItem)) { var item = e.Item as GridDataItem; var htmlContent = item.DataItem as HtmlTextInfo; var createdBy = "Default"; if ((htmlContent.CreatedByUserID != -1)) { var createdByByUser = UserController.GetUserById(PortalId, htmlContent.CreatedByUserID); if (createdByByUser != null) { createdBy = createdByByUser.DisplayName; } } foreach (TableCell cell in item.Cells) { foreach (Control cellControl in cell.Controls) { if (cellControl is ImageButton) { var imageButton = cellControl as ImageButton; imageButton.CommandArgument = htmlContent.ItemID.ToString(); switch (imageButton.CommandName.ToLower()) { case "rollback": //hide rollback for the first item if (dgVersions.CurrentPageIndex == 0) { if ((item.ItemIndex == 0)) { imageButton.Visible = false; break; } } imageButton.Visible = true; break; case "remove": var msg = GetLocalizedString("DeleteVersion.Confirm"); msg = msg.Replace("[VERSION]", htmlContent.Version.ToString()).Replace("[STATE]", htmlContent.StateName).Replace("[DATECREATED]", htmlContent.CreatedOnDate.ToString()) .Replace("[USERNAME]", createdBy); imageButton.OnClientClick = "return confirm(\"" + msg + "\");"; //hide the delete button var showDelete = UserInfo.IsSuperUser || PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); if (!showDelete) { showDelete = htmlContent.IsPublished == false; } imageButton.Visible = showDelete; break; } } } } } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { BindCountry(); BindState(); // Edit check if (EditMode) // Someone requested edit this record { //True is use is editing himself, false if is edited by an admin selfEdit = (userName == PortalSettings.CurrentUser.Identity.Email); // Removed by Mario Endara <*****@*****.**> (2004/11/04) // if (PortalSecurity.IsInRoles("Admins") || selfEdit) if (PortalSecurity.HasEditPermissions(ModuleID) || PortalSecurity.HasAddPermissions(ModuleID) || selfEdit) { //We can edit // Hide RequiredPassword.Visible = false; RequiredConfirm.Visible = false; EditPasswordRow.Visible = true; SaveChangesBtn.Visible = true; RegisterBtn.Visible = false; // Obtain a single row of event information UsersDB accountSystem = new UsersDB(); RainbowUser memberUser = accountSystem.GetSingleUser(userName); try { originalUserID = memberUser.ProviderUserKey; NameField.Text = memberUser.Name; EmailField.Text = memberUser.Email; CompanyField.Text = memberUser.Company; AddressField.Text = memberUser.Address; ZipField.Text = memberUser.Zip; CityField.Text = memberUser.City; CountryField.ClearSelection(); if (CountryField.Items.FindByValue(memberUser.CountryID) != null) { CountryField.Items.FindByValue(memberUser.CountryID).Selected = true; } BindState(); StateField.ClearSelection(); if (StateField.Items.Count > 0 && StateField.Items.FindByValue(memberUser.StateID.ToString()) != null) { StateField.Items.FindByValue(memberUser.StateID.ToString()).Selected = true; } FaxField.Text = memberUser.Fax; PhoneField.Text = memberUser.Phone; SendNewsletter.Checked = memberUser.SendNewsletter; //stores original password for later check // originalPassword = memberUser.GetPassword(); NOT STILL SUPPORTED } catch (System.ArgumentNullException error) { // no existe el usuario; } } else { //We do not have rights to do it! PortalSecurity.AccessDeniedEdit(); } } else { BindState(); //No edit RequiredPassword.Visible = true; RequiredConfirm.Visible = true; EditPasswordRow.Visible = false; SaveChangesBtn.Visible = false; RegisterBtn.Visible = true; } string termsOfService = portalSettings.GetTermsOfService; //Verify if we have to show conditions if (termsOfService.Length != 0) { //Shows conditions FieldConditions.Text = termsOfService; ConditionsRow.Visible = true; } else { //Hides conditions ConditionsRow.Visible = false; } } }
/// ----------------------------------------------------------------------------- /// <summary> /// BindData loads the controls from the Database /// </summary> /// <remarks> /// </remarks> /// ----------------------------------------------------------------------------- private void BindData() { //bind all portal roles to dropdownlist if (RoleId == Null.NullInteger) { if (cboRoles.Items.Count == 0) { var roles = RoleController.Instance.GetRoles(PortalId, x => x.Status == RoleStatus.Approved); //Remove access to Admin Role if use is not a member of the role int roleIndex = Null.NullInteger; foreach (RoleInfo tmpRole in roles) { if (tmpRole.RoleName == PortalSettings.AdministratorRoleName) { if (!PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) { roleIndex = roles.IndexOf(tmpRole); } } break; } if (roleIndex > Null.NullInteger) { roles.RemoveAt(roleIndex); } cboRoles.DataSource = roles; cboRoles.DataBind(); } } else { if (!Page.IsPostBack) { if (Role != null) { //cboRoles.Items.Add(new ListItem(Role.RoleName, Role.RoleID.ToString())); cboRoles.AddItem(Role.RoleName, Role.RoleID.ToString()); cboRoles.Items[0].Selected = true; lblTitle.Text = string.Format(Localization.GetString("RoleTitle.Text", LocalResourceFile), Role.RoleName, Role.RoleID); } cboRoles.Visible = false; plRoles.Visible = false; } } //bind all portal users to dropdownlist if (UserId == -1) { //Make sure user has enough permissions if (Role.RoleName == PortalSettings.AdministratorRoleName && !PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NotAuthorized", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); pnlRoles.Visible = false; pnlUserRoles.Visible = false; chkNotify.Visible = false; return; } if (UsersControl == UsersControl.Combo) { if (cboUsers.Items.Count == 0) { foreach (UserInfo objUser in UserController.GetUsers(PortalId)) { //cboUsers.Items.Add(new ListItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString())); cboUsers.AddItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString()); } } txtUsers.Visible = false; cboUsers.Visible = true; cmdValidate.Visible = false; } else { txtUsers.Visible = true; cboUsers.Visible = false; cmdValidate.Visible = true; } } else { if (User != null) { txtUsers.Text = User.UserID.ToString(); lblTitle.Text = string.Format(Localization.GetString("UserTitle.Text", LocalResourceFile), User.Username, User.UserID); } txtUsers.Visible = false; cboUsers.Visible = false; cmdValidate.Visible = false; plUsers.Visible = false; } }
public static List <string> GetCultureListItems() { List <string> Languages = new List <string>(); try { IEnumerable <System.Web.UI.WebControls.ListItem> cultureListItems = DotNetNuke.Services.Localization.Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, CultureInfo.CurrentCulture.ToString(), "", false); PortalSettings ps = PortalController.Instance.GetCurrentSettings() as PortalSettings; foreach (Locale loc in LocaleController.Instance.GetLocales(ps.PortalId).Values) { string defaultRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", loc.Code), ps.PortalId, "Administrators"); if (!ps.ContentLocalizationEnabled || (LocaleIsAvailable(loc) && (PortalSecurity.IsInRoles(ps.AdministratorRoleName) || loc.IsPublished || PortalSecurity.IsInRoles(defaultRoles)))) { foreach (System.Web.UI.WebControls.ListItem cultureItem in cultureListItems) { if (cultureItem.Value == loc.Code) { Languages.Add(loc.Code); } } } } } catch { } return(Languages); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { cancelHyperLink.NavigateUrl = ReturnURL; if (_moduleId != -1) { ctlAudit.Entity = Module; } if (Page.IsPostBack == false) { ctlIcon.FileFilter = Globals.glbImageFileTypes; dgPermissions.TabId = PortalSettings.ActiveTab.TabID; dgPermissions.ModuleID = _moduleId; cboTab.DataSource = TabController.GetPortalTabs(PortalId, -1, false, Null.NullString, true, false, true, false, true); cboTab.DataBind(); //if tab is a host tab, then add current tab if (Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) { cboTab.InsertItem(0, PortalSettings.ActiveTab.LocalizedTabName, PortalSettings.ActiveTab.TabID.ToString()); } if (Module != null) { if (cboTab.FindItemByValue(Module.TabID.ToString()) == null) { var objTab = TabController.Instance.GetTab(Module.TabID, Module.PortalID, false); cboTab.AddItem(objTab.LocalizedTabName, objTab.TabID.ToString()); } } //only Portal Administrators can manage the visibility on all Tabs var isAdmin = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); rowAllTabs.Visible = isAdmin; chkAllModules.Enabled = isAdmin; if (HideCancelButton) { cancelHyperLink.Visible = false; } //tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { chkNewTabs.Enabled = false; chkDefault.Enabled = false; chkAllowIndex.Enabled = false; cboTab.Enabled = false; } if (_moduleId != -1) { BindData(); cmdDelete.Visible = (ModulePermissionController.CanDeleteModule(Module) || TabPermissionController.CanAddContentToPage()) && !HideDeleteButton; } else { isShareableCheckBox.Checked = true; isShareableViewOnlyCheckBox.Checked = true; isShareableRow.Visible = true; cboVisibility.SelectedIndex = 0; //maximized chkAllTabs.Checked = false; cmdDelete.Visible = false; } if (Module != null) { cmdUpdate.Visible = ModulePermissionController.HasModulePermission(Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); permissionsRow.Visible = ModulePermissionController.CanAdminModule(Module) || TabPermissionController.CanAddContentToPage(); } //Set visibility of Specific Settings if (SettingsControl == null == false) { //Get the module settings from the PortalSettings and pass the //two settings hashtables to the sub control to process SettingsControl.LoadSettings(); specificSettingsTab.Visible = true; fsSpecific.Visible = true; } else { specificSettingsTab.Visible = false; fsSpecific.Visible = false; } if (Module != null) { termsSelector.PortalId = Module.PortalID; termsSelector.Terms = Module.Terms; } termsSelector.DataBind(); } if (Module != null) { cultureLanguageLabel.Language = Module.CultureCode; } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } }
private bool VerifyUserPermissions() { if (IsHostMenu && !UserInfo.IsSuperUser) { AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); DisableForm(); return(false); } //Check if User is a member of the Current Portal (or a member of the MasterPortal if PortalGroups enabled) if (User.PortalID != Null.NullInteger && User.PortalID != PortalId) { AddModuleMessage("InvalidUser", ModuleMessage.ModuleMessageType.YellowWarning, true); DisableForm(); return(false); } //Check if User is a SuperUser and that the current User is a SuperUser if (User.IsSuperUser && !UserInfo.IsSuperUser) { AddModuleMessage("NoUser", ModuleMessage.ModuleMessageType.YellowWarning, true); DisableForm(); return(false); } if (IsEdit) { //Check if user has admin rights if (!IsAdmin || (User.IsInRole(PortalSettings.AdministratorRoleName) && !PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))) { AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); DisableForm(); return(false); } } else { if (!IsUser) { if (Request.IsAuthenticated) { if (!PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)) { //Display current user's profile Response.Redirect(Globals.NavigateURL(PortalSettings.UserTabId, "", "UserID=" + UserInfo.UserID), true); } } else { if ((User.UserID > Null.NullInteger)) { AddModuleMessage("NotAuthorized", ModuleMessage.ModuleMessageType.YellowWarning, true); DisableForm(); return(false); } } } } return(true); }
protected void OnUpdateClick(object sender, EventArgs e) { try { if (Page.IsValid) { var allTabsChanged = false; //TODO: REMOVE IF UNUSED //var allowIndexChanged = false; //only Portal Administrators can manage the visibility on all Tabs var isAdmin = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); chkAllModules.Enabled = isAdmin; //tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { chkAllTabs.Enabled = false; chkNewTabs.Enabled = false; chkDefault.Enabled = false; chkAllowIndex.Enabled = false; cboTab.Enabled = false; } Module.ModuleID = _moduleId; Module.ModuleTitle = txtTitle.Text; Module.Alignment = cboAlign.SelectedItem.Value; Module.Color = txtColor.Text; Module.Border = txtBorder.Text; Module.IconFile = ctlIcon.Url; Module.CacheTime = !String.IsNullOrEmpty(txtCacheDuration.Text) ? Int32.Parse(txtCacheDuration.Text) : 0; Module.CacheMethod = cboCacheProvider.SelectedValue; Module.TabID = TabId; if (Module.AllTabs != chkAllTabs.Checked) { allTabsChanged = true; } Module.AllTabs = chkAllTabs.Checked; // collect these first as any settings update will clear the cache var originalChecked = Settings["hideadminborder"] != null && bool.Parse(Settings["hideadminborder"].ToString()); var allowIndex = Settings.ContainsKey("AllowIndex") && Convert.ToBoolean(Settings["AllowIndex"]); var oldMoniker = ((string)Settings["Moniker"] ?? "").TrimToLength(100); var newMoniker = txtMoniker.Text.TrimToLength(100); if (!oldMoniker.Equals(txtMoniker.Text)) { var ids = TabModulesController.Instance.GetTabModuleIdsBySetting("Moniker", newMoniker); if (ids != null && ids.Count > 0) { //Warn user - duplicate moniker value Skin.AddModuleMessage(this, Localization.GetString("MonikerExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "Moniker", newMoniker); } if (originalChecked != chkAdminBorder.Checked) { ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "hideadminborder", chkAdminBorder.Checked.ToString()); } //check whether allow index value is changed if (allowIndex != chkAllowIndex.Checked) { ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "AllowIndex", chkAllowIndex.Checked.ToString()); } switch (Int32.Parse(cboVisibility.SelectedItem.Value)) { case 0: Module.Visibility = VisibilityState.Maximized; break; case 1: Module.Visibility = VisibilityState.Minimized; break; //case 2: default: Module.Visibility = VisibilityState.None; break; } Module.IsDeleted = false; Module.Header = txtHeader.Text; Module.Footer = txtFooter.Text; Module.StartDate = startDatePicker.SelectedDate != null ? startDatePicker.SelectedDate.Value : Null.NullDate; Module.EndDate = endDatePicker.SelectedDate != null ? endDatePicker.SelectedDate.Value : Null.NullDate; Module.ContainerSrc = moduleContainerCombo.SelectedValue; Module.ModulePermissions.Clear(); Module.ModulePermissions.AddRange(dgPermissions.Permissions); Module.Terms.Clear(); Module.Terms.AddRange(termsSelector.Terms); if (!Module.IsShared) { Module.InheritViewPermissions = chkInheritPermissions.Checked; Module.IsShareable = isShareableCheckBox.Checked; Module.IsShareableViewOnly = isShareableViewOnlyCheckBox.Checked; } Module.DisplayTitle = chkDisplayTitle.Checked; Module.DisplayPrint = chkDisplayPrint.Checked; Module.DisplaySyndicate = chkDisplaySyndicate.Checked; Module.IsWebSlice = chkWebSlice.Checked; Module.WebSliceTitle = txtWebSliceTitle.Text; Module.WebSliceExpiryDate = diWebSliceExpiry.SelectedDate != null ? diWebSliceExpiry.SelectedDate.Value : Null.NullDate; if (!string.IsNullOrEmpty(txtWebSliceTTL.Text)) { Module.WebSliceTTL = Convert.ToInt32(txtWebSliceTTL.Text); } Module.IsDefaultModule = chkDefault.Checked; Module.AllModules = chkAllModules.Checked; ModuleController.Instance.UpdateModule(Module); //Update Custom Settings if (SettingsControl != null) { try { SettingsControl.UpdateSettings(); } catch (ThreadAbortException exc) { Logger.Debug(exc); Thread.ResetAbort(); //necessary } catch (Exception ex) { Exceptions.LogException(ex); } } //These Module Copy/Move statements must be //at the end of the Update as the Controller code assumes all the //Updates to the Module have been carried out. //Check if the Module is to be Moved to a new Tab if (!chkAllTabs.Checked) { var newTabId = Int32.Parse(cboTab.SelectedValue); if (TabId != newTabId) { //First check if there already is an instance of the module on the target page var tmpModule = ModuleController.Instance.GetModule(_moduleId, newTabId, false); if (tmpModule == null) { //Move module ModuleController.Instance.MoveModule(_moduleId, TabId, newTabId, Globals.glbDefaultPane); } else { //Warn user Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } } } //Check if Module is to be Added/Removed from all Tabs if (allTabsChanged) { var listTabs = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, false, true); if (chkAllTabs.Checked) { if (!chkNewTabs.Checked) { foreach (var destinationTab in listTabs) { var module = ModuleController.Instance.GetModule(_moduleId, destinationTab.TabID, false); if (module != null) { if (module.IsDeleted) { ModuleController.Instance.RestoreModule(module); } } else { if (!PortalSettings.ContentLocalizationEnabled || (Module.CultureCode == destinationTab.CultureCode)) { ModuleController.Instance.CopyModule(Module, destinationTab, Module.PaneName, true); } } } } } else { ModuleController.Instance.DeleteAllModules(_moduleId, TabId, listTabs, true, false, false); } } if (!DoNotRedirectOnUpdate) { //Navigate back to admin page Response.Redirect(ReturnURL, true); } } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } }
private void GrdUsersOnItemDataBound(object sender, GridItemEventArgs e) { var item = e.Item; if (item.ItemType == GridItemType.Item || item.ItemType == GridItemType.AlternatingItem || item.ItemType == GridItemType.SelectedItem) { var imgApprovedDeleted = item.FindControl("imgApprovedDeleted"); var imgNotApprovedDeleted = item.FindControl("imgNotApprovedDeleted"); var imgApproved = item.FindControl("imgApproved"); var imgNotApproved = item.FindControl("imgNotApproved"); var user = (UserInfo)item.DataItem; if (user == null) { return; } if (user.IsDeleted) { foreach (WebControl control in item.Controls) { control.Attributes.Remove("class"); control.Attributes.Add("class", "NormalDeleted"); } if (imgApprovedDeleted != null && user.Membership.Approved) { imgApprovedDeleted.Visible = true; } else if (imgNotApprovedDeleted != null && !user.Membership.Approved) { imgNotApprovedDeleted.Visible = true; } } else { if (imgApproved != null && user.Membership.Approved) { imgApproved.Visible = true; } else if (imgNotApproved != null && !user.Membership.Approved) { imgNotApproved.Visible = true; } } var gridDataItem = (GridDataItem)item; var editLink = gridDataItem["EditButton"].Controls[0] as HyperLink; if (editLink != null) { editLink.Visible = (!user.IsInRole(PortalSettings.AdministratorRoleName) || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))); if (editLink.Visible) { if (user.IsSuperUser) { editLink.Visible = PortalSettings.UserInfo.IsSuperUser; } } } var delete = (DnnImageButton)item.FindControl("Delete"); delete.Visible = IsCommandAllowed(user, "Delete"); delete.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture); delete.ToolTip = Localization.GetString("Delete.Text", LocalResourceFile); var restore = (DnnImageButton)item.FindControl("Restore"); restore.Visible = IsCommandAllowed(user, "Restore"); restore.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture); restore.ToolTip = Localization.GetString("Restore.Text", LocalResourceFile); var remove = (DnnImageButton)item.FindControl("Remove"); remove.Visible = IsCommandAllowed(user, "Remove"); remove.CommandArgument = user.UserID.ToString(CultureInfo.InvariantCulture); remove.ToolTip = Localization.GetString("Remove.Text", LocalResourceFile); var rolesColumn = gridDataItem["RolesButton"].Controls[0]; rolesColumn.Visible = !user.IsSuperUser && (!user.IsInRole(PortalSettings.AdministratorRoleName) || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))); var onlineControl = (DnnImage)item.FindControl("imgOnline"); if (onlineControl != null) { onlineControl.Visible = user.Membership.IsOnLine; onlineControl.ToolTip = Localization.GetString("Online.Text", LocalResourceFile); } } }
private bool Validate() { CreateStatus = UserCreateStatus.AddUser; var portalSecurity = new PortalSecurity(); //Check User Editor bool _IsValid = userForm.IsValid; if (RegistrationFormType == 0) { //Update UserName if (UseEmailAsUserName) { User.Username = User.Email; if (String.IsNullOrEmpty(User.DisplayName)) { User.DisplayName = User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)); } } //Check Password is valid if (!RandomPassword) { //Check Password is Valid if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(User.Membership.Password)) { CreateStatus = UserCreateStatus.InvalidPassword; } if (RequirePasswordConfirm && String.IsNullOrEmpty(AuthenticationType)) { if (User.Membership.Password != User.Membership.PasswordConfirm) { CreateStatus = UserCreateStatus.PasswordMismatch; } } } else { //Generate a random password for the user User.Membership.Password = UserController.GeneratePassword(); User.Membership.PasswordConfirm = User.Membership.Password; } } else { //Set Username to Email if (String.IsNullOrEmpty(User.Username)) { User.Username = User.Email; } //Set DisplayName if (String.IsNullOrEmpty(User.DisplayName)) { User.DisplayName = String.IsNullOrEmpty(User.FirstName + " " + User.LastName) ? User.Email.Substring(0, User.Email.IndexOf("@", StringComparison.Ordinal)) : User.FirstName + " " + User.LastName; } //Random Password if (String.IsNullOrEmpty(User.Membership.Password)) { //Generate a random password for the user User.Membership.Password = UserController.GeneratePassword(); } //Password Confirm if (!String.IsNullOrEmpty(User.Membership.PasswordConfirm)) { if (User.Membership.Password != User.Membership.PasswordConfirm) { CreateStatus = UserCreateStatus.PasswordMismatch; } } } ////Validate Exclude Terms //if (!String.IsNullOrEmpty(ExcludeTerms)) //{ // string[] excludeTerms = ExcludeTerms.Split(','); // foreach (string term in excludeTerms) // { // var trimmedTerm = term.Trim().ToLowerInvariant(); // if (User.Username.ToLowerInvariant().Contains(trimmedTerm)) // { // CreateStatus = UserCreateStatus.InvalidUserName; // } // if (User.DisplayName.ToLowerInvariant().Contains(trimmedTerm)) // { // CreateStatus = UserCreateStatus.InvalidDisplayName; // } // } //} //Validate Profanity if (UseProfanityFilter) { if (!portalSecurity.ValidateInput(User.Username, PortalSecurity.FilterFlag.NoProfanity)) { CreateStatus = UserCreateStatus.InvalidUserName; } if (!String.IsNullOrEmpty(User.DisplayName)) { if (!portalSecurity.ValidateInput(User.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) { CreateStatus = UserCreateStatus.InvalidDisplayName; } } } //Validate Unique User Name UserInfo user = UserController.GetUserByName(PortalId, User.Username); if (user != null) { if (UseEmailAsUserName) { CreateStatus = UserCreateStatus.DuplicateEmail; } else { CreateStatus = UserCreateStatus.DuplicateUserName; int i = 1; string userName = null; while (user != null) { userName = User.Username + "0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.GetUserByName(PortalId, userName); i++; } User.Username = userName; } } //Validate Unique Display Name if (CreateStatus == UserCreateStatus.AddUser && RequireUniqueDisplayName) { user = TestableUserController.Instance.GetUserByDisplayname(PortalId, User.DisplayName); if (user != null) { CreateStatus = UserCreateStatus.DuplicateDisplayName; int i = 1; string displayName = null; while (user != null) { displayName = User.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); user = TestableUserController.Instance.GetUserByDisplayname(PortalId, displayName); i++; } User.DisplayName = displayName; } } //Check Question/Answer if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) { if (string.IsNullOrEmpty(User.Membership.PasswordQuestion)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidQuestion; } if (CreateStatus == UserCreateStatus.AddUser) { if (string.IsNullOrEmpty(User.Membership.PasswordAnswer)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidAnswer; } } } if (CreateStatus != UserCreateStatus.AddUser) { _IsValid = false; } return(_IsValid); }
/// <summary> /// The BindData helper method is used to populate a asp:datalist /// server control with the current "edit access" permissions /// set within the portal configuration system /// </summary> private void BindData() { var useNTLM = HttpContext.Current.User is WindowsPrincipal; // add by Jonathan Fong 22/07/2004 to support LDAP // jes1111 - useNTLM |= ConfigurationSettings.AppSettings["LDAPLogin"] != null ? true : false; useNTLM |= Config.LDAPLogin.Length != 0 ? true : false; this.authAddRoles.Visible = this.authApproveRoles.Visible = this.authDeleteRoles.Visible = this.authEditRoles.Visible = this.authPropertiesRoles.Visible = this.authPublishingRoles.Visible = this.authMoveModuleRoles.Visible = this.authDeleteModuleRoles.Visible = this.authViewRoles.Visible = !useNTLM; var m = this.GetModule(); if (m != null) { this.moduleType.Text = GiveMeFriendlyName(m.GuidID); // Update Textbox Settings this.moduleTitle.Text = m.ModuleTitle; this.cacheTime.Text = m.CacheTime.ToString(); this.portalTabs = new PagesDB().GetPagesFlat(this.PortalSettings.PortalID); this.tabDropDownList.DataBind(); this.tabDropDownList.ClearSelection(); if (this.tabDropDownList.Items.FindByValue(m.PageID.ToString()) != null) { this.tabDropDownList.Items.FindByValue(m.PageID.ToString()).Selected = true; } // Change by [email protected] // Date: 19/5/2003 this.showEveryWhere.Checked = m.ShowEveryWhere; // is the window mgmt support enabled // jes1111 - allowCollapsable.Enabled = GlobalResources.SupportWindowMgmt; this.allowCollapsable.Enabled = Config.WindowMgmtControls; this.allowCollapsable.Checked = m.SupportCollapsable; this.ShowMobile.Checked = m.ShowMobile; // Change by [email protected] // Date: 6/2/2003 PortalModuleControl pm = null; var controlPath = Path.WebPathCombine(Path.ApplicationRoot, m.DesktopSrc); try { if (!controlPath.Contains("Area")) { pm = (PortalModuleControl)this.LoadControl(controlPath); if (pm.InnerSupportsWorkflow) { this.enableWorkflowSupport.Checked = m.SupportWorkflow; this.authApproveRoles.Enabled = m.SupportWorkflow; this.authPublishingRoles.Enabled = m.SupportWorkflow; this.PopulateRoles(ref this.authPublishingRoles, m.AuthorizedPublishingRoles); this.PopulateRoles(ref this.authApproveRoles, m.AuthorizedApproveRoles); } else { this.enableWorkflowSupport.Enabled = false; this.authApproveRoles.Enabled = false; this.authPublishingRoles.Enabled = false; } } } catch (Exception ex) { // ErrorHandler.HandleException("There was a problem loading: '" + controlPath + "'", ex); // throw; throw new AppleseedException( LogLevel.Error, "There was a problem loading: '" + controlPath + "'", ex); } // End Change [email protected] // Populate checkbox list with all security roles for this portal // and "check" the ones already configured for this module this.PopulateRoles(ref this.authEditRoles, m.AuthorizedEditRoles); this.PopulateRoles(ref this.authViewRoles, m.AuthorizedViewRoles); this.PopulateRoles(ref this.authAddRoles, m.AuthorizedAddRoles); this.PopulateRoles(ref this.authDeleteRoles, m.AuthorizedDeleteRoles); this.PopulateRoles(ref this.authMoveModuleRoles, m.AuthorizedMoveModuleRoles); this.PopulateRoles(ref this.authDeleteModuleRoles, m.AuthorizedDeleteModuleRoles); this.PopulateRoles(ref this.authPropertiesRoles, m.AuthorizedPropertiesRoles); // Jes1111 if (pm != null) { if (!pm.Cacheable) { this.cacheTime.Text = "-1"; this.cacheTime.Enabled = false; } } } else { // Denied access if Module not in Tab. [email protected] (2004/07/23) PortalSecurity.AccessDenied(); } }
/// ----------------------------------------------------------------------------- /// <summary> /// HasWorkflowStatePermission checks whether the current user has a specific WorkflowState Permission /// </summary> /// <param name = "objWorkflowStatePermissions">The Permissions for the WorkflowState</param> /// <param name = "permissionKey">The Permission to check</param> /// <history> /// </history> /// ----------------------------------------------------------------------------- public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection objWorkflowStatePermissions, string permissionKey) { return(PortalSecurity.IsInRoles(objWorkflowStatePermissions.ToString(permissionKey))); }
internal virtual string InputFilter(string input) { var ps = new PortalSecurity(); return(ps.InputFilter(input, PortalSecurity.FilterFlag.NoProfanity)); }
/// <summary> /// Page_Load runs when the control is loaded. /// </summary> /// <history> /// [cnurse] 10/06/2004 Updated to reflect design changes for Help, 508 support /// and localisation /// </history> protected void Page_Load(object sender, EventArgs e) { try { if (!Page.IsPostBack) { // localization lblPageFunctions.Text = Localization.GetString("PageFunctions", this.LocalResourceFile); optModuleType.Items.FindByValue("0").Selected = true; lblCommonTasks.Text = Localization.GetString("CommonTasks", this.LocalResourceFile); imgAddTabIcon.AlternateText = Localization.GetString("AddTab.AlternateText", this.LocalResourceFile); cmdAddTab.Text = Localization.GetString("AddTab", this.LocalResourceFile); imgEditTabIcon.AlternateText = Localization.GetString("EditTab.AlternateText", this.LocalResourceFile); cmdEditTab.Text = Localization.GetString("EditTab", this.LocalResourceFile); imgDeleteTabIcon.AlternateText = Localization.GetString("DeleteTab.AlternateText", this.LocalResourceFile); cmdDeleteTab.Text = Localization.GetString("DeleteTab", this.LocalResourceFile); imgCopyTabIcon.AlternateText = Localization.GetString("CopyTab.AlternateText", this.LocalResourceFile); cmdCopyTab.Text = Localization.GetString("CopyTab", this.LocalResourceFile); imgPreviewTabIcon.AlternateText = Localization.GetString("PreviewTab.AlternateText", this.LocalResourceFile); cmdPreviewTab.Text = Localization.GetString("PreviewTab", this.LocalResourceFile); if (IsPreview) { imgPreviewTabIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_unpreviewtab.gif"; } lblModule.Text = Localization.GetString("Module", this.LocalResourceFile); lblPane.Text = Localization.GetString("Pane", this.LocalResourceFile); lblTitle.Text = Localization.GetString("Title", this.LocalResourceFile); lblAlign.Text = Localization.GetString("Align", this.LocalResourceFile); imgAddModuleIcon.AlternateText = Localization.GetString("AddModule.AlternateText", this.LocalResourceFile); cmdAddModule.Text = Localization.GetString("AddModule", this.LocalResourceFile); cmdInstallFeatures.Text = Localization.GetString("InstallFeatures", this.LocalResourceFile); imgRolesIcon.AlternateText = Localization.GetString("Roles.AlternateText", this.LocalResourceFile); cmdRoles.Text = Localization.GetString("Roles", this.LocalResourceFile); imgSiteIcon.AlternateText = Localization.GetString("Site.AlternateText", this.LocalResourceFile); cmdSite.Text = Localization.GetString("Site", this.LocalResourceFile); imgUsersIcon.AlternateText = Localization.GetString("Users.AlternateText", this.LocalResourceFile); cmdUsers.Text = Localization.GetString("Users", this.LocalResourceFile); imgFilesIcon.AlternateText = Localization.GetString("Files.AlternateText", this.LocalResourceFile); cmdFiles.Text = Localization.GetString("Files", this.LocalResourceFile); imgSearchIndexIcon.AlternateText = Localization.GetString("SearchIndex.AlternateText", this.LocalResourceFile); cmdSearchIndex.Text = Localization.GetString("SearchIndex", this.LocalResourceFile); if (PortalSettings.ActiveTab.IsAdminTab) { imgEditTabIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_edittab_bw.gif"; cmdEditTab.Enabled = false; cmdEditTabIcon.Enabled = false; imgDeleteTabIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_deletetab_bw.gif"; cmdDeleteTab.Enabled = false; cmdDeleteTabIcon.Enabled = false; imgCopyTabIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_copytab_bw.gif"; cmdCopyTab.Enabled = false; cmdCopyTabIcon.Enabled = false; } else { ClientAPI.AddButtonConfirm(cmdDeleteTab, Localization.GetString("DeleteTabConfirm", this.LocalResourceFile)); ClientAPI.AddButtonConfirm(cmdDeleteTabIcon, Localization.GetString("DeleteTabConfirm", this.LocalResourceFile)); } if (Globals.IsAdminControl()) { cmdAddModule.Enabled = false; imgAddModuleIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_addmodule_bw.gif"; cmdAddModuleIcon.Enabled = false; } if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) == false) { imgSiteIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_site_bw.gif"; cmdSite.Enabled = false; cmdSiteIcon.Enabled = false; imgUsersIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_users_bw.gif"; cmdUsers.Enabled = false; cmdUsersIcon.Enabled = false; imgRolesIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_roles_bw.gif"; cmdRoles.Enabled = false; cmdRolesIcon.Enabled = false; imgFilesIcon.ImageUrl = "~/Admin/ControlPanel/images/iconbar_files_bw.gif"; cmdFiles.Enabled = false; cmdFilesIcon.Enabled = false; } UserInfo objUser = UserController.GetCurrentUserInfo(); if (objUser != null) { if (!objUser.IsSuperUser) { rowInstallModule.Visible = false; } } BindData(); if (PortalSettings.ActiveTab.IsAdminTab == false & Globals.IsAdminControl() == false) { for (int intItem = 0; intItem < PortalSettings.ActiveTab.Panes.Count; intItem++) { cboPanes.Items.Add(Convert.ToString(PortalSettings.ActiveTab.Panes[intItem])); } } else { cboPanes.Items.Add(Globals.glbDefaultPane); } if (cboPanes.Items.FindByValue(Globals.glbDefaultPane) != null) { cboPanes.Items.FindByValue(Globals.glbDefaultPane).Selected = true; } if (cboPermission.Items.Count > 0) { cboPermission.SelectedIndex = 0; // view } if (cboAlign.Items.Count > 0) { cboAlign.SelectedIndex = 0; // left } if (cboPosition.Items.Count > 0) { cboPosition.SelectedIndex = 1; // bottom } } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
/// ----------------------------------------------------------------------------- /// <summary> /// UpdateUser persists a user to the Data Store /// </summary> /// <remarks> /// </remarks> /// <param name="user">The user to persist to the Data Store.</param> /// ----------------------------------------------------------------------------- public override void UpdateUser(UserInfo user) { var objSecurity = new PortalSecurity(); string firstName = objSecurity.InputFilter(user.FirstName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string lastName = objSecurity.InputFilter(user.LastName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string email = objSecurity.InputFilter(user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string displayName = objSecurity.InputFilter(user.DisplayName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); if (displayName.Contains("<")) { displayName = HttpUtility.HtmlEncode(displayName); } bool updatePassword = user.Membership.UpdatePassword; bool isApproved = user.Membership.Approved; if (String.IsNullOrEmpty(displayName)) { displayName = firstName + " " + lastName; } //Persist the Membership to the Data Store UpdateUserMembership(user); //Persist the DNN User to the Database _dataProvider.UpdateUser(user.UserID, user.PortalID, firstName, lastName, user.IsSuperUser, email, displayName, user.VanityUrl, updatePassword, isApproved, false, user.LastIPAddress, user.PasswordResetToken, user.PasswordResetExpiration, user.IsDeleted, UserController.Instance.GetCurrentUserInfo().UserID); //Persist the Profile to the Data Store ProfileController.UpdateUserProfile(user); }
/// ----------------------------------------------------------------------------- /// <summary> /// UpdateUserProfile persists a user's Profile to the Data Store /// </summary> /// <remarks> /// </remarks> /// <param name="user">The user to persist to the Data Store.</param> /// ----------------------------------------------------------------------------- public override void UpdateUserProfile(UserInfo user) { ProfilePropertyDefinitionCollection properties = user.Profile.ProfileProperties; //Ensure old and new TimeZone properties are in synch var newTimeZone = properties["PreferredTimeZone"]; var oldTimeZone = properties["TimeZone"]; if (oldTimeZone != null && newTimeZone != null) { //preference given to new property, if new is changed then old should be updated as well. if (newTimeZone.IsDirty && !string.IsNullOrEmpty(newTimeZone.PropertyValue)) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); if (timeZoneInfo != null) oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); } //however if old is changed, we need to update new as well else if (oldTimeZone.IsDirty) { int oldOffset; int.TryParse(oldTimeZone.PropertyValue, out oldOffset); newTimeZone.PropertyValue = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset).Id; } } foreach (ProfilePropertyDefinition profProperty in properties) { if ((profProperty.PropertyValue != null) && (profProperty.IsDirty)) { var objSecurity = new PortalSecurity(); string propertyValue = objSecurity.InputFilter(profProperty.PropertyValue, PortalSecurity.FilterFlag.NoScripting); _dataProvider.UpdateProfileProperty(Null.NullInteger, user.UserID, profProperty.PropertyDefinitionId, propertyValue, (int) profProperty.ProfileVisibility.VisibilityMode, profProperty.ProfileVisibility.ExtendedVisibilityString(), DateTime.Now); var objEventLog = new EventLogController(); objEventLog.AddLog(user, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", "USERPROFILE_UPDATED"); } } }
private UserCreateStatus CreateDNNUser(ref UserInfo user) { var objSecurity = new PortalSecurity(); string userName = objSecurity.InputFilter(user.Username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string email = objSecurity.InputFilter(user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string lastName = objSecurity.InputFilter(user.LastName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); string firstName = objSecurity.InputFilter(user.FirstName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); var createStatus = UserCreateStatus.Success; string displayName = objSecurity.InputFilter(user.DisplayName, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); if (displayName.Contains("<")) { displayName = HttpUtility.HtmlEncode(displayName); } bool updatePassword = user.Membership.UpdatePassword; bool isApproved = user.Membership.Approved; try { user.UserID = Convert.ToInt32(_dataProvider.AddUser(user.PortalID, userName, firstName, lastName, user.AffiliateID, user.IsSuperUser, email, displayName, updatePassword, isApproved, UserController.Instance.GetCurrentUserInfo().UserID)); } catch (Exception ex) { //Clear User (duplicate User information) Exceptions.LogException(ex); user = null; createStatus = UserCreateStatus.ProviderError; } return createStatus; }
public static string EncryptParameter(string Value, string encryptionKey) { PortalSecurity objSecurity = new PortalSecurity(); string strParameter = objSecurity.Encrypt(encryptionKey, Value); strParameter = strParameter.Replace("/", "_"); strParameter = strParameter.Replace("+", "-"); strParameter = strParameter.Replace("=", "%3d"); return strParameter; }
private static void UpdateUserMembership(UserInfo user) { var portalSecurity = new PortalSecurity(); string email = portalSecurity.InputFilter(user.Email, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); //Persist the Membership Properties to the AspNet Data Store MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); membershipUser.Email = email; membershipUser.LastActivityDate = DateTime.Now; if (user.IsSuperUser) { membershipUser.IsApproved = user.Membership.Approved; } System.Web.Security.Membership.UpdateUser(membershipUser); DataCache.RemoveCache(GetCacheKey(user.Username)); }
/// <summary> /// cmdUpdate_Click runs when the Update LinkButton is clicked. /// It saves the current Site Settings /// </summary> /// <history> /// [cnurse] 10/18/2004 documented /// [cnurse] 10/19/2004 modified to support custm module specific settings /// </history> protected void cmdUpdate_Click(object Sender, EventArgs e) { try { if (Page.IsValid) { ModuleController objModules = new ModuleController(); bool AllTabsChanged = false; // tab administrators can only manage their own tab if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName) == false) { chkAllTabs.Enabled = false; chkDefault.Enabled = false; chkAllModules.Enabled = false; cboTab.Enabled = false; } // update module ModuleInfo objModule = objModules.GetModule(moduleId, TabId, false); objModule.ModuleID = moduleId; objModule.ModuleTitle = txtTitle.Text; objModule.Alignment = cboAlign.SelectedItem.Value; objModule.Color = txtColor.Text; objModule.Border = txtBorder.Text; objModule.IconFile = ctlIcon.Url; if (!String.IsNullOrEmpty(txtCacheTime.Text)) { objModule.CacheTime = int.Parse(txtCacheTime.Text); } else { objModule.CacheTime = 0; } objModule.TabID = TabId; if (objModule.AllTabs != chkAllTabs.Checked) { AllTabsChanged = true; } objModule.AllTabs = chkAllTabs.Checked; switch (int.Parse(cboVisibility.SelectedItem.Value)) { case 0: objModule.Visibility = VisibilityState.Maximized; break; case 1: objModule.Visibility = VisibilityState.Minimized; break; case 2: objModule.Visibility = VisibilityState.None; break; } objModule.IsDeleted = false; objModule.Header = txtHeader.Text; objModule.Footer = txtFooter.Text; if (!String.IsNullOrEmpty(txtStartDate.Text)) { objModule.StartDate = Convert.ToDateTime(txtStartDate.Text); } else { objModule.StartDate = Null.NullDate; } if (!String.IsNullOrEmpty(txtEndDate.Text)) { objModule.EndDate = Convert.ToDateTime(txtEndDate.Text); } else { objModule.EndDate = Null.NullDate; } objModule.ContainerSrc = ctlModuleContainer.SkinSrc; objModule.ModulePermissions = dgPermissions.Permissions; objModule.InheritViewPermissions = chkInheritPermissions.Checked; objModule.DisplayTitle = chkDisplayTitle.Checked; objModule.DisplayPrint = chkDisplayPrint.Checked; objModule.DisplaySyndicate = chkDisplaySyndicate.Checked; objModule.IsDefaultModule = chkDefault.Checked; objModule.AllModules = chkAllModules.Checked; objModules.UpdateModule(objModule); //Update Custom Settings if (ctlSpecific != null) { ctlSpecific.UpdateSettings(); } //These Module Copy/Move statements must be //at the end of the Update as the Controller code assumes all the //Updates to the Module have been carried out. //Check if the Module is to be Moved to a new Tab if (!chkAllTabs.Checked) { int newTabId = int.Parse(cboTab.SelectedItem.Value); if (TabId != newTabId) { objModules.MoveModule(moduleId, TabId, newTabId, ""); } } //'Check if Module is to be Added/Removed from all Tabs if (AllTabsChanged) { ArrayList arrTabs = Globals.GetPortalTabs(PortalSettings.DesktopTabs, false, true); if (chkAllTabs.Checked) { objModules.CopyModule(moduleId, TabId, arrTabs, true); } else { objModules.DeleteAllModules(moduleId, TabId, arrTabs, false, false); } } // Navigate back to admin page Response.Redirect(Globals.NavigateURL(), true); } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
/// ----------------------------------------------------------------------------- /// <summary> /// grdUsers_ItemDataBound runs when a row in the grid is bound /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 01/05/2007 Intial documentation /// </history> /// ----------------------------------------------------------------------------- private void grdUsers_ItemDataBound(object sender, DataGridItemEventArgs e) { var item = e.Item; if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) { var imgApprovedDeleted = item.FindControl("imgApprovedDeleted"); var imgNotApprovedDeleted = item.FindControl("imgNotApprovedDeleted"); var imgApproved = item.FindControl("imgApproved"); var imgNotApproved = item.FindControl("imgNotApproved"); var user = (UserInfo)item.DataItem; if (user != null) { if (user.IsDeleted) { foreach (WebControl control in item.Controls) { control.Attributes.Remove("class"); control.Attributes.Add("class", "NormalDeleted"); } if (imgApprovedDeleted != null && user.Membership.Approved) { imgApprovedDeleted.Visible = true; } else if (imgNotApprovedDeleted != null && !user.Membership.Approved) { imgNotApprovedDeleted.Visible = true; } } else { if (imgApproved != null && user.Membership.Approved) { imgApproved.Visible = true; } else if (imgNotApproved != null && !user.Membership.Approved) { imgNotApproved.Visible = true; } } } var imgColumnControl = item.Controls[0].Controls[0]; if (imgColumnControl is HyperLink) { var editLink = (HyperLink)imgColumnControl; editLink.Visible = (!user.IsInRole(PortalSettings.AdministratorRoleName) || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))); if (editLink.Visible) { if (user.IsSuperUser) { editLink.Visible = PortalSettings.UserInfo.IsSuperUser; } } } imgColumnControl = item.Controls[1].Controls[0]; if (imgColumnControl is ImageButton) { var delImage = (ImageButton)imgColumnControl; delImage.Visible = IsCommandAllowed(user, "Delete"); } imgColumnControl = item.Controls[2].Controls[0]; if (imgColumnControl is HyperLink) { var rolesLink = (HyperLink)imgColumnControl; rolesLink.Visible = !user.IsSuperUser && (!user.IsInRole(PortalSettings.AdministratorRoleName) || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName))); } imgColumnControl = item.Controls[3].FindControl("imgOnline"); if (imgColumnControl is Image) { var userOnlineImage = (System.Web.UI.WebControls.Image)imgColumnControl; userOnlineImage.Visible = user.Membership.IsOnLine; } imgColumnControl = item.Controls[3].Controls[0]; if (imgColumnControl is ImageButton) { var restoreImage = (ImageButton)imgColumnControl; restoreImage.Visible = IsCommandAllowed(user, "Restore"); } imgColumnControl = item.Controls[4].Controls[0]; if (imgColumnControl is ImageButton) { ImageButton removeImage = (ImageButton)imgColumnControl; removeImage.Visible = IsCommandAllowed(user, "Remove"); } } }
public static XmlDocument UpdateMachineKey(XmlDocument xmlConfig) { PortalSecurity objSecurity = new PortalSecurity(); string validationKey = objSecurity.CreateKey(20); string decryptionKey = objSecurity.CreateKey(24); XmlNode xmlMachineKey = xmlConfig.SelectSingleNode("configuration/system.web/machineKey"); XmlUtils.UpdateAttribute(xmlMachineKey, "validationKey", validationKey); XmlUtils.UpdateAttribute(xmlMachineKey, "decryptionKey", decryptionKey); xmlConfig = AddAppSetting(xmlConfig, "InstallationDate", System.DateTime.Today.ToShortDateString()); return xmlConfig; }
/// <summary> /// Page_Load runs when the control is loaded /// </summary> /// <history> /// [cnurse] 10/18/2004 documented /// [cnurse] 10/19/2004 modified to support custm module specific settings /// [vmasanas] 11/28/2004 modified to support modules in admin tabs /// </history> protected void Page_Load(Object sender, EventArgs e) { try { // Verify that the current user has access to edit this module if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName) == false && PortalSecurity.IsInRoles(PortalSettings.ActiveTab.AdministratorRoles.ToString()) == false) { Response.Redirect(Globals.NavigateURL("Access Denied"), true); } //this needs to execute always to the client script code is registred in InvokePopupCal cmdStartCalendar.NavigateUrl = Calendar.InvokePopupCal(txtStartDate); cmdEndCalendar.NavigateUrl = Calendar.InvokePopupCal(txtEndDate); if (Page.IsPostBack == false) { ctlIcon.FileFilter = Globals.glbImageFileTypes; dgPermissions.TabId = PortalSettings.ActiveTab.TabID; dgPermissions.ModuleID = moduleId; ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem")); cboTab.DataSource = Globals.GetPortalTabs(PortalSettings.DesktopTabs, -1, false, true, false, false, true); cboTab.DataBind(); //if is and admin or host tab, then add current tab if (PortalSettings.ActiveTab.ParentId == PortalSettings.AdminTabId || PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId) { cboTab.Items.Insert(0, new ListItem(PortalSettings.ActiveTab.TabName, PortalSettings.ActiveTab.TabID.ToString())); } // tab administrators can only manage their own tab if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleName) == false) { chkAllTabs.Enabled = false; chkDefault.Enabled = false; chkAllModules.Enabled = false; cboTab.Enabled = false; } if (moduleId != -1) { BindData(); } else { cboVisibility.SelectedIndex = 0; // maximized chkAllTabs.Checked = false; cmdDelete.Visible = false; } //Set visibility of Specific Settings if (ctlSpecific != null) { //Get the module settings from the PortalSettings and pass the //two settings hashtables to the sub control to process ctlSpecific.LoadSettings(); dshSpecific.Visible = true; tblSpecific.Visible = true; } else { dshSpecific.Visible = false; tblSpecific.Visible = false; } } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
protected virtual void RenderViewMode(System.Web.UI.HtmlTextWriter writer) { string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); PortalSecurity security = new PortalSecurity(); writer.Write(security.InputFilter(propValue, PortalSecurity.FilterFlag.NoScripting)); writer.RenderEndTag(); }