private static void CreateYAFUser(string sUsername, string sPassword, string email) { if (!UserMembershipHelper.UserExists(sUsername, email)) { YafMembershipProvider mb = (YafMembershipProvider)System.Web.Security.Membership.Providers["YafMembershipProvider"]; int?forumUserID = 0; if (!mb.ValidateUser(sUsername, sPassword)) { MembershipCreateStatus status; MembershipUser forumUser = mb.CreateUser(sUsername, sPassword, email, "question", "answer", true, null, out status); // create the user in the YAF DB as well as sync roles... forumUserID = RoleMembershipHelper.CreateForumUser(forumUser, 1); RoleMembershipHelper.SetupUserRoles(1, sUsername); RoleMembershipHelper.AddUserToRole(sUsername, "Registered"); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(sUsername); userProfile.Homepage = "fwd.com"; // setup their inital profile information userProfile.Save(); } else { return; } } }
/// <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); } }
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { MembershipUser user = Membership.GetUser(CreateUserWizard1.UserName); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, CreateUserWizard1.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = PageContext.GetProfile(CreateUserWizard1.UserName); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... YafBuildLink.Redirect(ForumPages.info, "i=7"); } // handle e-mail verification if needed if (PageContext.BoardSettings.EmailVerification) { // get the user email TextBox emailTextBox = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email"); string email = emailTextBox.Text.Trim(); string hashinput = DateTime.Now.ToString() + email + Security.CreatePassword(20); string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); // save verification record... YAF.Classes.Data.DB.checkemail_save(userID, hash, user.Email); YafTemplateEmail verifyEmail = new YafTemplateEmail("VERIFYEMAIL"); string subject = String.Format(GetText("VERIFICATION_EMAIL_SUBJECT"), PageContext.BoardSettings.Name); verifyEmail.TemplateParams ["{link}"] = String.Format("{1}{0}", YafBuildLink.GetLinkNotEscaped(ForumPages.approve, "k={0}", hash), YafForumInfo.ServerURL); verifyEmail.TemplateParams ["{key}"] = hash; verifyEmail.TemplateParams ["{forumname}"] = PageContext.BoardSettings.Name; verifyEmail.TemplateParams ["{forumlink}"] = String.Format("{0}", YafForumInfo.ForumURL); verifyEmail.SendEmail(new System.Net.Mail.MailAddress(email, user.UserName), subject, true); } }
/// <summary> /// The create user wizard 1_ created user. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { MembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, this.CreateUserWizard1.UserName); string displayName = user.UserName; if (this.PageContext.BoardSettings.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.PageContext.BoardSettings.EmailVerification) { // get the user email this.SendVerificationEmail(user, userID); } if (this.PageContext.BoardSettings.NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.SendRegistrationNotificationEmail(user); } }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser"> /// The Google user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var isPossibleSpamBot = false; var userIpAddress = BoardContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (BoardContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result)) { BoardContext.Current.Get <ILogger>().Log( null, "Bot Detected", $"Bot Check detected a possible SPAM BOT: (user name : '{googleUser.UserName}', email : '{googleUser.Email}', ip: '{userIpAddress}', reason : {result}), user was rejected.", EventLogTypes.SpamBotDetected); if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(2)) { message = BoardContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!BoardContext.Current.Get <BoardSettings>().BanBotIpOnDetection) { return(false); } BoardContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, $"A spam Bot who was trying to register was banned by IP {userIpAddress}", BoardContext.Current.PageUserID); // Clear cache BoardContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (BoardContext.Current.Get <BoardSettings>().LogBannedIP) { BoardContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", $"A spam Bot who was trying to register was banned by IP {userIpAddress}", EventLogTypes.IpBanSet); } return(false); } } var memberShipProvider = BoardContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( googleUser.UserName, pass, googleUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out _); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = Utils.UserProfile.GetProfile(googleUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService) { var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator(); if (userIpLocator != null) { userProfile.Country = userIpLocator["CountryCode"]; var location = new StringBuilder(); if (userIpLocator["RegionName"] != null && userIpLocator["RegionName"].IsSet() && !userIpLocator["RegionName"].Equals("-")) { location.Append(userIpLocator["RegionName"]); } if (userIpLocator["CityName"] != null && userIpLocator["CityName"].IsSet() && !userIpLocator["CityName"].Equals("-")) { location.AppendFormat(", {0}", userIpLocator["CityName"]); } userProfile.Location = location.ToString(); } } userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (BoardContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... BoardContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { BoardContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... BoardContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; BoardContext.Current.GetRepository <User>().Save( userId, BoardContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, TimeZoneInfo.Local.Id, null, null, null, null); // save the settings... BoardContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), BoardContext.Current.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar BoardContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null); BoardContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); BoardContext.Current.Get <ISingeSignOnUser>().LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }
/// <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 <MembershipProvider>().RequiresUniqueEmail) { if (this.Get <MembershipProvider>().GetUserNameByEmail((string)row["Email"]) != null) { return(importCount); } } var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var securityQuestion = "Answer is a generated Pass"; if (row.Table.Columns.Contains("Password") && ((string)row["Password"]).IsSet() && row.Table.Columns.Contains("SecurityQuestion") && ((string)row["SecurityQuestion"]).IsSet() && row.Table.Columns.Contains("SecurityAnswer") && ((string)row["SecurityAnswer"]).IsSet()) { pass = (string)row["Password"]; securityAnswer = (string)row["SecurityAnswer"]; securityQuestion = (string)row["SecurityQuestion"]; } var user = BoardContext.Current.Get <MembershipProvider>().CreateUser( (string)row["Name"], pass, (string)row["Email"], this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null, this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out _); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, (string)row["Name"]); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = Utils.UserProfile.GetProfile((string)row["Name"]); // 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"]; } userProfile.Save(); 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 = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var isDst = false; if (row.Table.Columns.Contains("IsDST") && ((string)row["IsDST"]).IsSet()) { bool.TryParse((string)row["IsDST"], out isDst); } 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, null, null, this.Get <BoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, isDst, null); // save the settings... this.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); importCount++; return(importCount); }
/// <summary> /// Creates the facebook user /// </summary> /// <param name="facebookUser">The facebook user.</param> /// <param name="userGender">The user gender.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateFacebookUser(FacebookUser facebookUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); MembershipUser user = YafContext.Current.Get <MembershipProvider>() .CreateUser( facebookUser.UserName, pass, facebookUser.Email, "Answer is a generated Pass", securityAnswer, true, null, out status); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, facebookUser.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(facebookUser.UserName); userProfile.Facebook = facebookUser.ProfileURL; userProfile.FacebookId = facebookUser.UserID; userProfile.Homepage = facebookUser.ProfileURL; if (facebookUser.Birthday.IsSet()) { DateTime userBirthdate; var ci = CultureInfo.CreateSpecificCulture("en-US"); DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date) { userProfile.Birthday = userBirthdate; } } userProfile.RealName = facebookUser.Name; userProfile.Gender = userGender; if (facebookUser.Location != null && facebookUser.Location.Name.IsSet()) { userProfile.Location = facebookUser.Location.Name; } userProfile.Save(); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafSingleSignOnUser.SendRegistrationNotificationEmail(user); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_FACEBOOK_REGISTER"); // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, facebookUser.UserName, facebookUser.UserName, facebookUser.Email, facebookUser.Timezone, null, null, true, null, null, null, null, null, null, null, null); bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar LegacyDb.user_saveavatar( userId, "https://graph.facebook.com/{0}/picture".FormatWith(facebookUser.UserID), null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true); message = string.Empty; return(true); }
/// <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; MembershipUser 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); 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> /// 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 <MembershipProvider>().RequiresUniqueEmail) { if (this.Get <MembershipProvider>().GetUserNameByEmail((string)row["Email"]) != null) { return(importCount); } } MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var securityQuestion = "Answer is a generated Pass"; if (row.Table.Columns.Contains("Password") && !string.IsNullOrEmpty((string)row["Password"]) && row.Table.Columns.Contains("SecurityQuestion") && !string.IsNullOrEmpty((string)row["SecurityQuestion"]) && row.Table.Columns.Contains("SecurityAnswer") && !string.IsNullOrEmpty((string)row["SecurityAnswer"])) { pass = (string)row["Password"]; securityAnswer = (string)row["SecurityAnswer"]; securityQuestion = (string)row["SecurityQuestion"]; } SitecoreMembershipUser user = YafContext.Current.Get <MembershipProvider>().CreateUser( (string)row["Name"], pass, (string)row["Email"], securityQuestion, securityAnswer, true, null, out status).ToType <SitecoreMembershipUser>(); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, (string)row["Name"]); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile((string)row["Name"]); // Add Profile Fields to User List Table. if (row.Table.Columns.Contains("RealName") && !string.IsNullOrEmpty((string)row["RealName"])) { userProfile.RealName = (string)row["RealName"]; } if (row.Table.Columns.Contains("Blog") && !string.IsNullOrEmpty((string)row["Blog"])) { userProfile.Blog = (string)row["Blog"]; } if (row.Table.Columns.Contains("Gender") && !string.IsNullOrEmpty((string)row["Gender"])) { int gender; int.TryParse((string)row["Gender"], out gender); userProfile.Gender = gender; } if (row.Table.Columns.Contains("Birthday") && !string.IsNullOrEmpty((string)row["Birthday"])) { DateTime userBirthdate; DateTime.TryParse((string)row["Birthday"], out userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime()) { userProfile.Birthday = userBirthdate; } } if (row.Table.Columns.Contains("MSN") && !string.IsNullOrEmpty((string)row["MSN"])) { userProfile.MSN = (string)row["MSN"]; } if (row.Table.Columns.Contains("BlogServiceUsername") && !string.IsNullOrEmpty((string)row["BlogServiceUsername"])) { userProfile.BlogServiceUsername = (string)row["BlogServiceUsername"]; } if (row.Table.Columns.Contains("BlogServicePassword") && !string.IsNullOrEmpty((string)row["BlogServicePassword"])) { userProfile.BlogServicePassword = (string)row["BlogServicePassword"]; } if (row.Table.Columns.Contains("AIM") && !string.IsNullOrEmpty((string)row["AIM"])) { userProfile.AIM = (string)row["AIM"]; } if (row.Table.Columns.Contains("Google") && !string.IsNullOrEmpty((string)row["Google"])) { userProfile.Google = (string)row["Google"]; } if (row.Table.Columns.Contains("GoogleId") && !string.IsNullOrEmpty((string)row["GoogleId"])) { userProfile.GoogleId = (string)row["GoogleId"]; } if (row.Table.Columns.Contains("Location") && !string.IsNullOrEmpty((string)row["Location"])) { userProfile.Location = (string)row["Location"]; } if (row.Table.Columns.Contains("Country") && !string.IsNullOrEmpty((string)row["Country"])) { userProfile.Country = (string)row["Country"]; } if (row.Table.Columns.Contains("Region") && !string.IsNullOrEmpty((string)row["Region"])) { userProfile.Region = (string)row["Region"]; } if (row.Table.Columns.Contains("City") && !string.IsNullOrEmpty((string)row["City"])) { userProfile.City = (string)row["City"]; } if (row.Table.Columns.Contains("Interests") && !string.IsNullOrEmpty((string)row["Interests"])) { userProfile.Interests = (string)row["Interests"]; } if (row.Table.Columns.Contains("Homepage") && !string.IsNullOrEmpty((string)row["Homepage"])) { userProfile.Homepage = (string)row["Homepage"]; } if (row.Table.Columns.Contains("Skype") && !string.IsNullOrEmpty((string)row["Skype"])) { userProfile.Skype = (string)row["Skype"]; } if (row.Table.Columns.Contains("ICQe") && !string.IsNullOrEmpty((string)row["ICQ"])) { userProfile.ICQ = (string)row["ICQ"]; } if (row.Table.Columns.Contains("XMPP") && !string.IsNullOrEmpty((string)row["XMPP"])) { userProfile.XMPP = (string)row["XMPP"]; } if (row.Table.Columns.Contains("YIM") && !string.IsNullOrEmpty((string)row["YIM"])) { userProfile.YIM = (string)row["YIM"]; } if (row.Table.Columns.Contains("Occupation") && !string.IsNullOrEmpty((string)row["Occupation"])) { userProfile.Occupation = (string)row["Occupation"]; } if (row.Table.Columns.Contains("Twitter") && !string.IsNullOrEmpty((string)row["Twitter"])) { userProfile.Twitter = (string)row["Twitter"]; } if (row.Table.Columns.Contains("TwitterId") && !string.IsNullOrEmpty((string)row["TwitterId"])) { userProfile.TwitterId = (string)row["TwitterId"]; } if (row.Table.Columns.Contains("Facebook") && !string.IsNullOrEmpty((string)row["Facebook"])) { userProfile.Facebook = (string)row["Facebook"]; } if (row.Table.Columns.Contains("FacebookId") && !string.IsNullOrEmpty((string)row["FacebookId"])) { userProfile.FacebookId = (string)row["FacebookId"]; } userProfile.Save(); 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... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); bool isDST = false; if (row.Table.Columns.Contains("IsDST") && !string.IsNullOrEmpty((string)row["IsDST"])) { bool.TryParse((string)row["IsDST"], out isDST); } int timeZone = 0; if (row.Table.Columns.Contains("Timezone") && !string.IsNullOrEmpty((string)row["Timezone"])) { int.TryParse((string)row["Timezone"], out timeZone); } LegacyDb.user_save( userId, YafContext.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, row.Table.Columns.Contains("TextEditor") ? row["TextEditor"] : null, null, null, null, null, isDST, null, null); bool autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); importCount++; return(importCount); }
/// <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 <MembershipProvider>().RequiresUniqueEmail) { if (this.Get <MembershipProvider>().GetUserNameByEmail(email: (string)row[columnName: "Email"]) != null) { return(importCount); } } MembershipCreateStatus status; var pass = Membership.GeneratePassword(length: 32, numberOfNonAlphanumericCharacters: 16); var securityAnswer = Membership.GeneratePassword(length: 64, numberOfNonAlphanumericCharacters: 30); var securityQuestion = "Answer is a generated Pass"; if (row.Table.Columns.Contains(name: "Password") && ((string)row[columnName : "Password"]).IsSet() && row.Table.Columns.Contains(name : "SecurityQuestion") && ((string)row[columnName : "SecurityQuestion"]).IsSet() && row.Table.Columns.Contains(name : "SecurityAnswer") && ((string)row[columnName : "SecurityAnswer"]).IsSet()) { pass = (string)row[columnName : "Password"]; securityAnswer = (string)row[columnName : "SecurityAnswer"]; securityQuestion = (string)row[columnName : "SecurityQuestion"]; } var user = YafContext.Current.Get <MembershipProvider>().CreateUser( username: (string)row[columnName: "Name"], password: pass, email: (string)row[columnName: "Email"], passwordQuestion: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null, passwordAnswer: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null, isApproved: true, providerUserKey: null, status: out status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(pageBoardID: YafContext.Current.PageBoardID, userName: (string)row[columnName: "Name"]); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user: user, pageBoardID: YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(userName: (string)row[columnName: "Name"]); // Add Profile Fields to User List Table. if (row.Table.Columns.Contains(name: "RealName") && ((string)row[columnName : "RealName"]).IsSet()) { userProfile.RealName = (string)row[columnName : "RealName"]; } if (row.Table.Columns.Contains(name: "Blog") && ((string)row[columnName : "Blog"]).IsSet()) { userProfile.Blog = (string)row[columnName : "Blog"]; } if (row.Table.Columns.Contains(name: "Gender") && ((string)row[columnName : "Gender"]).IsSet()) { int gender; int.TryParse(s: (string)row[columnName: "Gender"], result: out gender); userProfile.Gender = gender; } if (row.Table.Columns.Contains(name: "Birthday") && ((string)row[columnName : "Birthday"]).IsSet()) { DateTime userBirthdate; DateTime.TryParse(s: (string)row[columnName: "Birthday"], result: out userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime()) { userProfile.Birthday = userBirthdate; } } if (row.Table.Columns.Contains(name: "BlogServiceUsername") && ((string)row[columnName : "BlogServiceUsername"]).IsSet()) { userProfile.BlogServiceUsername = (string)row[columnName : "BlogServiceUsername"]; } if (row.Table.Columns.Contains(name: "BlogServicePassword") && ((string)row[columnName : "BlogServicePassword"]).IsSet()) { userProfile.BlogServicePassword = (string)row[columnName : "BlogServicePassword"]; } if (row.Table.Columns.Contains(name: "GoogleId") && ((string)row[columnName : "GoogleId"]).IsSet()) { userProfile.GoogleId = (string)row[columnName : "GoogleId"]; } if (row.Table.Columns.Contains(name: "Location") && ((string)row[columnName : "Location"]).IsSet()) { userProfile.Location = (string)row[columnName : "Location"]; } if (row.Table.Columns.Contains(name: "Country") && ((string)row[columnName : "Country"]).IsSet()) { userProfile.Country = (string)row[columnName : "Country"]; } if (row.Table.Columns.Contains(name: "Region") && ((string)row[columnName : "Region"]).IsSet()) { userProfile.Region = (string)row[columnName : "Region"]; } if (row.Table.Columns.Contains(name: "City") && ((string)row[columnName : "City"]).IsSet()) { userProfile.City = (string)row[columnName : "City"]; } if (row.Table.Columns.Contains(name: "Interests") && ((string)row[columnName : "Interests"]).IsSet()) { userProfile.Interests = (string)row[columnName : "Interests"]; } if (row.Table.Columns.Contains(name: "Homepage") && ((string)row[columnName : "Homepage"]).IsSet()) { userProfile.Homepage = (string)row[columnName : "Homepage"]; } if (row.Table.Columns.Contains(name: "Skype") && ((string)row[columnName : "Skype"]).IsSet()) { userProfile.Skype = (string)row[columnName : "Skype"]; } if (row.Table.Columns.Contains(name: "ICQe") && ((string)row[columnName : "ICQ"]).IsSet()) { userProfile.ICQ = (string)row[columnName : "ICQ"]; } if (row.Table.Columns.Contains(name: "XMPP") && ((string)row[columnName : "XMPP"]).IsSet()) { userProfile.XMPP = (string)row[columnName : "XMPP"]; } if (row.Table.Columns.Contains(name: "Occupation") && ((string)row[columnName : "Occupation"]).IsSet()) { userProfile.Occupation = (string)row[columnName : "Occupation"]; } if (row.Table.Columns.Contains(name: "Twitter") && ((string)row[columnName : "Twitter"]).IsSet()) { userProfile.Twitter = (string)row[columnName : "Twitter"]; } if (row.Table.Columns.Contains(name: "TwitterId") && ((string)row[columnName : "TwitterId"]).IsSet()) { userProfile.TwitterId = (string)row[columnName : "TwitterId"]; } if (row.Table.Columns.Contains(name: "Facebook") && ((string)row[columnName : "Facebook"]).IsSet()) { userProfile.Facebook = (string)row[columnName : "Facebook"]; } if (row.Table.Columns.Contains(name: "FacebookId") && ((string)row[columnName : "FacebookId"]).IsSet()) { userProfile.FacebookId = (string)row[columnName : "FacebookId"]; } userProfile.Save(); 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: user, pass: pass, securityAnswer: securityAnswer, templateName: "NOTIFICATION_ON_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(providerUserKey: user.ProviderUserKey); var isDst = false; if (row.Table.Columns.Contains(name: "IsDST") && ((string)row[columnName : "IsDST"]).IsSet()) { bool.TryParse(value : (string)row[columnName : "IsDST"], result : out isDst); } var timeZone = 0; if (row.Table.Columns.Contains(name: "Timezone") && ((string)row[columnName : "Timezone"]).IsSet()) { int.TryParse(s : (string)row[columnName : "Timezone"], result : out timeZone); } var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; this.GetRepository <User>().Save( userID: userId, boardID: YafContext.Current.PageBoardID, userName: row[columnName: "Name"], displayName: row.Table.Columns.Contains(name: "DisplayName") ? row[columnName: "DisplayName"] : null, email: row[columnName: "Email"], timeZone: timeZone, languageFile: row.Table.Columns.Contains(name: "LanguageFile") ? row[columnName: "LanguageFile"] : null, culture: row.Table.Columns.Contains(name: "Culture") ? row[columnName: "Culture"] : null, themeFile: row.Table.Columns.Contains(name: "ThemeFile") ? row[columnName: "ThemeFile"] : null, textEditor: row.Table.Columns.Contains(name: "TextEditor") ? row[columnName: "TextEditor"] : null, approved: null, pmNotification: null, autoWatchTopics: this.Get <YafBoardSettings>().DefaultNotificationSetting, dSTUser: autoWatchTopicsEnabled, hideUser: isDst, notificationType: null, null); // save the settings... this.GetRepository <User>().SaveNotification( userID: userId, pmNotification: true, autoWatchTopics: autoWatchTopicsEnabled, notificationType: this.Get <YafBoardSettings>().DefaultNotificationSetting, dailyDigest: this.Get <YafBoardSettings>().DefaultSendDigestEmail); importCount++; return(importCount); }
/// <summary> /// Creates the or assign twitter user. /// </summary> /// <param name="twitterUser">The twitter user.</param> /// <param name="oAuth">The oAUTH.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Create User if not exists?! Doesnt work because there is no Email var email = "{0}@twitter.com".FormatWith(twitterUser.UserName); // Check user for bot /*var spamChecker = new YafSpamCheck(); * string result; * var isPossibleSpamBot = false; * * var userIpAddress = YafContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress(); * * // Check content for spam * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result)) * { * YafContext.Current.Get<ILogger>().Log( * null, * "Bot Detected", * "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." * .FormatWith(twitterUser.UserName, twitterUser.Email, userIpAddress, result), * EventLogTypes.SpamBotDetected); * * if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(1)) * { * // Flag user as spam bot * isPossibleSpamBot = true; * } * else if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(2)) * { * message = YafContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE"); * * if (!YafContext.Current.Get<YafBoardSettings>().BanBotIpOnDetection) * { * return false; * } * * YafContext.Current.GetRepository<BannedIP>() * .Save( * null, * userIpAddress, * "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), * YafContext.Current.PageUserID); * * // Clear cache * YafContext.Current.Get<IDataCache>().Remove(Constants.Cache.BannedIP); * * if (YafContext.Current.Get<YafBoardSettings>().LogBannedIP) * { * YafContext.Current.Get<ILogger>() * .Log( * null, * "IP BAN of Bot During Registration", * "A spam Bot who was trying to register was banned by IP {0}".FormatWith( * userIpAddress), * EventLogTypes.IpBanSet); * } * * return false; * } * }*/ // Create User if not exists?! MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); MembershipUser user = YafContext.Current.Get <MembershipProvider>() .CreateUser( twitterUser.UserName, pass, email, "Answer is a generated Pass", securityAnswer, true, null, out status); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(twitterUser.UserName); userProfile.TwitterId = twitterUser.UserId.ToString(); userProfile.Twitter = twitterUser.UserName; userProfile.Homepage = twitterUser.Url.IsSet() ? twitterUser.Url : "http://twitter.com/{0}".FormatWith(twitterUser.UserName); userProfile.RealName = twitterUser.Name; userProfile.Interests = twitterUser.Description; userProfile.Location = twitterUser.Location; userProfile.Save(); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafSingleSignOnUser.SendRegistrationNotificationEmail(user, userID.Value); } // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); // send user register notification to the following admin users... SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, twitterUser.UserName, null, email, 0, null, null, null, null, null, null, null, null, null, null, null); bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar if (twitterUser.ProfileImageUrl.IsSet()) { LegacyDb.user_saveavatar(userId, twitterUser.ProfileImageUrl, null, null); } LoginTwitterSuccess(true, oAuth, userId, user); message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL"); 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 (UserMembershipHelper.UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS"), MessageTypes.danger); return; } var user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <BoardSettings>().EmailVerification, null, out var status); if (status != MembershipCreateStatus.Success) { // error of some kind this.PageContext.AddLoadMessage( this.GetTextFormatted("MSG_ERROR_CREATE", status), MessageTypes.danger); return; } // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, newUsername); // create the user in the YAF DB as well as sync roles... var userId = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create profile var userProfile = Utils.UserProfile.GetProfile(newUsername); // setup their initial profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting .Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // save the time zone... this.GetRepository <User>().Save( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), 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( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), 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> /// Creates the YAF user. /// </summary> /// <param name="dnnUserInfo">The DNN user info.</param> /// <param name="dnnUser">The DNN user.</param> /// <param name="boardID">The board ID.</param> /// <param name="portalID">The portal identifier.</param> /// <param name="boardSettings">The board settings.</param> /// <returns> /// Returns the User ID of the new User /// </returns> public static int CreateYafUser( UserInfo dnnUserInfo, MembershipUser dnnUser, int boardID, int portalID, YafBoardSettings boardSettings) { // setup roles RoleMembershipHelper.SetupUserRoles(boardID, dnnUser.UserName); // create the user in the YAF DB so profile can gets created... var yafUserId = RoleMembershipHelper.CreateForumUser(dnnUser, dnnUserInfo.DisplayName, boardID); if (yafUserId == null) { return(0); } // create profile var userProfile = YafUserProfile.GetProfile(dnnUser.UserName); // setup their initial profile information userProfile.Initialize(dnnUser.UserName, true); if (dnnUserInfo.Profile.FullName.IsSet()) { userProfile.RealName = dnnUserInfo.Profile.FullName; } if (dnnUserInfo.Profile.Country.IsSet() && !dnnUserInfo.Profile.Country.Equals("N/A")) { var regionInfo = ProfileSyncronizer.GetRegionInfoFromCountryName(dnnUserInfo.Profile.Country); if (regionInfo != null) { userProfile.Country = regionInfo.TwoLetterISORegionName; } } if (dnnUserInfo.Profile.City.IsSet()) { userProfile.City = dnnUserInfo.Profile.City; } if (dnnUserInfo.Profile.Website.IsSet()) { userProfile.Homepage = dnnUserInfo.Profile.Website; } userProfile.Save(); // Save User LegacyDb.user_save( yafUserId, boardID, dnnUserInfo.Username, dnnUserInfo.DisplayName, dnnUserInfo.Email, 0, null, null, null, null, null, null, null, null, null, null, null); var autoWatchTopicsEnabled = boardSettings.DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // save notification Settings LegacyDb.user_savenotification( yafUserId, true, autoWatchTopicsEnabled, boardSettings.DefaultNotificationSetting, boardSettings.DefaultSendDigestEmail); RoleSyncronizer.SynchronizeUserRoles(boardID, portalID, yafUserId.ToType <int>(), dnnUserInfo); return(yafUserId.ToType <int>()); }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser">The Google user.</param> /// <param name="userGender">The user gender.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); MembershipUser user = YafContext.Current.Get <MembershipProvider>() .CreateUser( googleUser.UserName, pass, googleUser.Email, "Answer is a generated Pass", securityAnswer, true, null, out status); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(googleUser.UserName); userProfile.Google = googleUser.ProfileURL; userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; userProfile.Save(); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafSingleSignOnUser.SendRegistrationNotificationEmail(user, userID.Value); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, 0, null, null, true, null, null, null, null, null, null, null, null); bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar LegacyDb.user_saveavatar(userId, googleUser.ProfileImage, null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }
/// <summary> /// Creates the YAF user. /// </summary> /// <param name="dnnUserInfo">The DNN user info.</param> /// <param name="dnnUser">The DNN user.</param> /// <param name="boardId">The board ID.</param> /// <param name="portalId">The portal identifier.</param> /// <param name="boardSettings">The board settings.</param> /// <returns> /// Returns the User ID of the new User /// </returns> public static int CreateYafUser( UserInfo dnnUserInfo, MembershipUser dnnUser, int boardId, int portalId, YafBoardSettings boardSettings) { // setup roles RoleMembershipHelper.SetupUserRoles(boardId, dnnUser.UserName); // create the user in the YAF DB so profile can gets created... var yafUserId = RoleMembershipHelper.CreateForumUser(dnnUser, dnnUserInfo.DisplayName, boardId); if (yafUserId == null) { return(0); } // create profile var userProfile = YafUserProfile.GetProfile(dnnUser.UserName); // setup their initial profile information userProfile.Initialize(dnnUser.UserName, true); if (dnnUserInfo.Profile.FullName.IsSet()) { userProfile.RealName = dnnUserInfo.Profile.FullName; } if (dnnUserInfo.Profile.Country.IsSet() && !dnnUserInfo.Profile.Country.Equals("N/A")) { var regionInfo = ProfileSyncronizer.GetRegionInfoFromCountryName(dnnUserInfo.Profile.Country); if (regionInfo != null) { userProfile.Country = regionInfo.TwoLetterISORegionName; } } if (dnnUserInfo.Profile.City.IsSet()) { userProfile.City = dnnUserInfo.Profile.City; } if (dnnUserInfo.Profile.Website.IsSet()) { userProfile.Homepage = dnnUserInfo.Profile.Website; } userProfile.Save(); var autoWatchTopicsEnabled = boardSettings.DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // Save User LegacyDb.user_save( userID: yafUserId, boardID: boardId, userName: dnnUserInfo.Username, displayName: dnnUserInfo.DisplayName, email: dnnUserInfo.Email, timeZone: dnnUserInfo.Profile.PreferredTimeZone.Id, languageFile: null, culture: null, themeFile: null, textEditor: null, useMobileTheme: null, approved: null, pmNotification: boardSettings.DefaultNotificationSetting, autoWatchTopics: autoWatchTopicsEnabled, dSTUser: dnnUserInfo.Profile.PreferredTimeZone.SupportsDaylightSavingTime, hideUser: null, notificationType: null); // save notification Settings LegacyDb.user_savenotification( yafUserId, true, autoWatchTopicsEnabled, boardSettings.DefaultNotificationSetting, boardSettings.DefaultSendDigestEmail); RoleSyncronizer.SynchronizeUserRoles(boardId, portalId, yafUserId.ToType <int>(), dnnUserInfo); return(yafUserId.ToType <int>()); }
/// <summary> /// Creates the or assign twitter user. /// </summary> /// <param name="twitterUser">The twitter user.</param> /// <param name="oAuth">The oAUTH.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Create User if not exists?! Doesnt work because there is no Email var email = "{0}@twitter.com".FormatWith(twitterUser.UserName); // Create User if not exists?! MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); MembershipUser user = YafContext.Current.Get <MembershipProvider>() .CreateUser( twitterUser.UserName, pass, email, "Answer is a generated Pass", securityAnswer, true, null, out status); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(twitterUser.UserName); userProfile.TwitterId = twitterUser.UserId.ToString(); userProfile.Twitter = twitterUser.UserName; userProfile.Homepage = twitterUser.Url.IsSet() ? twitterUser.Url : "http://twitter.com/{0}".FormatWith(twitterUser.UserName); userProfile.RealName = twitterUser.Name; userProfile.Interests = twitterUser.Description; userProfile.Location = twitterUser.Location; userProfile.Save(); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafSingleSignOnUser.SendRegistrationNotificationEmail(user); } // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); // send user register notification to the following admin users... SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, twitterUser.UserName, null, email, 0, null, null, null, null, null, null, null, null, null, null, null); bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar if (twitterUser.ProfileImageUrl.IsSet()) { LegacyDb.user_saveavatar(userId, twitterUser.ProfileImageUrl, null, null); } LoginTwitterSuccess(true, oAuth, userId, user); message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL"); return(true); }
protected void ForumRegister_Click(object sender, System.EventArgs e) { if (Page.IsValid) { string newEmail = Email.Text.Trim(); string newUsername = UserName.Text.Trim(); if (!General.IsValidEmail(newEmail)) { PageContext.AddLoadMessage("You have entered an illegal e-mail address."); return; } if (UserMembershipHelper.UserExists(UserName.Text.Trim(), newEmail)) { PageContext.AddLoadMessage("Username or email are already registered."); return; } string hashinput = DateTime.Now.ToString() + newEmail + Security.CreatePassword(20); string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); MembershipCreateStatus status; MembershipUser user = Membership.CreateUser(newUsername, Password.Text.Trim(), newEmail, Question.Text.Trim(), Answer.Text.Trim(), !PageContext.BoardSettings.EmailVerification, out status); if (status != MembershipCreateStatus.Success) { // error of some kind PageContext.AddLoadMessage("Membership Error Creating User: "******"VERIFYEMAIL"); verifyEmail.TemplateParams ["{link}"] = String.Format("{1}{0}", YAF.Classes.Utils.YafBuildLink.GetLink(YAF.Classes.Utils.ForumPages.approve, "k={0}", hash), YAF.Classes.Utils.YafForumInfo.ServerURL); verifyEmail.TemplateParams ["{key}"] = hash; verifyEmail.TemplateParams ["{forumname}"] = PageContext.BoardSettings.Name; verifyEmail.TemplateParams ["{forumlink}"] = String.Format("{0}", ForumURL); string subject = String.Format(PageContext.Localization.GetText("COMMON", "EMAILVERIFICATION_SUBJECT"), PageContext.BoardSettings.Name); verifyEmail.SendEmail(new System.Net.Mail.MailAddress(newEmail, newUsername), subject, true); } // success PageContext.AddLoadMessage(string.Format("User {0} Created Successfully.", UserName.Text.Trim())); YAF.Classes.Utils.YafBuildLink.Redirect(YAF.Classes.Utils.ForumPages.admin_reguser); } }
/// <summary> /// The forum register_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void ForumRegister_Click([NotNull] object sender, [NotNull] EventArgs e) { 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")); return; } if (UserMembershipHelper.UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS")); return; } MembershipCreateStatus status; MembershipUser 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); if (status != MembershipCreateStatus.Success) { // error of some kind this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_ERROR_CREATE").FormatWith(status)); return; } // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, newUsername); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // 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(); var autoWatchTopicsEnabled = this.Get <YafBoardSettings>() .DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // save the time zone... LegacyDb.user_save( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), this.PageContext.PageBoardID, null, null, null, this.TimeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, this.Get <YafBoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, null, null, null); if (this.Get <YafBoardSettings>().EmailVerification) { this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userID, newUsername); } LegacyDb.user_savenotification( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); // success this.PageContext.AddLoadMessage( this.GetText("ADMIN_REGUSER", "MSG_CREATED").FormatWith(this.UserName.Text.Trim())); YafBuildLink.Redirect(ForumPages.admin_reguser); }
/// <summary> /// Creates the or assign twitter user. /// </summary> /// <param name="twitterUser"> /// The twitter user. /// </param> /// <param name="oAuth"> /// The oAUTH. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message) { if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Create User if not exists?! Doesn't work because there is no Email var email = $"{twitterUser.UserName}@twitter.com"; // Check user for bot /*var spamChecker = new YafSpamCheck(); * string result; * var isPossibleSpamBot = false; * * var userIpAddress = BoardContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress(); * * // Check content for spam * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result)) * { * BoardContext.Current.Get<ILogger>().Log( * null, * "Bot Detected", * "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." * .FormatWith(twitterUser.UserName, twitterUser.Email, userIpAddress, result), * EventLogTypes.SpamBotDetected); * * if (BoardContext.Current.Get<BoardSettings>().BotHandlingOnRegister.Equals(1)) * { * // Flag user as spam bot * isPossibleSpamBot = true; * } * else if (BoardContext.Current.Get<BoardSettings>().BotHandlingOnRegister.Equals(2)) * { * message = BoardContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE"); * * if (!BoardContext.Current.Get<BoardSettings>().BanBotIpOnDetection) * { * return false; * } * * BoardContext.Current.GetRepository<BannedIP>() * .Save( * null, * userIpAddress, * "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), * BoardContext.Current.PageUserID); * * // Clear cache * BoardContext.Current.Get<IDataCache>().Remove(Constants.Cache.BannedIP); * * if (BoardContext.Current.Get<BoardSettings>().LogBannedIP) * { * BoardContext.Current.Get<ILogger>() * .Log( * null, * "IP BAN of Bot During Registration", * "A spam Bot who was trying to register was banned by IP {0}".FormatWith( * userIpAddress), * EventLogTypes.IpBanSet); * } * * return false; * } * }*/ // Create User if not exists?! var memberShipProvider = BoardContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( twitterUser.UserName, pass, email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out _); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, twitterUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = Utils.UserProfile.GetProfile(twitterUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.TwitterId = twitterUser.UserId.ToString(); userProfile.Twitter = twitterUser.UserName; userProfile.Homepage = twitterUser.Url.IsSet() ? twitterUser.Url : $"http://twitter.com/{twitterUser.UserName}"; userProfile.RealName = twitterUser.Name; userProfile.Interests = twitterUser.Description; userProfile.Location = twitterUser.Location; if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService) { var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator(); if (userIpLocator != null) { userProfile.Country = userIpLocator["CountryCode"]; var location = new StringBuilder(); if (userIpLocator["RegionName"] != null && userIpLocator["RegionName"].IsSet() && !userIpLocator["RegionName"].Equals("-")) { location.Append(userIpLocator["RegionName"]); } if (userIpLocator["CityName"] != null && userIpLocator["CityName"].IsSet() && !userIpLocator["CityName"].Equals("-")) { location.AppendFormat(", {0}", userIpLocator["CityName"]); } userProfile.Location = location.ToString(); } } userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED"); return(false); } if (BoardContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... BoardContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); // send user register notification to the following admin users... SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth); var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; BoardContext.Current.GetRepository <User>().Save( userId, BoardContext.Current.PageBoardID, twitterUser.UserName, twitterUser.UserName, email, TimeZoneInfo.Local.Id, null, null, null, null); // save the settings... BoardContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), BoardContext.Current.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar if (twitterUser.ProfileImageUrl.IsSet()) { BoardContext.Current.GetRepository <User>().SaveAvatar(userId, twitterUser.ProfileImageUrl, null, null); } LoginTwitterSuccess(true, oAuth, userId, user); message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL"); return(true); }
/// <summary> /// Creates the facebook user /// </summary> /// <param name="facebookUser"> /// The facebook user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateFacebookUser(FacebookUser facebookUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var spamChecker = new YafSpamCheck(); string result; var isPossibleSpamBot = false; var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (spamChecker.CheckUserForSpamBot(facebookUser.UserName, facebookUser.Email, userIpAddress, out result)) { YafContext.Current.Get <ILogger>().Log( null, "Bot Detected", "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." .FormatWith(facebookUser.UserName, facebookUser.Email, userIpAddress, result), EventLogTypes.SpamBotDetected); if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection) { return(false); } YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), YafContext.Current.PageUserID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", "A spam Bot who was trying to register was banned by IP {0}".FormatWith( userIpAddress), EventLogTypes.IpBanSet); } return(false); } } MembershipCreateStatus status; var memberShipProvider = YafContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( facebookUser.UserName, pass, facebookUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, facebookUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(facebookUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.Facebook = facebookUser.ProfileURL; userProfile.FacebookId = facebookUser.UserID; userProfile.Homepage = facebookUser.ProfileURL; if (facebookUser.Birthday.IsSet()) { DateTime userBirthdate; var ci = CultureInfo.CreateSpecificCulture("en-US"); DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date) { userProfile.Birthday = userBirthdate; } } userProfile.RealName = facebookUser.Name; userProfile.Gender = userGender; if (facebookUser.Location != null && facebookUser.Location.Name.IsSet()) { userProfile.Location = facebookUser.Location.Name; } userProfile.Save(); // setup their initial profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_FACEBOOK_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, facebookUser.UserName, facebookUser.UserName, facebookUser.Email, 0, null, null, true, null, null, null, null, null, null, null, null); var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar LegacyDb.user_saveavatar( userId, "https://graph.facebook.com/{0}/picture".FormatWith(facebookUser.UserID), null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true); message = string.Empty; return(true); }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser"> /// The Google user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var spamChecker = new YafSpamCheck(); string result; var isPossibleSpamBot = false; var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (spamChecker.CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out result)) { YafContext.Current.Get <ILogger>().Log( null, "Bot Detected", "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." .FormatWith(googleUser.UserName, googleUser.Email, userIpAddress, result), EventLogTypes.SpamBotDetected); if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection) { return(false); } YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), YafContext.Current.PageUserID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", "A spam Bot who was trying to register was banned by IP {0}".FormatWith( userIpAddress), EventLogTypes.IpBanSet); } return(false); } } MembershipCreateStatus status; var memberShipProvider = YafContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( googleUser.UserName, pass, googleUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(googleUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; if (YafContext.Current.Get <YafBoardSettings>().EnableIPInfoService&& this.UserIpLocator == null) { this.UserIpLocator = new IPDetails().GetData( YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(), "text", false, YafContext.Current.CurrentForumPage.Localization.Culture.Name, string.Empty, string.Empty); if (this.UserIpLocator != null && this.UserIpLocator["StatusCode"] == "OK" && this.UserIpLocator.Count > 0) { userProfile.Country = this.UserIpLocator["CountryCode"]; var location = new StringBuilder(); if (this.UserIpLocator["RegionName"] != null && this.UserIpLocator["RegionName"].IsSet() && !this.UserIpLocator["RegionName"].Equals("-")) { location.Append(this.UserIpLocator["RegionName"]); } if (this.UserIpLocator["CityName"] != null && this.UserIpLocator["CityName"].IsSet() && !this.UserIpLocator["CityName"].Equals("-")) { location.AppendFormat(", {0}", this.UserIpLocator["CityName"]); } userProfile.Location = location.ToString(); } } userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; YafContext.Current.GetRepository <User>().Save( userID: userId, boardID: YafContext.Current.PageBoardID, userName: googleUser.UserName, displayName: googleUser.UserName, email: googleUser.Email, timeZone: TimeZoneInfo.Local.Id, languageFile: null, culture: null, themeFile: null, textEditor: null, approved: null, pmNotification: YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, autoWatchTopics: autoWatchTopicsEnabled, dSTUser: TimeZoneInfo.Local.SupportsDaylightSavingTime, hideUser: null, notificationType: null); // save the settings... YafContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar YafContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }