/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null || !this.Get <YafBoardSettings>().AllowEmailSending) { YafBuildLink.AccessDenied(); } if (this.IsPostBack) { return; } // get user data... SitecoreMembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserID); if (user == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } string displayName = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddRoot(); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); this.Send.Text = this.GetText("SEND"); }
/// <summary> /// Creates the user in the YAF DB from the ASP.NET Membership user information. /// Also copies the Roles as groups into YAF DB for the current user /// </summary> /// <param name="user"> /// Current Membership User /// </param> /// <param name="displayName"> /// The display Name. /// </param> /// <param name="pageBoardID"> /// Current BoardID /// </param> /// <returns> /// Returns the UserID of the user if everything was successful. Otherwise, null. /// </returns> public static int?CreateForumUser([NotNull] SitecoreMembershipUser user, [NotNull] string displayName, int pageBoardID) { int?userID = null; try { userID = LegacyDb.user_aspnet( pageBoardID, user.UserName, displayName, user.Email, user.ProviderUserKey, user.IsApproved); foreach (string role in GetRolesForUser(user.UserName)) { LegacyDb.user_setrole(pageBoardID, user.ProviderUserKey, role); } // YAF.Classes.Data.DB.eventlog_create(DBNull.Value, user, string.Format("Created forum user {0}", user.UserName)); } catch (Exception x) { YafContext.Current.Get <ILogger>().Error(x, "Error in CreateForumUser"); } return(userID); }
/// <summary> /// Sends the verification email. /// </summary> /// <param name="user">The user.</param> /// <param name="email">The email.</param> /// <param name="userID">The user identifier.</param> /// <param name="newUsername">The new username.</param> public void SendVerificationEmail( [NotNull] SitecoreMembershipUser user, [NotNull] string email, int?userID, string newUsername = null) { CodeContracts.VerifyNotNull(email, "email"); CodeContracts.VerifyNotNull(user, "user"); var hashinput = string.Format("{0}{1}{2}", DateTime.UtcNow, email, Security.CreatePassword(20)); var hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); // save verification record... this.GetRepository <CheckEmail>().Save(userID, hash, user.Email); var verifyEmail = new YafTemplateEmail("VERIFYEMAIL"); var subject = this.Get <ILocalization>() .GetTextFormatted("VERIFICATION_EMAIL_SUBJECT", this.Get <YafBoardSettings>().Name); verifyEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.approve, true, "k={0}", hash); verifyEmail.TemplateParams["{key}"] = hash; verifyEmail.TemplateParams["{forumname}"] = this.Get <YafBoardSettings>().Name; verifyEmail.TemplateParams["{forumlink}"] = "{0}".FormatWith(YafForumInfo.ForumURL); verifyEmail.SendEmail(new MailAddress(email, newUsername ?? user.UserName), subject, true); }
/// <summary> /// The btn reset password_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void btnResetPassword_Click([NotNull] object sender, [NotNull] EventArgs e) { // reset password... try { SitecoreMembershipUser user = UserMembershipHelper.GetMembershipUserById(this.CurrentUserID.Value); if (user != null) { // reset the password... user.UnlockUser(); string newPassword = user.ResetPassword(); // email a notification... var passwordRetrieval = new YafTemplateEmail("PASSWORDRETRIEVAL"); string subject = this.Get <ILocalization>().GetText("RECOVER_PASSWORD", "PASSWORDRETRIEVAL_EMAIL_SUBJECT").FormatWith( this.PageContext.BoardSettings.Name); passwordRetrieval.TemplateParams["{username}"] = user.UserName; passwordRetrieval.TemplateParams["{password}"] = newPassword; passwordRetrieval.TemplateParams["{forumname}"] = this.Get <YafBoardSettings>().Name; passwordRetrieval.TemplateParams["{forumlink}"] = "{0}".FormatWith(YafForumInfo.ForumURL); passwordRetrieval.SendEmail(new MailAddress(user.Email, user.UserName), subject, true); this.PageContext.AddLoadMessage(this.Get <ILocalization>().GetText("ADMIN_EDITUSER", "MSG_PASS_RESET")); } } catch (Exception x) { this.PageContext.AddLoadMessage("Exception: {0}".FormatWith(x.Message)); } }
/// <summary> /// Sends a new user notification email to all emails in the NotificationOnUserRegisterEmailList /// Setting /// </summary> /// <param name="user">The user.</param> /// <param name="userId">The user id.</param> public void SendRegistrationNotificationEmail([NotNull] SitecoreMembershipUser user, int userId) { string[] emails = this.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.Split(';'); var notifyAdmin = new YafTemplateEmail(); var subject = this.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_USER_REGISTER_EMAIL_SUBJECT") .FormatWith(this.Get <YafBoardSettings>().Name); notifyAdmin.TemplateParams["{adminlink}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.admin_edituser, true, "u={0}", userId); notifyAdmin.TemplateParams["{user}"] = user.UserName; notifyAdmin.TemplateParams["{email}"] = user.Email; notifyAdmin.TemplateParams["{forumname}"] = this.Get <YafBoardSettings>().Name; var emailBody = notifyAdmin.ProcessTemplate("NOTIFICATION_ON_USER_REGISTER"); foreach (var email in emails.Where(email => email.Trim().IsSet())) { this.GetRepository <Mail>() .Create(this.Get <YafBoardSettings>().ForumEmail, email.Trim(), subject, emailBody); } }
/// <summary> /// Sends the user welcome notification. /// </summary> /// <param name="user">The user.</param> /// <param name="userId">The user identifier.</param> public void SendUserWelcomeNotification([NotNull] SitecoreMembershipUser user, int?userId) { if (this.Get <YafBoardSettings>().SendWelcomeNotificationAfterRegister.Equals(0)) { return; } var notifyUser = new YafTemplateEmail(); var subject = this.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_WELCOME_USER_SUBJECT") .FormatWith(YafContext.Current.Get <YafBoardSettings>().Name); notifyUser.TemplateParams["{user}"] = user.UserName; notifyUser.TemplateParams["{forumname}"] = this.BoardSettings.Name; notifyUser.TemplateParams["{forumurl}"] = YafForumInfo.ForumURL; var emailBody = notifyUser.ProcessTemplate("NOTIFICATION_ON_WELCOME_USER"); var messageFlags = new MessageFlags { IsHtml = false, IsBBCode = true }; if (this.Get <YafBoardSettings>().AllowPrivateMessages && this.Get <YafBoardSettings>().SendWelcomeNotificationAfterRegister.Equals(2)) { LegacyDb.pmessage_save(2, userId, subject, emailBody, messageFlags.BitValue, -1); } else { this.GetRepository <Mail>().Create(this.BoardSettings.ForumEmail, user.Email, subject, emailBody); } }
/// <summary> /// Send an Private Message to the Newly Created User with /// his Account Info (Pass, Security Question and Answer) /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="pass"> /// The pass. /// </param> /// <param name="securityAnswer"> /// The security answer. /// </param> /// <param name="userId"> /// The user Id. /// </param> /// <param name="oAuth"> /// The oAUTH. /// </param> private static void SendRegistrationMessageToTwitterUser( [NotNull] SitecoreMembershipUser user, [NotNull] string pass, [NotNull] string securityAnswer, [NotNull] int userId, OAuthTwitter oAuth) { var notifyUser = new YafTemplateEmail(); string subject = YafContext.Current.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_NEW_FACEBOOK_USER_SUBJECT") .FormatWith(YafContext.Current.Get <YafBoardSettings>().Name); notifyUser.TemplateParams["{user}"] = user.UserName; notifyUser.TemplateParams["{email}"] = user.Email; notifyUser.TemplateParams["{pass}"] = pass; notifyUser.TemplateParams["{answer}"] = securityAnswer; notifyUser.TemplateParams["{forumname}"] = YafContext.Current.Get <YafBoardSettings>().Name; var emailBody = notifyUser.ProcessTemplate("NOTIFICATION_ON_TWITTER_REGISTER"); var messageFlags = new MessageFlags { IsHtml = false, IsBBCode = true }; // Send Message also as DM to Twitter. var tweetApi = new TweetAPI(oAuth); var message = "{0}. {1}".FormatWith( subject, YafContext.Current.Get <ILocalization>().GetText("LOGIN", "TWITTER_DM")); if (YafContext.Current.Get <YafBoardSettings>().AllowPrivateMessages) { LegacyDb.pmessage_save(2, userId, subject, emailBody, messageFlags.BitValue, -1); } else { message = YafContext.Current.Get <ILocalization>() .GetTextFormatted( "LOGIN", "TWITTER_DM_ACCOUNT", YafContext.Current.Get <YafBoardSettings>().Name, user.UserName, pass); } try { tweetApi.SendDirectMessage(TweetAPI.ResponseFormat.json, user.UserName, message.Truncate(140)); } catch (Exception ex) { YafContext.Current.Get <ILogger>().Error(ex, "Error while sending Twitter DM Message"); } }
/// <summary> /// Updates the User Info /// </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 Save_Click([NotNull] object sender, [NotNull] EventArgs e) { // Update the Membership if (!this.IsGuestX.Checked) { SitecoreMembershipUser user = UserMembershipHelper.GetUser(this.Name.Text.Trim()); string userName = this.Get <MembershipProvider>().GetUserNameByEmail(this.Email.Text.Trim()); if (userName.IsSet() && userName != user.UserName) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_EMAIL"), MessageTypes.Warning); return; } if (this.Email.Text.Trim() != user.Email) { // update the e-mail here too... user.Email = this.Email.Text.Trim(); } // Update IsApproved user.IsApproved = this.IsApproved.Checked; this.Get <MembershipProvider>().UpdateUser(user); } else { if (!this.IsApproved.Checked) { this.PageContext.AddLoadMessage( this.Get <ILocalization>().GetText("ADMIN_EDITUSER", "MSG_GUEST_APPROVED"), MessageTypes.Success); return; } } var userFlags = new UserFlags { IsHostAdmin = this.IsHostAdminX.Checked, IsGuest = this.IsGuestX.Checked, IsCaptchaExcluded = this.IsCaptchaExcluded.Checked, IsActiveExcluded = this.IsExcludedFromActiveUsers.Checked, IsApproved = this.IsApproved.Checked }; LegacyDb.user_adminsave( this.PageContext.PageBoardID, this.CurrentUserID, this.Name.Text.Trim(), this.DisplayName.Text.Trim(), this.Email.Text.Trim(), userFlags.BitValue, this.RankID.SelectedValue); this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.CurrentUserID)); this.BindData(); }
/// <summary> /// Handles the CreatedUser event of the CreateUserWizard1 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 CreateUserWizard1_CreatedUser([NotNull] object sender, [NotNull] EventArgs e) { SitecoreMembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, this.CreateUserWizard1.UserName); var displayName = user.UserName; if (this.Get <YafBoardSettings>().EnableDisplayName) { displayName = this.CreateUserStepContainer.FindControlAs <TextBox>("DisplayName").Text.Trim(); } // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, displayName, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... YafBuildLink.RedirectInfoPage(InfoMessage.Failure); } // handle e-mail verification if needed if (this.Get <YafBoardSettings>().EmailVerification) { // get the user email var emailTextBox = (TextBox)this.CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email"); var email = emailTextBox.Text.Trim(); this.Get <ISendNotification>().SendVerificationEmail(user, email, userID); } else { // Send welcome mail/pm to user this.Get <ISendNotification>().SendUserWelcomeNotification(user, userID.Value); } if (this.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (this.IsPossibleSpamBot) { this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { // get user data... SitecoreMembershipUser userHe = UserMembershipHelper.GetMembershipUserById(this.UserID); string displayNameHe = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayNameHe : userHe.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayNameHe : userHe.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); if (this.UserID == this.PageContext.PageUserID) { this.NotifyLabel.Text = this.GetText("SERVERYOU"); } else { if (userHe == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } // Data for current page user SitecoreMembershipUser userMe = UserMembershipHelper.GetMembershipUserById(this.PageContext.PageUserID); // get full user data... var userDataHe = new CombinedUserDataHelper(userHe, this.UserID); var userDataMe = new CombinedUserDataHelper(userMe, this.PageContext.PageUserID); string serverHe = userDataHe.Profile.XMPP.Substring(userDataHe.Profile.XMPP.IndexOf("@") + 1).Trim(); string serverMe = userDataMe.Profile.XMPP.Substring(userDataMe.Profile.XMPP.IndexOf("@") + 1).Trim(); if (serverMe == serverHe) { this.NotifyLabel.Text = this.GetTextFormatted("SERVERSAME", userDataHe.Profile.XMPP); } else { this.NotifyLabel.Text = this.GetTextFormatted("SERVEROTHER", "http://" + serverHe); } } } }
/// <summary> /// Sends a spam bot notification to admins. /// </summary> /// <param name="user">The user.</param> /// <param name="userId">The user id.</param> public void SendSpamBotNotificationToAdmins([NotNull] SitecoreMembershipUser user, int userId) { // Get Admin Group ID var adminGroupID = YafContext.Current.GetRepository <Group>() .ListTyped(boardId: YafContext.Current.PageBoardID) .Where(@group => @group.Name.Contains("Admin")) .Select(@group => @group.ID) .FirstOrDefault(); if (adminGroupID <= 0) { return; } using (DataTable dt = LegacyDb.user_emails(YafContext.Current.PageBoardID, adminGroupID)) { foreach (DataRow row in dt.Rows) { var emailAddress = row.Field <string>("Email"); if (!emailAddress.IsSet()) { continue; } var notifyAdmin = new YafTemplateEmail(); var subject = this.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_BOT_USER_REGISTER_EMAIL_SUBJECT") .FormatWith(this.Get <YafBoardSettings>().Name); notifyAdmin.TemplateParams["{adminlink}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.admin_edituser, true, "u={0}", userId); notifyAdmin.TemplateParams["{user}"] = user.UserName; notifyAdmin.TemplateParams["{email}"] = user.Email; notifyAdmin.TemplateParams["{forumname}"] = this.Get <YafBoardSettings>().Name; var emailBody = notifyAdmin.ProcessTemplate("NOTIFICATION_ON_BOT_USER_REGISTER"); this.GetRepository <Mail>() .Create(this.Get <YafBoardSettings>().ForumEmail, emailAddress, subject, emailBody); } } }
/// <summary> /// The create user wizard 1_ next button click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void CreateUserWizard1_NextButtonClick([NotNull] object sender, [NotNull] WizardNavigationEventArgs e) { if (this.CreateUserWizard1.WizardSteps[e.CurrentStepIndex].ID != "profile") { return; } SitecoreMembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); this.SetupUserProfile(user, userId); // Clearing cache with old Active User Lazy Data ... this.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); }
/// <summary> /// This method returns a string which shows how many times users have /// thanked the message with the provided messageID. Returns an empty string. /// </summary> /// <param name="username"> /// The username. /// </param> /// <param name="messageID"> /// The Message ID. /// </param> /// <returns> /// The thanks number. /// </returns> protected static string ThanksNumber([NotNull] string username, int messageID) { int thanksNumber = LegacyDb.message_ThanksNumber(messageID); string displayName = username; if (YafContext.Current.Get <YafBoardSettings>().EnableDisplayName) { // get the user's display name. SitecoreMembershipUser mu = UserMembershipHelper.GetMembershipUserByName(username); if (mu != null) { displayName = YafContext.Current.Get <IUserDisplayName>().GetName( UserMembershipHelper.GetUserIDFromProviderUserKey( mu.ProviderUserKey)); } } displayName = YafContext.Current.Get <HttpServerUtilityBase>().HtmlEncode(displayName); string thanksText; switch (thanksNumber) { case 0: return(string.Empty); case 1: thanksText = YafContext.Current.Get <ILocalization>().GetText("POSTS", "THANKSINFOSINGLE").FormatWith( displayName); return ("<img id=\"ThanksInfoImage{0}\" src=\"{1}\" runat=\"server\" title=\"{2}\" /> {2}".FormatWith( messageID, YafContext.Current.Get <ITheme>().GetItem("ICONS", "THANKSINFOLIST_IMAGE"), thanksText)); } thanksText = YafContext.Current.Get <ILocalization>().GetText("POSTS", "THANKSINFO").FormatWith(thanksNumber, displayName); return ("<img id=\"ThanksInfoImage{0}\" src=\"{1}\" runat=\"server\" title=\"{2}\" /> {2}".FormatWith( messageID, YafContext.Current.Get <ITheme>().GetItem("ICONS", "THANKSINFOLIST_IMAGE"), thanksText)); }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { this.Send.Text = this.GetText("SEND"); this.From.Text = this.PageContext.User.UserName; this.Email.Text = this.PageContext.User.Email; // get user data... SitecoreMembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserID); if (user == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } string displayName = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); // get full user data... var userData = new CombinedUserDataHelper(user, this.UserID); this.ViewState["to"] = userData.Profile.ICQ; this.Status.Src = "http://web.icq.com/whitepages/online?icq={0}&img=5".FormatWith(userData.Profile.ICQ); } }
/// <summary> /// Call the Events when the Twitter Login was Successfully /// </summary> /// <param name="newUser"> /// The new user. /// </param> /// <param name="oAuth"> /// The twitter oAUTH. /// </param> /// <param name="userId"> /// The user id. /// </param> /// <param name="user"> /// The user. /// </param> private static void LoginTwitterSuccess( [NotNull] bool newUser, [NotNull] OAuthTwitter oAuth, [NotNull] int userId, [CanBeNull] SitecoreMembershipUser user) { if (newUser) { YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); } else { // Clearing cache with old Active User Lazy Data ... YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(userId)); } // Store Tokens in Session (Could Bes Stored in DB but it would be a Security Problem) YafContext.Current.Get <IYafSession>().TwitterToken = oAuth.Token; YafContext.Current.Get <IYafSession>().TwitterTokenSecret = oAuth.TokenSecret; YafSingleSignOnUser.LoginSuccess(AuthService.twitter, user.UserName, userId, true); }
/// <summary> /// Creates the board in the database. /// </summary> /// <param name="boardName">Name of the board.</param> /// <param name="boardMembershipAppName">Name of the board membership application.</param> /// <param name="boardRolesAppName">Name of the board roles application.</param> /// <param name="langFile">The language file.</param> /// <param name="newAdmin">The new admin.</param> /// <returns></returns> private int DbCreateBoard( string boardName, string boardMembershipAppName, string boardRolesAppName, string langFile, SitecoreMembershipUser newAdmin) { int newBoardID = this.GetRepository <Board>() .Create( boardName, this.Culture.SelectedItem.Value, langFile, boardMembershipAppName, boardRolesAppName, newAdmin.UserName, newAdmin.Email, newAdmin.ProviderUserKey.ToString(), this.PageContext().IsHostAdmin, Config.CreateDistinctRoles && Config.IsAnyPortal ? "YAF " : string.Empty); return(newBoardID); }
/// <summary> /// Migrates the create user. /// </summary> /// <param name="name">The name.</param> /// <param name="email">The email.</param> /// <param name="question">The question.</param> /// <param name="answer">The answer.</param> /// <param name="approved">The approved.</param> /// <param name="user">The user.</param> /// <returns> /// The migrate create user. /// </returns> private static MembershipCreateStatus MigrateCreateUser( [NotNull] string name, [NotNull] string email, [NotNull] string question, [NotNull] string answer, bool approved, [NotNull] out SitecoreMembershipUser user) { MembershipCreateStatus status; // create a new user and generate a password. int retry = 0; do { string password = Membership.GeneratePassword(7 + retry, 1 + retry); user = YafContext.Current.Get <MembershipProvider>() .CreateUser(name, password, email, question, answer, approved, null, out status).ToType <SitecoreMembershipUser>(); }while (status == MembershipCreateStatus.InvalidPassword && ++retry < 10); return(status); }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { // get user data... SitecoreMembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserID); if (user == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } string displayName = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); // get full user data... var userData = new CombinedUserDataHelper(user, this.UserID); this.Msg.NavigateUrl = "msnim:chat?contact={0}".FormatWith(userData.Profile.MSN); // Msg.Attributes.Add( "onclick", "return skypeCheck();" ); this.Img.Src = "http://messenger.services.live.com/users/{0}/presenceimage".FormatWith(userData.Profile.MSN); } }
/// <summary> /// Send an Email to the Newly Created User with /// his Account Info (Pass, Security Question and Answer) /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="pass"> /// The pass. /// </param> /// <param name="securityAnswer"> /// The security answer. /// </param> /// <param name="templateName"> /// The template Name. /// </param> public void SendRegistrationNotificationToUser( [NotNull] SitecoreMembershipUser user, [NotNull] string pass, [NotNull] string securityAnswer, string templateName) { var notifyUser = new YafTemplateEmail(); var subject = this.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_NEW_FACEBOOK_USER_SUBJECT") .FormatWith(YafContext.Current.Get <YafBoardSettings>().Name); notifyUser.TemplateParams["{user}"] = user.UserName; notifyUser.TemplateParams["{email}"] = user.Email; notifyUser.TemplateParams["{pass}"] = pass; notifyUser.TemplateParams["{answer}"] = securityAnswer; notifyUser.TemplateParams["{forumname}"] = this.BoardSettings.Name; var emailBody = notifyUser.ProcessTemplate(templateName); this.GetRepository <Mail>().Create(this.BoardSettings.ForumEmail, user.Email, subject, emailBody); }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { // get user data... SitecoreMembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserID); if (user == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } string displayName = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); // get full user data... var userData = new CombinedUserDataHelper(user, this.UserID); this.Img.Src = "http://opi.yahoo.com/online?u={0}&m=g&t=2".FormatWith(userData.Profile.YIM); this.Msg.NavigateUrl = "http://edit.yahoo.com/config/send_webmesg?.target={0}&.src=pg".FormatWith(userData.Profile.YIM); } }
/// <summary> /// The page_ load. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.User == null) { YafBuildLink.AccessDenied(); } if (!this.IsPostBack) { // get user data... SitecoreMembershipUser user = new SitecoreMembershipUser(this.User); if (user == null) { YafBuildLink.AccessDenied(/*No such user exists*/); } string displayName = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); this.PageLinks.AddLink( this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName, YafBuildLink.GetLink( ForumPages.profile, "u={0}&name={1}", this.UserID, this.PageContext.BoardSettings.EnableDisplayName ? displayName : user.UserName)); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); // get full user data... var userData = new CombinedUserDataHelper(user, this.UserID); this.Msg.NavigateUrl = "aim:goim?screenname={0}&message=Hi.+Are+you+there?".FormatWith(userData.Profile.AIM); this.Buddy.NavigateUrl = "aim:addbuddy?screenname={0}".FormatWith(userData.Profile.AIM); } }
/// <summary> /// The send_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Send_Click([NotNull] object sender, [NotNull] EventArgs e) { try { // get "to" user... SitecoreMembershipUser toUser = UserMembershipHelper.GetMembershipUserById(this.UserID); // send it... this.Get <ISendMail>().Send( new MailAddress(this.PageContext.User.Email, this.PageContext.User.UserName), new MailAddress(toUser.Email.Trim(), toUser.UserName.Trim()), this.Subject.Text.Trim(), this.Body.Text.Trim()); // redirect to profile page... YafBuildLink.Redirect(ForumPages.profile, false, "u={0}", this.UserID); } catch (Exception x) { this.Logger.Log(this.PageContext.PageUserID, this, x); this.PageContext.AddLoadMessage(this.PageContext.IsAdmin ? x.Message : this.GetText("ERROR")); } }
/// <summary> /// Setups the user profile. /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="userId"> /// The user identifier. /// </param> private void SetupUserProfile(SitecoreMembershipUser user, int userId) { // this is the "Profile Information" step. Save the data to their profile (+ defaults). var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones"); var country = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("Country"); var locationTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Location"); var homepageTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Homepage"); var dstUser = (CheckBox)this.CreateUserWizard1.FindWizardControlRecursive("DSTUser"); // setup/save the profile YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); if (country.SelectedValue != null) { userProfile.Country = country.SelectedValue; } string result; if (this.Get <ISpamWordCheck>().CheckForSpamWord(homepageTextBox.Text.Trim(), out result)) { this.IsPossibleSpamBotInternalCheck = true; var userIpAddress = this.Get <HttpRequestBase>().GetUserRealIPAddress(); if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot this.IsPossibleSpamBot = true; this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userId); } else if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { // Kill user UserMembershipHelper.DeleteAndBanUser(userId, user, userIpAddress); this.PageContext.AddLoadMessage(this.GetText("BOT_MESSAGE"), MessageTypes.Error); } this.Logger.Log( null, "Bot Detected", "Internal Spam Word Check detected a SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}') reason word: {3}" .FormatWith(user.UserName, this.CreateUserWizard1.Email, userIpAddress, homepageTextBox.Text.Trim()), EventLogTypes.SpamBotDetected); } if (!this.IsPossibleSpamBotInternalCheck) { userProfile.Location = locationTextBox.Text.Trim(); // add http:// by default if (!Regex.IsMatch(homepageTextBox.Text.Trim(), @"^(http|https|ftp|ftps|git|svn|news)\://.*")) { homepageTextBox.Text = "http://{0}".FormatWith(homepageTextBox.Text.Trim()); } if (ValidationHelper.IsValidURL(homepageTextBox.Text)) { userProfile.Homepage = homepageTextBox.Text.Trim(); } userProfile.Save(); // save the time zone... LegacyDb.user_save( userID: userId, boardID: this.PageContext.PageBoardID, userName: null, displayName: null, email: null, timeZone: timeZones.SelectedValue.ToType <int>(), languageFile: null, culture: null, themeFile: null, textEditor: null, useMobileTheme: null, approved: null, pmNotification: null, autoWatchTopics: null, dSTUser: dstUser.Checked, hideUser: null, notificationType: null); var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); } }
/// <summary> /// Initializes a new instance of the <see cref="CombinedUserDataHelper"/> class. /// </summary> /// <param name="SitecoreMembershipUser"> /// The membership user. /// </param> public CombinedUserDataHelper(SitecoreMembershipUser SitecoreMembershipUser) : this(SitecoreMembershipUser, UserMembershipHelper.GetUserIDFromProviderUserKey(SitecoreMembershipUser.ProviderUserKey)) { }
/// <summary> /// Initializes a new instance of the <see cref="CombinedUserDataHelper"/> class. /// </summary> /// <param name="SitecoreMembershipUser"> /// The membership user. /// </param> /// <param name="userID"> /// The user id. /// </param> public CombinedUserDataHelper(SitecoreMembershipUser SitecoreMembershipUser, int userID) { this._userId = userID; this.SitecoreMembershipUser = SitecoreMembershipUser; this.InitUserData(); }
public static IUserData GetUserData([NotNull] this SitecoreMembershipUser SitecoreMembershipUser) { CodeContracts.VerifyNotNull(SitecoreMembershipUser, "SitecoreMembershipUser"); return(new CombinedUserDataHelper(SitecoreMembershipUser)); }
private static void MigrateUsersFromDataTable(bool approved, [NotNull] DataTable dataTable) { // is this the Yaf membership provider? bool isYafProvider = YafContext.Current.Get <MembershipProvider>().Name == "YafMembershipProvider"; bool isLegacyYafDB = dataTable.Columns.Contains("Location"); var userRows = dataTable.AsEnumerable(); Parallel.ForEach( userRows, row => { // skip the guest user if (row.Field <bool>("IsGuest")) { return; } // validate that name and email are available... if (row["Name"].IsNullOrEmptyDBField() || row["Email"].IsNullOrEmptyDBField()) { return; } string name = row.Field <string>("Name").Trim(); string email = row.Field <string>("Email").ToLower().Trim(); // clean up the name by removing commas... name = name.Replace(",", string.Empty); // verify this user & email are not empty if (!name.IsSet() || !email.IsSet()) { return; } SitecoreMembershipUser user = UserMembershipHelper.GetUser(name, false); if (user == null) { MembershipCreateStatus status = MigrateCreateUser( name, email, "Your email in all lower case", email, approved, out user); if (status != MembershipCreateStatus.Success) { YafContext.Current.Get <ILogger>() .Log(0, "MigrateUsers", "Failed to create user {0}: {1}".FormatWith(name, status)); } else { // update the YAF table with the ProviderKey -- update the provider table if this is the YAF provider... LegacyDb.user_migrate(row["UserID"], user.ProviderUserKey, isYafProvider); user.Comment = "Migrated from YetAnotherForum.NET"; YafContext.Current.Get <MembershipProvider>().UpdateUser(user); if (!isYafProvider) { /* Email generated password to user * System.Text.StringBuilder msg = new System.Text.StringBuilder(); * msg.AppendFormat( "Hello {0}.\r\n\r\n", name ); * msg.AppendFormat( "Here is your new password: {0}\r\n\r\n", password ); * msg.AppendFormat( "Visit {0} at {1}", ForumName, ForumURL ); * * YAF.Classes.Data.DB.mail_create( ForumEmail, user.Email, "Forum Upgrade", msg.ToString() ); */ } } if (isLegacyYafDB) { // copy profile data over... YafUserProfile userProfile = YafUserProfile.GetProfile(name); if (dataTable.Columns.Contains("AIM") && !row["AIM"].IsNullOrEmptyDBField()) { userProfile.AIM = row["AIM"].ToString(); } if (dataTable.Columns.Contains("YIM") && !row["YIM"].IsNullOrEmptyDBField()) { userProfile.YIM = row["YIM"].ToString(); } if (dataTable.Columns.Contains("MSN") && !row["MSN"].IsNullOrEmptyDBField()) { userProfile.MSN = row["MSN"].ToString(); } if (dataTable.Columns.Contains("ICQ") && !row["ICQ"].IsNullOrEmptyDBField()) { userProfile.ICQ = row["ICQ"].ToString(); } if (dataTable.Columns.Contains("RealName") && !row["RealName"].IsNullOrEmptyDBField()) { userProfile.RealName = row["RealName"].ToString(); } if (dataTable.Columns.Contains("Occupation") && !row["Occupation"].IsNullOrEmptyDBField()) { userProfile.Occupation = row["Occupation"].ToString(); } if (dataTable.Columns.Contains("Location") && !row["Location"].IsNullOrEmptyDBField()) { userProfile.Location = row["Location"].ToString(); } if (dataTable.Columns.Contains("Homepage") && !row["Homepage"].IsNullOrEmptyDBField()) { userProfile.Homepage = row["Homepage"].ToString(); } if (dataTable.Columns.Contains("Interests") && !row["Interests"].IsNullOrEmptyDBField()) { userProfile.Interests = row["Interests"].ToString(); } if (dataTable.Columns.Contains("Weblog") && !row["Weblog"].IsNullOrEmptyDBField()) { userProfile.Blog = row["Weblog"].ToString(); } if (dataTable.Columns.Contains("Gender") && !row["Gender"].IsNullOrEmptyDBField()) { userProfile.Gender = row["Gender"].ToType <int>(); } userProfile.Save(); } } else { // just update the link just in case... LegacyDb.user_migrate(row["UserID"], user.ProviderUserKey, false); } // setup roles for this user... using (DataTable dtGroups = LegacyDb.usergroup_list(row["UserID"])) { foreach (DataRow rowGroup in dtGroups.Rows) { AddUserToRole(user.UserName, rowGroup["Name"].ToString()); } } }); }
/// <summary> /// The create users. /// </summary> /// <param name="boardID"> /// The board id. /// </param> /// <param name="_users_Number"> /// The _users_ number. /// </param> /// <param name="_outCounter"> /// The _out counter. /// </param> /// <param name="_countLimit"> /// The _count limit. /// </param> /// <param name="_excludeCurrentBoard"> /// The _exclude current board. /// </param> /// <returns> /// The string with number of created users. /// </returns> private string CreateUsers( int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard) { int iboards; // if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit; for (iboards = 0; iboards < _countLimit; iboards++) { boardID = this.UsersBoardsList.Items[iboards].Value.ToType <int>(); int i; for (i = 0; i < this.UsersNumber.Text.Trim().ToType <int>(); i++) { this.randomGuid = Guid.NewGuid().ToString(); string newEmail = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info"; string newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid; if (UserMembershipHelper.UserExists(newUsername, newEmail)) { continue; } string hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20); string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); MembershipCreateStatus status; SitecoreMembershipUser user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <YafBoardSettings>().EmailVerification, null, out status).ToType <SitecoreMembershipUser>(); if (status != MembershipCreateStatus.Success) { continue; } // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(boardID, newUsername); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, boardID); // create profile YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername); // setup their inital profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); // save the time zone... if ( !(this.UsersBoardsList.Items[iboards].Value.ToType <int>() == YafContext.Current.PageBoardID && _excludeCurrentBoard)) { LegacyDb.user_save( LegacyDb.user_get(boardID, user.ProviderUserKey), boardID, null, null, null, this.TimeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, null, null, null, null, null); _outCounter++; } } } return(_outCounter + " Users in " + iboards + " Board(s); "); }
/// <summary> /// Deletes and ban's the user. /// </summary> /// <param name="userID">The user id.</param> /// <param name="user">The MemberShip User.</param> /// <param name="userIpAddress">The user's IP address.</param> /// <returns> /// Returns if Deleting was successfully /// </returns> public static bool DeleteAndBanUser(int userID, SitecoreMembershipUser user, string userIpAddress) { // Ban IP ? if (YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection) { YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), userID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( userID, "IP BAN of Bot", "A spam Bot who was banned by IP {0}".FormatWith(userIpAddress), EventLogTypes.IpBanSet); } } // Ban Name ? YafContext.Current.GetRepository <BannedName>() .Save(null, user.UserName, "Name was reported by the automatic spam system."); // Ban User Email? YafContext.Current.GetRepository <BannedEmail>() .Save(null, user.Email, "Email was reported by the automatic spam system."); // Delete the images/albums both from database and physically. var uploadDir = HttpContext.Current.Server.MapPath( string.Concat(BaseUrlBuilder.ServerFileRoot, YafBoardFolders.Current.Uploads)); using (DataTable dt = LegacyDb.album_list(userID, null)) { foreach (DataRow dr in dt.Rows) { YafAlbum.Album_Image_Delete(uploadDir, dr["AlbumID"], userID, null); } } YafContext.Current.Get <MembershipProvider>().DeleteUser(user.UserName, true); LegacyDb.user_delete(userID); YafContext.Current.Get <ILogger>() .Log( YafContext.Current.PageUserID, "UserMembershipHelper.DeleteUser", "User {0} was deleted by the automatic spam check system.".FormatWith(user.UserName), EventLogTypes.UserDeleted); // clear the cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.UsersOnlineStatus); YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BoardUserStats); YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.UsersDisplayNameCollection); return(true); }
/// <summary> /// Creates the user in the YAF DB from the ASP.NET Membership user information. /// Also copies the Roles as groups into YAF DB for the current user /// </summary> /// <param name="user"> /// Current Membership User /// </param> /// <param name="pageBoardID"> /// Current BoardID /// </param> /// <returns> /// Returns the UserID of the user if everything was successful. Otherwise, null. /// </returns> public static int?CreateForumUser([NotNull] SitecoreMembershipUser user, int pageBoardID) { return(CreateForumUser(user, user.UserName, pageBoardID)); }