/// <summary> /// Bind data for this control. /// </summary> private void BindData() { // list roles of this board var groups = this.GetRepository <Group>().List(boardId: this.PageContext.PageBoardID); // set repeater data-source this.RoleListYaf.DataSource = groups; // clear cached list of roles this.availableRoles.Clear(); // get all provider roles (from role in AspNetRolesHelper.GetAllRoles() let rows = groups.Select(g => g.Name == role) where groups.Count == 0 select role).ForEach(role1 => this.availableRoles.Add(role1)); // check if there are any roles for syncing if (this.availableRoles.Count > 0 && !Config.IsDotNetNuke) { // make it data-source this.RoleListNet.DataSource = this.availableRoles; } else { // no data-source for provider roles this.RoleListNet.DataSource = null; } // bind data to controls this.DataBind(); }
/// <summary> /// The bind data. /// </summary> private void BindData() { var user = this.GetRepository <User>().GetBoardUser(this.UserId); if (user == null || user.Item1.ID == 0) { // No such user exists or this is an nntp user ("0") BuildLink.AccessDenied(); } // populate user information controls... // Is BuddyList feature enabled? if (this.Get <BoardSettings>().EnableBuddyList) { this.SetupBuddyList(this.UserId, user); } else { // BuddyList feature is disabled. don't show any link. this.lnkBuddy.Visible = false; this.BuddyCard.Visible = false; } var userNameOrDisplayName = this.HtmlEncode( this.Get <BoardSettings>().EnableDisplayName ? user.Item1.DisplayName : user.Item1.Name); this.SetupUserProfileInfo(user); this.AddPageLinks(userNameOrDisplayName); this.SetupUserStatistics(user); this.SetupUserLinks(user, userNameOrDisplayName); this.SetupAvatar(user.Item1); this.Groups.DataSource = AspNetRolesHelper.GetRolesForUser(user.Item2); this.ModerateTab.Visible = this.PageContext.IsAdmin || this.PageContext.IsForumModerator; this.AdminUserButton.Visible = this.PageContext.IsAdmin; if (this.LastPosts.Visible) { this.LastPosts.DataSource = this.GetRepository <Message>().AllUserAsDataTable( this.PageContext.PageBoardID, this.UserId, this.PageContext.PageUserID, 10).AsEnumerable(); this.SearchUser.NavigateUrl = BuildLink.GetLink( ForumPages.Search, "postedby={0}", userNameOrDisplayName); } this.DataBind(); }
/// <summary> /// The run once. /// </summary> public override void RunOnce() { try { // attempt to run the sync code... AspNetRolesHelper.SyncAllMembershipUsers((int)this.Data); } catch (Exception x) { this.Logger.Error(x, $"Error In {TaskName} Task"); } }
/// <summary> /// Handles the Load event of the Page 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> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { this.PageContext.QueryIDs = new QueryStringIDHelper("u", true); var dt = this.GetRepository <User>().ListAsDataTable(this.PageContext.PageBoardID, this.CurrentUserId, null); if (dt.Rows.Count != 1) { return; } var userRow = dt.GetFirstRow(); // do admin permission check... if (!this.PageContext.IsHostAdmin && this.IsUserHostAdmin(userRow)) { // user is not host admin and is attempted to edit host admin account... BuildLink.AccessDenied(); } if (this.IsPostBack) { return; } var userName = this.HtmlEncode(this.Get <BoardSettings>().EnableDisplayName ? userRow["DisplayName"].ToString() : userRow["Name"].ToString()); var header = string.Format(this.GetText("ADMIN_EDITUSER", "TITLE"), userName); this.Header.Text = this.IconHeader.Text = header; // current page label (no link) this.PageLinks.AddLink( header, string.Empty); this.Page.Header.Title = $"{this.GetText("ADMIN_ADMIN", "Administration")} - {this.GetText("ADMIN_USERS", "TITLE")} - {string.Format(this.GetText("ADMIN_EDITUSER", "TITLE"), userName)}"; // do a quick user membership sync... var user = this.Get <IAspNetUsersHelper>().GetMembershipUserById(this.CurrentUserId); // update if the user is not Guest if (!this.IsGuestUser) { AspNetRolesHelper.UpdateForumUser(user, this.PageContext.PageBoardID); } this.EditUserTabs.DataBind(); }
/// <summary> /// Handles page load event. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { // this needs to be done just once, not during post-backs if (this.IsPostBack) { return; } // sync roles just in case... AspNetRolesHelper.SyncRoles(BoardContext.Current.PageBoardID); // bind data this.BindData(); }
/// <summary> /// Handles the Load event of the Page 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> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { var user = this.GetRepository <User>().GetById(this.CurrentUserId); if (user == null) { return; } // do admin permission check... if (!this.PageContext.IsHostAdmin && user.UserFlags.IsHostAdmin) { // user is not host admin and is attempted to edit host admin account... BuildLink.AccessDenied(); } if (this.IsPostBack) { return; } var userName = this.HtmlEncode(this.Get <IUserDisplayName>().GetName(user)); var header = string.Format(this.GetText("ADMIN_EDITUSER", "TITLE"), userName); this.Header.Text = this.IconHeader.Text = header; // current page label (no link) this.PageLinks.AddLink( header, string.Empty); this.Page.Header.Title = $"{this.GetText("ADMIN_ADMIN", "Administration")} - {this.GetText("ADMIN_USERS", "TITLE")} - {string.Format(this.GetText("ADMIN_EDITUSER", "TITLE"), userName)}"; // do a quick user membership sync... var aspNetUser = this.Get <IAspNetUsersHelper>().GetMembershipUserById(this.CurrentUserId); // update if the user is not Guest if (!this.IsGuestUser) { AspNetRolesHelper.UpdateForumUser(aspNetUser, this.PageContext.PageBoardID); } this.EditUserTabs.DataBind(); }
/// <summary> /// Handles provider roles adding/deleting. /// </summary> /// <param name="source"> /// The source. /// </param> /// <param name="e"> /// The e. /// </param> protected void RoleListNetItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e) { // detect which command are we handling switch (e.CommandName) { case "add": // save role and get its ID const int InitialPMessages = 0; var groupId = this.GetRepository <Group>().Save( DBNull.Value, this.PageContext.PageBoardID, e.CommandArgument.ToString(), false, false, false, false, 1, InitialPMessages, null, 100, null, 0, null, null, 0, 0); // redirect to newly created role BuildLink.Redirect(ForumPages.Admin_EditGroup, "i={0}", groupId); break; case "delete": // delete role from provider data AspNetRolesHelper.DeleteRole(e.CommandArgument.ToString()); // re-bind data this.BindData(); break; } }
/// <summary> /// The handle. /// </summary> /// <param name="event"> /// The event. /// </param> /// <exception cref="ApplicationException">Failed to find guest user.</exception> /// <exception cref="ApplicationException">Failed to create new user.</exception> /// <exception cref="ApplicationException">Unable to find the Guest User!</exception> public void Handle([NotNull] InitPageLoadEvent @event) { try { object userKey = null; if (BoardContext.Current.User != null) { userKey = BoardContext.Current.User.Id; } var tries = 0; DataRow pageRow; var forumPage = this.Get <HttpRequestBase>().QueryString.ToString(); var location = this.Get <HttpRequestBase>().FilePath; // resources are not handled by ActiveLocation control so far. if (location.Contains("resource.ashx")) { forumPage = string.Empty; location = string.Empty; } do { pageRow = this.GetRepository <ActiveAccess>().PageLoadAsDataRow( this.Get <HttpSessionStateBase>().SessionID, BoardContext.Current.PageBoardID, userKey, this.Get <HttpRequestBase>().GetUserRealIPAddress(), location, forumPage, (string)@event.Data.Browser, (string)@event.Data.Platform, (int?)@event.Data.CategoryID, (int?)@event.Data.ForumID, (int?)@event.Data.TopicID, (int?)@event.Data.MessageID, (bool)@event.Data.IsSearchEngine, (bool)@event.Data.IsMobileDevice, (bool)@event.Data.DontTrack); // if the user doesn't exist... if (userKey != null && pageRow == null) { // create the user... if ( !AspNetRolesHelper.DidCreateForumUser( BoardContext.Current.User, BoardContext.Current.PageBoardID)) { throw new ApplicationException("Failed to create new user."); } } if (tries++ < 2) { continue; } if (userKey != null && pageRow == null) { // probably no permissions, use guest user instead... userKey = null; continue; } // fail... break; }while (pageRow == null && userKey != null); if (pageRow == null) { throw new ApplicationException("Unable to find the Guest User!"); } // add all loaded page data into our data dictionary... @event.DataDictionary.AddRange(pageRow.ToDictionary()); // clear active users list if (@event.DataDictionary["ActiveUpdate"].ToType <bool>()) { // purge the cache if something has changed... this.DataCache.Remove(Constants.Cache.UsersOnlineStatus); } } catch (Exception x) { #if !DEBUG // log the exception... this.Logger.Fatal( x, "Failure Initializing User/Page (URL: {0}).", this.Get <HttpRequestBase>().Url.ToString()); // log the user out... // FormsAuthentication.SignOut(); if (BoardContext.Current.ForumPageType != ForumPages.Info) { // show a failure notice since something is probably up with membership... BuildLink.RedirectInfoPage(InfoMessage.Failure); } else { // totally failing... just re-throw the exception... throw; } #else // re-throw exception... throw; #endif } }
/// <summary> /// Sends Notifications to Moderators that a Message was Reported /// </summary> /// <param name="pageForumID"> /// The page Forum ID. /// </param> /// <param name="reportedMessageId"> /// The reported message id. /// </param> /// <param name="reporter"> /// The reporter. /// </param> /// <param name="reportText"> /// The report Text. /// </param> public void ToModeratorsThatMessageWasReported( int pageForumID, int reportedMessageId, int reporter, string reportText) { try { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(pageForumID)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange( AspNetRolesHelper.GetUsersInRole(moderator.Name).Select(u => u.UserName)); } else { moderatorUserNames.Add(moderator.Name); } }); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName); var userId = this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", "NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail("NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE") { // get the user localization... TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{reason}"] = reportText, ["{reporter}"] = this.Get <IUserDisplayName>() .GetName(reporter), ["{adminlink}"] = BuildLink.GetLinkNotEscaped( ForumPages.Moderate_ReportedPosts, true, "f={0}", pageForumID) } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); } catch (Exception x) { // report exception to the forum's event log this.Get <ILogger>().Error( x, $"Send Message Report Notification Error for UserID {BoardContext.Current.PageUserID}"); } }
/// <summary> /// Sends Notifications to Moderators that Message Needs Approval /// </summary> /// <param name="forumId">The forum id.</param> /// <param name="newMessageId">The new message id.</param> /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param> public void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage) { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(forumId)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange(AspNetRolesHelper.GetUsersInRole(moderator.Name).Select(u => u.UserName)); } else { moderatorUserNames.Add(moderator.Name); } }); var themeCss = $"{this.Get<BoardSettings>().BaseUrlMask}{this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css")}"; var forumLink = BoardInfo.ForumURL; var adminLink = BuildLink.GetLinkNotEscaped(ForumPages.Moderate_UnapprovedPosts, true, "f={0}", forumId); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName); var userId = this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail( isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL") { TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{adminlink}"] = adminLink, ["{themecss}"] = themeCss, ["{forumlink}"] = forumLink } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); }
/// <summary> /// The render. /// </summary> /// <param name="writer"> /// The writer. /// </param> protected override void Render(HtmlTextWriter writer) { var hiddenContent = this.Parameters["inner"]; var groupString = this.Parameters["group"]; if (hiddenContent.IsNotSet()) { return; } var descriptionGuest = this.LocalizedString( "HIDDENMOD_GUEST", "This board requires you to be registered and logged-in before you can view hidden messages."); var shownContentGuest = $"<div class=\"alert alert-danger\" role=\"alert\">{descriptionGuest}</div>"; if (groupString.IsNotSet()) { // Hide from Guests only if (BoardContext.Current.IsGuest) { writer.Write(shownContentGuest); return; } } else { if (BoardContext.Current.IsGuest) { writer.Write(shownContentGuest); return; } descriptionGuest = this.LocalizedString( "HIDDENMOD_GROUP", "You dont´t have the right to see the Hidden Content."); shownContentGuest = $"<div class=\"alert alert-danger\" role=\"alert\">{descriptionGuest}</div>"; var groups = groupString.Split(';'); /*List<string> groups = new List<string>(); * List<string> ranks = new List<string>(); * * foreach (string group in groupsAndRanks) * { * if (group.StartsWith("group.")) * { * groups.Add(group.Substring(group.IndexOf(".") + 1)); * } * else if (group.StartsWith("rank.")) * { * ranks.Add(group.Substring(group.IndexOf(".") + 1)); * } * else * { * groups.Add(group); * } * }*/ // Check For Role Hiding if (AspNetRolesHelper.GetRolesForUser( BoardContext.Current.MembershipUser).Any(role => !groups.Any(role.Equals))) { shownContentGuest = hiddenContent; } // TODO : Check for Rank Hiding /*if (ranks.Any()) * { * var yafUserData = new CombinedUserDataHelper(BoardContext.Current.CurrentUserData.PageUserID); * * if (!ranks.Where(rank => yafUserData.RankName.Equals(rank)).Any()) * { * shownContentGuest = hiddenContent; * } * }*/ } // Override Admin, or User is Post Author if (BoardContext.Current.IsAdmin || this.DisplayUserID == BoardContext.Current.PageUserID) { shownContentGuest = hiddenContent; } writer.Write(shownContentGuest); }
/// <summary> /// Import the User From the Current Table Row /// </summary> /// <param name="row"> /// The row with the User Information. /// </param> /// <param name="importCount"> /// The import Count. /// </param> /// <returns> /// Returns the Imported User Count. /// </returns> private int ImportUser(DataRow row, int importCount) { // Also Check if the Email is unique and exists if (this.Get <IAspNetUsersHelper>().GetUserByEmail((string)row["Email"]) != null) { return(importCount); } var provider = new YafMembershipProvider(); var pass = provider.GeneratePassword(); var securityAnswer = provider.GeneratePassword(); // create empty profile just so they have one var userProfile = new ProfileInfo(); // Add Profile Fields to User List Table. if (row.Table.Columns.Contains("RealName") && ((string)row["RealName"]).IsSet()) { userProfile.RealName = (string)row["RealName"]; } if (row.Table.Columns.Contains("Blog") && ((string)row["Blog"]).IsSet()) { userProfile.Blog = (string)row["Blog"]; } if (row.Table.Columns.Contains("Gender") && ((string)row["Gender"]).IsSet()) { int.TryParse((string)row["Gender"], out var gender); userProfile.Gender = gender; } if (row.Table.Columns.Contains("Birthday") && ((string)row["Birthday"]).IsSet()) { DateTime.TryParse((string)row["Birthday"], out var userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime()) { userProfile.Birthday = userBirthdate; } } if (row.Table.Columns.Contains("GoogleId") && ((string)row["GoogleId"]).IsSet()) { userProfile.GoogleId = (string)row["GoogleId"]; } if (row.Table.Columns.Contains("Location") && ((string)row["Location"]).IsSet()) { userProfile.Location = (string)row["Location"]; } if (row.Table.Columns.Contains("Country") && ((string)row["Country"]).IsSet()) { userProfile.Country = (string)row["Country"]; } if (row.Table.Columns.Contains("Region") && ((string)row["Region"]).IsSet()) { userProfile.Region = (string)row["Region"]; } if (row.Table.Columns.Contains("City") && ((string)row["City"]).IsSet()) { userProfile.City = (string)row["City"]; } if (row.Table.Columns.Contains("Interests") && ((string)row["Interests"]).IsSet()) { userProfile.Interests = (string)row["Interests"]; } if (row.Table.Columns.Contains("Homepage") && ((string)row["Homepage"]).IsSet()) { userProfile.Homepage = (string)row["Homepage"]; } if (row.Table.Columns.Contains("Skype") && ((string)row["Skype"]).IsSet()) { userProfile.Skype = (string)row["Skype"]; } if (row.Table.Columns.Contains("ICQe") && ((string)row["ICQ"]).IsSet()) { userProfile.ICQ = (string)row["ICQ"]; } if (row.Table.Columns.Contains("XMPP") && ((string)row["XMPP"]).IsSet()) { userProfile.XMPP = (string)row["XMPP"]; } if (row.Table.Columns.Contains("Occupation") && ((string)row["Occupation"]).IsSet()) { userProfile.Occupation = (string)row["Occupation"]; } if (row.Table.Columns.Contains("Twitter") && ((string)row["Twitter"]).IsSet()) { userProfile.Twitter = (string)row["Twitter"]; } if (row.Table.Columns.Contains("TwitterId") && ((string)row["TwitterId"]).IsSet()) { userProfile.TwitterId = (string)row["TwitterId"]; } if (row.Table.Columns.Contains("Facebook") && ((string)row["Facebook"]).IsSet()) { userProfile.Facebook = (string)row["Facebook"]; } if (row.Table.Columns.Contains("FacebookId") && ((string)row["FacebookId"]).IsSet()) { userProfile.FacebookId = (string)row["FacebookId"]; } var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = (string)row["Name"], LoweredUserName = (string)row["Name"], Email = (string)row["Email"], IsApproved = true, Profile_Birthday = userProfile.Birthday, Profile_Blog = userProfile.Blog, Profile_Gender = userProfile.Gender, Profile_GoogleId = userProfile.GoogleId, Profile_Homepage = userProfile.Homepage, Profile_ICQ = userProfile.ICQ, Profile_Facebook = userProfile.Facebook, Profile_FacebookId = userProfile.FacebookId, Profile_Twitter = userProfile.Twitter, Profile_TwitterId = userProfile.TwitterId, Profile_Interests = userProfile.Interests, Profile_Location = userProfile.Location, Profile_Country = userProfile.Country, Profile_Region = userProfile.Region, Profile_City = userProfile.City, Profile_Occupation = userProfile.Occupation, Profile_RealName = userProfile.RealName, Profile_Skype = userProfile.Skype, Profile_XMPP = userProfile.XMPP, Profile_LastSyncedWithDNN = userProfile.LastSyncedWithDNN }; this.Get <IAspNetUsersHelper>().Create(user, pass); // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(BoardContext.Current.PageBoardID, user); // create the user in the YAF DB as well as sync roles... var userID = AspNetRolesHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); if (userID == null) { // something is seriously wrong here -- redirect to failure... return(importCount); } // send user register notification to the new users this.Get <ISendNotification>().SendRegistrationNotificationToUser( user, pass, securityAnswer, "NOTIFICATION_ON_REGISTER"); // save the time zone... var userId = this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(user.Id); var timeZone = 0; if (row.Table.Columns.Contains("Timezone") && ((string)row["Timezone"]).IsSet()) { int.TryParse((string)row["Timezone"], out timeZone); } var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; this.GetRepository <User>().Save( userId, BoardContext.Current.PageBoardID, row["Name"], row.Table.Columns.Contains("DisplayName") ? row["DisplayName"] : null, row["Email"], timeZone, row.Table.Columns.Contains("LanguageFile") ? row["LanguageFile"] : null, row.Table.Columns.Contains("Culture") ? row["Culture"] : null, row.Table.Columns.Contains("ThemeFile") ? row["ThemeFile"] : null, false); // save the settings... this.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); importCount++; return(importCount); }
/// <summary> /// Create user /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void RegisterClick(object sender, EventArgs e) { if (!this.Page.IsValid) { return; } if (!this.ValidateUser()) { return; } var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = this.UserName.Text, LoweredUserName = this.UserName.Text, Email = this.Email.Text, IsApproved = false, EmailConfirmed = false }; var result = this.Get <IAspNetUsersHelper>().Create(user, this.Password.Text.Trim()); if (!result.Succeeded) { // error of some kind this.PageContext.AddLoadMessage(result.Errors.FirstOrDefault(), MessageTypes.danger); } else { // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(this.PageContext.PageBoardID, user); var displayName = this.DisplayName.Text; // create the user in the YAF DB as well as sync roles... var userID = AspNetRolesHelper.CreateForumUser(user, displayName, this.PageContext.PageBoardID); if (userID == null) { // something is seriously wrong here -- redirect to failure... BuildLink.RedirectInfoPage(InfoMessage.Failure); } if (this.IsPossibleSpamBot) { if (this.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } } else { // handle e-mail verification var email = this.Email.Text.Trim(); this.Get <ISendNotification>().SendVerificationEmail(user, email, userID); if (this.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } } this.BodyRegister.Visible = false; this.Footer.Visible = false; // success notification localization this.Message.Visible = true; this.AccountCreated.Text = this.Get <IBBCode>().MakeHtml( this.GetText("ACCOUNT_CREATED_VERIFICATION"), true, true); } }
/// <summary> /// Creates the facebook user /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="email"> /// The email. /// </param> /// <param name="facebookUserId"> /// The facebook User Id. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateFacebookUser(string name, string email, string facebookUserId, out string message) { if (this.Get <BoardSettings>().DisableRegistrations) { message = this.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check if user name is null var userName = name; var displayName = userName; userName = displayName.Replace(" ", "."); var pass = PasswordGenerator.GeneratePassword(true, true, true, true, false, 16); var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = userName, LoweredUserName = userName.ToLower(), Email = email, IsApproved = true, EmailConfirmed = true, Profile_RealName = name, Profile_FacebookId = facebookUserId, Profile_Facebook = $"https://www.facebook.com/profile.php?id={facebookUserId}" }; var result = this.Get <IAspNetUsersHelper>().Create(user, pass); if (!result.Succeeded) { // error of some kind message = result.Errors.FirstOrDefault(); return(false); } // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(BoardContext.Current.PageBoardID, user); // create the user in the YAF DB as well as sync roles... var userID = AspNetRolesHelper.CreateForumUser(user, displayName, BoardContext.Current.PageBoardID); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = this.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // send user register notification to the user... this.Get <ISendNotification>().SendRegistrationNotificationToUser( user, pass, "NOTIFICATION_ON_FACEBOOK_REGISTER"); if (this.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; this.GetRepository <User>().Save( userID.Value, BoardContext.Current.PageBoardID, user.UserName, user.UserName, user.Email, TimeZoneInfo.Local.Id, null, null, null, false); // save the settings... this.GetRepository <User>().SaveNotification( userID.Value, true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar this.GetRepository <User>().SaveAvatar( userID.Value, $"https://graph.facebook.com/{facebookUserId}/picture", null, null); this.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userID.Value)); message = string.Empty; return(true); }
/// <summary> /// Handles the Click event of the ForumRegister control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void ForumRegisterClick([NotNull] object sender, [NotNull] EventArgs e) { this.Page.Validate(); if (!this.Page.IsValid) { return; } var newEmail = this.Email.Text.Trim(); var newUsername = this.UserName.Text.Trim(); if (!ValidationHelper.IsValidEmail(newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_INVALID_MAIL"), MessageTypes.danger); return; } if (this.Get <IAspNetUsersHelper>().UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS"), MessageTypes.danger); return; } // setup their initial profile information var userProfile = new ProfileInfo { Location = this.Location.Text.Trim(), Homepage = this.HomePage.Text.Trim() }; var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = newUsername, LoweredUserName = newUsername, Email = newEmail, IsApproved = !this.Get <BoardSettings>().EmailVerification, EmailConfirmed = !this.Get <BoardSettings>().EmailVerification, Profile_Birthday = userProfile.Birthday, Profile_Blog = userProfile.Blog, Profile_Gender = userProfile.Gender, Profile_GoogleId = userProfile.GoogleId, Profile_Homepage = userProfile.Homepage, Profile_ICQ = userProfile.ICQ, Profile_Facebook = userProfile.Facebook, Profile_FacebookId = userProfile.FacebookId, Profile_Twitter = userProfile.Twitter, Profile_TwitterId = userProfile.TwitterId, Profile_Interests = userProfile.Interests, Profile_Location = userProfile.Location, Profile_Country = userProfile.Country, Profile_Region = userProfile.Region, Profile_City = userProfile.City, Profile_Occupation = userProfile.Occupation, Profile_RealName = userProfile.RealName, Profile_Skype = userProfile.Skype, Profile_XMPP = userProfile.XMPP, Profile_LastSyncedWithDNN = userProfile.LastSyncedWithDNN }; var result = this.Get <IAspNetUsersHelper>().Create(user, this.Password.Text.Trim()); if (!result.Succeeded) { // error of some kind this.PageContext.AddLoadMessage(result.Errors.FirstOrDefault(), MessageTypes.danger); return; } // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(BoardContext.Current.PageBoardID, user); // create the user in the YAF DB as well as sync roles... var userId = AspNetRolesHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting .Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // save the time zone... this.GetRepository <User>().Save( this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(user.Id), this.PageContext.PageBoardID, null, null, null, this.TimeZones.SelectedValue, null, null, null, false); if (this.Get <BoardSettings>().EmailVerification) { this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userId, newUsername); } this.GetRepository <User>().SaveNotification( this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(user.Id), true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); // success this.PageContext.AddLoadMessage( this.GetTextFormatted("MSG_CREATED", this.UserName.Text.Trim()), MessageTypes.success); BuildLink.Redirect(ForumPages.Admin_RegisterUser); }
/// <summary> /// The create board. /// </summary> /// <param name="adminName">The admin name.</param> /// <param name="adminPassword">The admin password.</param> /// <param name="adminEmail">The admin email.</param> /// <param name="boardName">The board name.</param> /// <param name="createUserAndRoles">The create user and roles.</param> /// <returns>Returns if the board was created or not</returns> protected bool CreateBoard( [NotNull] string adminName, [NotNull] string adminPassword, [NotNull] string adminEmail, [NotNull] string boardName, bool createUserAndRoles) { int newBoardId; var cult = StaticDataHelper.Cultures(); var langFile = "english.xml"; cult.Where(dataRow => dataRow.CultureTag == this.Culture.SelectedValue) .ForEach(row => langFile = row.CultureFile); if (createUserAndRoles) { var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = adminName, LoweredUserName = adminName, Email = adminEmail, IsApproved = true }; // Create new admin users var result = this.Get <IAspNetUsersHelper>().Create(user, adminPassword); if (!result.Succeeded) { this.PageContext.AddLoadMessage( $"Create User Failed: {result.Errors.FirstOrDefault()}", MessageTypes.danger); return(false); } // Create groups required for the new board AspNetRolesHelper.CreateRole("Administrators"); AspNetRolesHelper.CreateRole("Registered"); // Add new admin users to group AspNetRolesHelper.AddUserToRole(user, "Administrators"); // Create Board newBoardId = this.DbCreateBoard( boardName, langFile, user); } else { // new admin var newAdmin = this.Get <IAspNetUsersHelper>().GetUser(); // Create Board newBoardId = this.DbCreateBoard( boardName, langFile, newAdmin); } if (newBoardId <= 0 || !Config.MultiBoardFolders) { return(true); } // Successfully created the new board var boardFolder = this.Server.MapPath(Path.Combine(Config.BoardRoot, $"{newBoardId}/")); // Create New Folders. if (!Directory.Exists(Path.Combine(boardFolder, "Images"))) { // Create the Images Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images")); // Create Sub Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals")); } if (!Directory.Exists(Path.Combine(boardFolder, "Uploads"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads")); } return(true); }
/// <summary> /// Saves the click. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void SaveClick([NotNull] object sender, [NotNull] EventArgs e) { if (!ValidationHelper.IsValidInt(this.PMLimit.Text.Trim())) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITGROUP", "MSG_VALID_NUMBER"), MessageTypes.warning); return; } if (!ValidationHelper.IsValidInt(this.Priority.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_INTEGER"), MessageTypes.warning); return; } if (!ValidationHelper.IsValidInt(this.UsrAlbums.Text.Trim())) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITGROUP", "MSG_ALBUM_NUMBER"), MessageTypes.warning); return; } if (!ValidationHelper.IsValidInt(this.UsrSigChars.Text.Trim())) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITGROUP", "MSG_SIG_NUMBER"), MessageTypes.warning); return; } if (!ValidationHelper.IsValidInt(this.UsrAlbumImages.Text.Trim())) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITGROUP", "MSG_TOTAL_NUMBER"), MessageTypes.warning); return; } // Role long roleId = 0; // get role ID from page's parameter if (this.Get <HttpRequestBase>().QueryString.Exists("i")) { roleId = long.Parse(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("i")); } // get new and old name var roleName = this.Name.Text.Trim(); var oldRoleName = string.Empty; // if we are editing existing role, get it's original name if (roleId != 0) { // get the current role name in the DB var groups = this.GetRepository <Group>().List(boardId: this.PageContext.PageBoardID); groups.ForEach(group => oldRoleName = group.Name); } // save role and get its ID if it's new (if it's old role, we get it anyway) roleId = this.GetRepository <Group>().Save( roleId, this.PageContext.PageBoardID, roleName, this.IsAdminX.Checked, this.IsGuestX.Checked, this.IsStartX.Checked, this.IsModeratorX.Checked, this.AccessMaskID.SelectedValue, this.PMLimit.Text.Trim(), this.StyleTextBox.Text.Trim(), this.Priority.Text.Trim(), this.Description.Text, this.UsrSigChars.Text, this.UsrSigBBCodes.Text, this.UsrSigHTMLTags.Text, this.UsrAlbums.Text.Trim(), this.UsrAlbumImages.Text.Trim()); // empty out access table(s) this.GetRepository <Active>().DeleteAll(); this.GetRepository <ActiveAccess>().DeleteAll(); // see if need to rename an existing role... if (oldRoleName.IsSet() && roleName != oldRoleName && AspNetRolesHelper.RoleExists(oldRoleName) && !AspNetRolesHelper.RoleExists(roleName) && !this.IsGuestX.Checked) { // transfer users in addition to changing the name of the role... var users = AspNetRolesHelper.GetUsersInRole(oldRoleName); // delete the old role... AspNetRolesHelper.DeleteRole(oldRoleName); // create new role... AspNetRolesHelper.CreateRole(roleName); if (users.Any()) { // put users into new role... users.ForEach(user => AspNetRolesHelper.AddUserToRole(user, roleName)); } } else if (!AspNetRolesHelper.RoleExists(roleName) && !this.IsGuestX.Checked) { // if role doesn't exist in provider's data source, create it // simply create it AspNetRolesHelper.CreateRole(roleName); } // Access masks for a newly created or an existing role if (this.Get <HttpRequestBase>().QueryString.Exists("i")) { // go through all forums for (var i = 0; i < this.AccessList.Items.Count; i++) { // get current repeater item var item = this.AccessList.Items[i]; // get forum ID var forumId = int.Parse(item.FindControlAs <HiddenField>("ForumID").Value); // save forum access masks for this role this.GetRepository <ForumAccess>().Save( forumId, roleId.ToType <int>(), item.FindControlAs <DropDownList>("AccessmaskID").SelectedValue.ToType <int>()); } BuildLink.Redirect(ForumPages.Admin_Groups); } // remove caching in case something got updated... this.Get <IDataCache>().Remove(Constants.Cache.ForumModerators); // Clearing cache with old permissions data... this.Get <IDataCache>().Remove( k => k.StartsWith(string.Format(Constants.Cache.ActiveUserLazyData, string.Empty))); // Clear Styling Caching this.Get <IDataCache>().Remove(Constants.Cache.GroupRankStyles); // Done, redirect to role editing page BuildLink.Redirect(ForumPages.Admin_EditGroup, "i={0}", roleId); }
/// <summary> /// Handles click on save button. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e) { var addedRoles = new List <string>(); var removedRoles = new List <string>(); // get user's name var user = this.Get <IAspNetUsersHelper>().GetMembershipUserById(this.CurrentUserID); // go through all roles displayed on page for (var i = 0; i < this.UserGroups.Items.Count; i++) { // get current item var item = this.UserGroups.Items[i]; // get role ID from it var roleID = int.Parse(item.FindControlAs <Label>("GroupID").Text); // get role name var roleName = this.GetRepository <Group>().GetById(roleID).Name; // is user supposed to be in that role? var isChecked = item.FindControlAs <CheckBox>("GroupMember").Checked; // save user in role this.GetRepository <UserGroup>().Save(this.CurrentUserID, roleID, isChecked); // empty out access table(s) this.GetRepository <Active>().DeleteAll(); this.GetRepository <ActiveAccess>().DeleteAll(); // update roles if this user isn't the guest if (this.Get <IAspNetUsersHelper>().IsGuestUser(this.CurrentUserID)) { continue; } // add/remove user from roles in membership provider if (isChecked && !AspNetRolesHelper.IsUserInRole(user, roleName)) { AspNetRolesHelper.AddUserToRole(user, roleName); addedRoles.Add(roleName); } else if (!isChecked && AspNetRolesHelper.IsUserInRole(user, roleName)) { AspNetRolesHelper.RemoveUserFromRole(user.Id, roleName); removedRoles.Add(roleName); } // Clearing cache with old permissions data... this.Get <IDataCache>().Remove(string.Format(Constants.Cache.ActiveUserLazyData, this.CurrentUserID)); } if (this.SendEmail.Checked) { // send notification to user if (addedRoles.Any()) { this.Get <ISendNotification>().SendRoleAssignmentNotification(user, addedRoles); } if (removedRoles.Any()) { this.Get <ISendNotification>().SendRoleUnAssignmentNotification(user, removedRoles); } } // update forum moderators cache just in case something was changed... this.Get <IDataCache>().Remove(Constants.Cache.ForumModerators); // clear the cache for this user... this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.CurrentUserID)); this.BindData(); }
/// <summary> /// Handles the Click event of the ForumRegister control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void ForumRegisterClick([NotNull] object sender, [NotNull] EventArgs e) { this.Page.Validate(); if (!this.Page.IsValid) { return; } var newEmail = this.Email.Text.Trim(); var newUsername = this.UserName.Text.Trim(); if (!ValidationHelper.IsValidEmail(newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_INVALID_MAIL"), MessageTypes.danger); return; } if (this.Get <IAspNetUsersHelper>().UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS"), MessageTypes.danger); return; } var user = new AspNetUsers { Id = Guid.NewGuid().ToString(), ApplicationId = this.Get <BoardSettings>().ApplicationId, UserName = newUsername, LoweredUserName = newUsername, Email = newEmail, IsApproved = false, EmailConfirmed = false }; var result = this.Get <IAspNetUsersHelper>().Create(user, this.Password.Text.Trim()); if (!result.Succeeded) { // error of some kind this.PageContext.AddLoadMessage(result.Errors.FirstOrDefault(), MessageTypes.danger); return; } // setup initial roles (if any) for this user AspNetRolesHelper.SetupUserRoles(this.PageContext.PageBoardID, user); // create the user in the YAF DB as well as sync roles... var userId = AspNetRolesHelper.CreateForumUser(user, this.PageContext.PageBoardID); var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting .Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userId, newUsername); this.GetRepository <User>().SaveNotification( this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(user.Id), true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); // success this.PageContext.LoadMessage.AddSession( this.GetTextFormatted("MSG_CREATED", this.UserName.Text.Trim()), MessageTypes.success); BuildLink.Redirect(ForumPages.Admin_Users); }