Esempio n. 1
0
        /// <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"];
            }

            var user = YafContext.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 status);

            // 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...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            var isDST = false;

            if (row.Table.Columns.Contains("IsDST") && !string.IsNullOrEmpty((string)row["IsDST"]))
            {
                bool.TryParse((string)row["IsDST"], out isDST);
            }

            var 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);

            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);

            importCount++;

            return(importCount);
        }
Esempio n. 2
0
        /// <summary>
        /// Export All Users
        /// </summary>
        /// <param name="type">
        /// The export format type.
        /// </param>
        private void ExportAllUsers(string type)
        {
            var usersList = LegacyDb.user_list(this.PageContext.PageBoardID, null, true);

            usersList.DataSet.DataSetName = "YafUserList";

            usersList.TableName = "YafUser";

            usersList.Columns.Remove("AvatarImage");
            usersList.Columns.Remove("AvatarImageType");

            usersList.Columns.Remove("ProviderUserKey");
            usersList.Columns.Remove("Password");
            usersList.Columns.Remove("Joined");
            usersList.Columns.Remove("LastVisit");
            usersList.Columns.Remove("IP");
            usersList.Columns.Remove("NumPosts");
            usersList.Columns.Remove("RankID");
            usersList.Columns.Remove("Flags");
            usersList.Columns.Remove("Points");
            usersList.Columns.Remove("IsApproved");
            usersList.Columns.Remove("IsActiveExcluded");
            usersList.Columns.Remove("IsCaptchaExcluded");
            usersList.Columns.Remove("IsDirty");
            usersList.Columns.Remove("Style");
            usersList.Columns.Remove("IsAdmin");
            usersList.Columns.Remove("IsGuest1");
            usersList.Columns.Remove("IsHostAdmin");

            // Add Profile Columns
            usersList.Columns.Add("RealName");
            usersList.Columns.Add("BlogServiceUrl");
            usersList.Columns.Add("Blog");
            usersList.Columns.Add("Gender");
            usersList.Columns.Add("MSN");
            usersList.Columns.Add("Birthday");
            usersList.Columns.Add("BlogServiceUsername");
            usersList.Columns.Add("BlogServicePassword");
            usersList.Columns.Add("AIM");
            usersList.Columns.Add("GoogleTalk");
            usersList.Columns.Add("Location");
            usersList.Columns.Add("Country");
            usersList.Columns.Add("Region");
            usersList.Columns.Add("City");
            usersList.Columns.Add("Interests");
            usersList.Columns.Add("Homepage");
            usersList.Columns.Add("Skype");
            usersList.Columns.Add("ICQ");
            usersList.Columns.Add("XMPP");
            usersList.Columns.Add("YIM");
            usersList.Columns.Add("Occupation");
            usersList.Columns.Add("Twitter");
            usersList.Columns.Add("TwitterId");
            usersList.Columns.Add("Facebook");
            usersList.Columns.Add("FacebookId");
            usersList.Columns.Add("Google");
            usersList.Columns.Add("GoogleId");

            usersList.Columns.Add("Roles");

            usersList.AcceptChanges();

            foreach (DataRow user in usersList.Rows)
            {
                var userProfile = YafUserProfile.GetProfile((string)user["Name"]);

                // Add Profile Fields to User List Table.
                user["RealName"]            = userProfile.RealName;
                user["Blog"]                = userProfile.Blog;
                user["Gender"]              = userProfile.Gender;
                user["MSN"]                 = userProfile.MSN;
                user["Birthday"]            = userProfile.Birthday;
                user["BlogServiceUsername"] = userProfile.BlogServiceUsername;
                user["BlogServicePassword"] = userProfile.BlogServicePassword;
                user["AIM"]                 = userProfile.AIM;
                user["Google"]              = userProfile.Google;
                user["GoogleId"]            = userProfile.GoogleId;
                user["Location"]            = userProfile.Location;
                user["Country"]             = userProfile.Country;
                user["Region"]              = userProfile.Region;
                user["City"]                = userProfile.City;
                user["Interests"]           = userProfile.Interests;
                user["Homepage"]            = userProfile.Homepage;
                user["Skype"]               = userProfile.Skype;
                user["ICQ"]                 = userProfile.ICQ;
                user["XMPP"]                = userProfile.XMPP;
                user["YIM"]                 = userProfile.YIM;
                user["Occupation"]          = userProfile.Occupation;
                user["Twitter"]             = userProfile.Twitter;
                user["TwitterId"]           = userProfile.TwitterId;
                user["Facebook"]            = userProfile.Facebook;
                user["FacebookId"]          = userProfile.FacebookId;

                user["Roles"] = this.Get <RoleProvider>().GetRolesForUser((string)user["Name"]).ToDelimitedString(",");

                usersList.AcceptChanges();
            }

            switch (type)
            {
            case "xml":
                this.ExportAsXml(usersList);
                break;

            case "csv":
                this.ExportAsCsv(usersList);
                break;
            }
        }
Esempio n. 3
0
        /// <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;
            }

            // 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");

            MembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName);

            // setup/save the profile
            YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName);

            if (country.SelectedValue != null)
            {
                userProfile.Country = country.SelectedValue;
            }

            userProfile.Location = locationTextBox.Text.Trim();
            userProfile.Homepage = homepageTextBox.Text.Trim();

            userProfile.Save();

            // save the time zone...
            int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            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);

            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);

            // Clearing cache with old Active User Lazy Data ...
            this.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));
        }
Esempio n. 4
0
        /// <summary>
        /// Logins the or create user.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="parameters">
        /// The access token.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if Login was successful or not
        /// </returns>
        public bool LoginOrCreateUser(HttpRequest request, string parameters, out string message)
        {
            if (!BoardContext.Current.Get <BoardSettings>().AllowSingleSignOn)
            {
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_DEACTIVATED");

                return(false);
            }

            var facebookUser = this.GetFacebookUser(request, parameters);

            // Check if user name is null
            if (facebookUser.UserName.IsNotSet())
            {
                facebookUser.UserName = facebookUser.Name;
            }

            if (facebookUser.Email.IsNotSet())
            {
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED3");

                return(false);
            }

            // Check if user exists
            var userName = BoardContext.Current.Get <MembershipProvider>().GetUserNameByEmail(facebookUser.Email);

            if (userName.IsNotSet())
            {
                var userGender = 0;

                if (!facebookUser.Gender.IsSet())
                {
                    return(CreateFacebookUser(facebookUser, userGender, out message));
                }

                switch (facebookUser.Gender)
                {
                case "male":
                    userGender = 1;
                    break;

                case "female":
                    userGender = 2;
                    break;
                }

                // Create User if not exists?!
                return(CreateFacebookUser(facebookUser, userGender, out message));
            }

            var yafUser = YafUserProfile.GetProfile(userName);

            var yafUserData =
                new CombinedUserDataHelper(BoardContext.Current.Get <MembershipProvider>().GetUser(userName, true));

            // Legacy Handling
            if (ValidationHelper.IsNumeric(yafUser.Facebook))
            {
                if (!yafUser.Facebook.Equals(facebookUser.UserID))
                {
                    message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED2");

                    return(false);
                }
            }

            if (!yafUser.FacebookId.Equals(facebookUser.UserID))
            {
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED2");

                return(false);
            }

            SingleSignOnUser.LoginSuccess(AuthService.facebook, userName, yafUserData.UserID, true);

            message = string.Empty;

            return(true);
        }
Esempio n. 5
0
        /// <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)
        {
            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;
            var 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...
            var userId = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create profile
            var 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);
        }
Esempio n. 6
0
        /// <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 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);
            }

            if (isPossibleSpamBot)
            {
                YafSingleSignOnUser.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...
            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);
        }
Esempio n. 7
0
        /// <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 <BoardSettings>().DisableRegistrations)
            {
                message = YafContext.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 = 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<BoardSettings>().BotHandlingOnRegister.Equals(1))
             *  {
             *      // Flag user as spam bot
             *      isPossibleSpamBot = true;
             *  }
             *  else if (YafContext.Current.Get<BoardSettings>().BotHandlingOnRegister.Equals(2))
             *  {
             *      message = YafContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE");
             *
             *      if (!YafContext.Current.Get<BoardSettings>().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<BoardSettings>().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?!
            var memberShipProvider = YafContext.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 var status);

            // setup initial 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...
            var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.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 (YafContext.Current.Get <BoardSettings>().EnableIPInfoService)
            {
                var userIpLocator = YafContext.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 = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                return(false);
            }

            if (YafContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.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 = YafContext.Current.Get <BoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            YafContext.Current.GetRepository <User>().Save(
                userId,
                YafContext.Current.PageBoardID,
                twitterUser.UserName,
                twitterUser.UserName,
                email,
                TimeZoneInfo.Local.Id,
                null,
                null,
                null,
                null,
                null,
                YafContext.Current.Get <BoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                TimeZoneInfo.Local.SupportsDaylightSavingTime,
                null,
                null);

            // save the settings...
            YafContext.Current.GetRepository <User>().SaveNotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <BoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <BoardSettings>().DefaultSendDigestEmail);

            // save avatar
            if (twitterUser.ProfileImageUrl.IsSet())
            {
                YafContext.Current.GetRepository <User>().SaveAvatar(userId, twitterUser.ProfileImageUrl, null, null);
            }

            LoginTwitterSuccess(true, oAuth, userId, user);

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

            return(true);
        }
Esempio n. 8
0
        /// <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);
        }
Esempio n. 9
0
        /// <summary>
        /// Setups the user profile.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="userId">The user identifier.</param>
        private void SetupUserProfile(MembershipUser 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.SendSpamBotNotificationToAdmins(user, userId);
                }
                else if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2))
                {
                    // Kill user
                    UserMembershipHelper.DeleteUser(userId, true);

                    this.PageContext.AddLoadMessage(this.GetText("BOT_MESSAGE"), MessageTypes.Error);

                    if (this.Get <YafBoardSettings>().BanBotIpOnDetection)
                    {
                        this.GetRepository <BannedIP>()
                        .Save(
                            null,
                            userIpAddress,
                            "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
                            this.PageContext.PageUserID);

                        // Clear cache
                        this.Get <IDataCache>().Remove(Constants.Cache.BannedIP);

                        if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP)
                        {
                            this.Get <ILogger>()
                            .Log(
                                this.PageContext.PageUserID,
                                "IP BAN of Bot During Registration",
                                "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
                                    userIpAddress),
                                EventLogTypes.IpBanSet);
                        }
                    }
                }

                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)
            {
                return;
            }

            userProfile.Location = locationTextBox.Text.Trim();
            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);

            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);
        }
Esempio n. 10
0
        /// <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, 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...
            int 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);

            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);
        }
Esempio n. 11
0
        /// <summary>
        /// Connects the user.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the connect was successful or not
        /// </returns>
        public bool ConnectUser(HttpRequest request, string parameters, out string message)
        {
            var oAuth = new OAuthTwitter
            {
                ConsumerKey    = Config.TwitterConsumerKey,
                ConsumerSecret = Config.TwitterConsumerSecret
            };

            // Get the access token and secret.
            oAuth.AccessTokenGet(request["oauth_token"], request["oauth_verifier"]);

            if (oAuth.TokenSecret.Length > 0)
            {
                var tweetAPI = new TweetAPI(oAuth);

                var twitterUser = tweetAPI.GetUser();

                if (twitterUser.UserId > 0)
                {
                    // Create User if not exists?!
                    if (!YafContext.Current.IsGuest && !YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
                    {
                        // Because twitter doesnt provide the email we need to match the user name...
                        if (twitterUser.UserName != YafContext.Current.Profile.UserName)
                        {
                            message = YafContext.Current.Get <ILocalization>()
                                      .GetText("LOGIN", "SSO_TWITTERNAME_NOTMATCH");

                            return(false);
                        }

                        // Update profile with twitter informations
                        YafUserProfile userProfile = YafContext.Current.Profile;

                        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();

                        // save avatar
                        if (twitterUser.ProfileImageUrl.IsSet())
                        {
                            LegacyDb.user_saveavatar(
                                YafContext.Current.PageUserID,
                                twitterUser.ProfileImageUrl,
                                null,
                                null);
                        }

                        YafSingleSignOnUser.LoginSuccess(AuthService.twitter, null, YafContext.Current.PageUserID, false);

                        message = string.Empty;

                        return(true);
                    }
                }
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

            return(false);
        }
Esempio n. 12
0
        /// <summary>
        /// Connects the user.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="parameters">The access token.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the connect was successful or not
        /// </returns>
        public bool ConnectUser(HttpRequest request, string parameters, out string message)
        {
            var facebookUser = this.GetFacebookUser(request, parameters);

            // Check if username is null
            if (facebookUser.UserName.IsNotSet())
            {
                facebookUser.UserName = facebookUser.Name;
            }

            var userGender = 0;

            if (facebookUser.Gender.IsSet())
            {
                switch (facebookUser.Gender)
                {
                case "male":
                    userGender = 1;
                    break;

                case "female":
                    userGender = 2;
                    break;
                }
            }

            // Create User if not exists?!
            if (!YafContext.Current.IsGuest && !YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                // match the email address...
                if (facebookUser.Email != YafContext.Current.CurrentUserData.Email)
                {
                    message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOKNAME_NOTMATCH");

                    return(false);
                }

                // Update profile with facebook informations
                YafUserProfile userProfile = YafContext.Current.Profile;

                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();

                // save avatar
                LegacyDb.user_saveavatar(
                    YafContext.Current.PageUserID,
                    "https://graph.facebook.com/{0}/picture".FormatWith(facebookUser.UserID),
                    null,
                    null);

                YafSingleSignOnUser.LoginSuccess(AuthService.facebook, null, YafContext.Current.PageUserID, false);

                message = string.Empty;

                return(true);
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED");
            return(false);
        }
Esempio n. 13
0
        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);
            }
        }
Esempio n. 14
0
        /// <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);
        }
Esempio n. 15
0
        /// <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>());
        }
Esempio n. 16
0
        /// <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,
                dnnUserInfo.Membership.LastLoginDate.ToUniversalTime());

            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>());
        }
Esempio n. 17
0
        /// <summary>
        /// Imports the users.
        /// </summary>
        /// <param name="boardId">The board id.</param>
        /// <param name="portalId">The portal id.</param>
        /// <param name="portalGuid">The portal unique identifier.</param>
        /// <param name="info">The information text.</param>
        /// <returns>
        /// Returns the Number of Users that where imported
        /// </returns>
        public static int ImportUsers(int boardId, int portalId, Guid portalGuid, out string info)
        {
            var newUserCount = 0;

            var users = UserController.GetUsers(portalId);

            // Inject SU here
            users.AddRange(UserController.GetUsers(false, true, Null.NullInteger));

            users.Sort(new UserComparer());

            // Load Yaf Board Settings if needed
            var boardSettings = YafContext.Current == null
                                    ? new YafLoadBoardSettings(boardId)
                                    : YafContext.Current.Get <YafBoardSettings>();

            var rolesChanged = false;

            try
            {
                foreach (UserInfo dnnUserInfo in users)
                {
                    var dnnUser = Membership.GetUser(dnnUserInfo.Username, true);

                    if (dnnUser == null)
                    {
                        continue;
                    }

                    // unapprove soft deleted user in yaf
                    if (dnnUserInfo.IsDeleted && dnnUser.IsApproved)
                    {
                        dnnUser.IsApproved = false;
                        Membership.UpdateUser(dnnUser);

                        continue;
                    }

                    if (!dnnUserInfo.IsDeleted && !dnnUser.IsApproved)
                    {
                        dnnUser.IsApproved = true;
                        Membership.UpdateUser(dnnUser);
                    }

                    var yafUserId = LegacyDb.user_get(boardId, dnnUser.ProviderUserKey);

                    if (yafUserId.Equals(0))
                    {
                        // Create user if Not Exist
                        yafUserId = CreateYafUser(dnnUserInfo, dnnUser, boardId, portalId, boardSettings);
                        newUserCount++;
                    }
                    else
                    {
                        ProfileSyncronizer.UpdateUserProfile(
                            yafUserId,
                            YafUserProfile.GetProfile(dnnUser.UserName),
                            new CustomCombinedUserDataHelper(dnnUser, yafUserId, boardId),
                            dnnUserInfo,
                            dnnUser,
                            portalId,
                            portalGuid,
                            boardSettings,
                            true);
                    }

                    rolesChanged = RoleSyncronizer.SynchronizeUserRoles(boardId, portalId, yafUserId, dnnUserInfo);

                    // super admin check...
                    if (dnnUserInfo.IsSuperUser)
                    {
                        SetYafHostUser(yafUserId, boardId);
                    }
                }

                YafContext.Current.Get <IDataCache>().Clear();

                DataCache.ClearCache();
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
            }

            info = "{0} User(s) Imported, all user profiles are synchronized{1}".FormatWith(
                newUserCount,
                rolesChanged ? ", but all User Roles are synchronized!" : ", User Roles already synchronized!");

            return(newUserCount);
        }
        /// <summary>
        /// DNN Profile is newer, sync YAF now
        /// NOTE : no need to manually sync Email Address
        /// </summary>
        /// <param name="yafUserId">The YAF user id.</param>
        /// <param name="yafUserProfile">The YAF user profile.</param>
        /// <param name="yafUserData">The YAF user data.</param>
        /// <param name="dnnUserInfo">The DNN user info.</param>
        /// <param name="portalGUID">The portal GUID.</param>
        /// <param name="boardSettings">The board settings.</param>
        private static void SyncYafProfile(int yafUserId, YafUserProfile yafUserProfile, IUserData yafUserData, UserInfo dnnUserInfo, Guid portalGUID, YafBoardSettings boardSettings)
        {
            /*var userCuluture = new YafCultureInfo
             * {
             *  LanguageFile = yafUserData.LanguageFile,
             *  Culture = yafUserData.CultureUser
             * };
             *
             * if (dnnUserInfo.Profile.PreferredLocale.IsSet())
             * {
             *  CultureInfo newCulture = new CultureInfo(dnnUserInfo.Profile.PreferredLocale);
             *
             *  foreach (DataRow row in
             *      StaticDataHelper.Cultures().Rows.Cast<DataRow>().Where(
             *          row => dnnUserInfo.Profile.PreferredLocale == row["CultureTag"].ToString() || newCulture.TwoLetterISOLanguageName == row["CultureTag"].ToString()))
             *  {
             *      userCuluture.LanguageFile = row["CultureFile"].ToString();
             *      userCuluture.Culture = row["CultureTag"].ToString();
             *  }
             * }*/

            LegacyDb.user_save(
                yafUserId,
                boardSettings.BoardID,
                null,
                dnnUserInfo.DisplayName,
                dnnUserInfo.Email,
                yafUserData.TimeZone,
                yafUserData.LanguageFile.IsSet() ? yafUserData.LanguageFile : null,
                yafUserData.CultureUser,
                yafUserData.ThemeFile,
                yafUserData.TextEditor,
                yafUserData.UseMobileTheme,
                null,
                null,
                null,
                yafUserData.DSTUser,
                yafUserData.IsActiveExcluded,
                null);

            if (dnnUserInfo.Profile.FullName.IsSet())
            {
                yafUserProfile.RealName = dnnUserInfo.Profile.FullName;
            }

            if (dnnUserInfo.Profile.Country.IsSet() && !dnnUserInfo.Profile.Country.Equals("N/A"))
            {
                var regionInfo = GetRegionInfoFromCountryName(dnnUserInfo.Profile.Country);

                if (regionInfo != null)
                {
                    yafUserProfile.Country = regionInfo.TwoLetterISORegionName;
                }
            }

            if (dnnUserInfo.Profile.City.IsSet())
            {
                yafUserProfile.City = dnnUserInfo.Profile.City;
            }

            if (dnnUserInfo.Profile.Website.IsSet())
            {
                yafUserProfile.Homepage = dnnUserInfo.Profile.Website;
            }

            yafUserProfile.LastSyncedWithDNN = DateTime.Now;

            yafUserProfile.Save();

            yafUserProfile.Save();

            try
            {
                if (dnnUserInfo.Profile.Photo.IsSet() && !dnnUserInfo.Profile.PhotoURL.Contains("no_avatar.gif"))
                {
                    SaveDnnAvatar(
                        "fileid={0}".FormatWith(dnnUserInfo.Profile.Photo),
                        yafUserId,
                        portalGUID);
                }
                else
                {
                    LegacyDb.user_deleteavatar(yafUserId);
                }
            }
            catch (Exception)
            {
            }

            YafContext.Current.Get <IRaiseEvent>().Raise(new UpdateUserEvent(yafUserId));

            YafContext.Current.Get <IDataCache>().Clear();
        }
Esempio n. 19
0
        /// <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); ");
        }
Esempio n. 20
0
        /// <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 (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Check user for bot
            var isPossibleSpamBot = false;

            var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress();

            // Check content for spam
            if (YafContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result))
            {
                YafContext.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 (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 {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 {userIpAddress}",
                            EventLogTypes.IpBanSet);
                    }

                    return(false);
                }
            }

            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 var 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)
            {
                var userIpLocator = YafContext.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 = 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,
                YafContext.Current.PageBoardID,
                googleUser.UserName,
                googleUser.UserName,
                googleUser.Email,
                TimeZoneInfo.Local.Id,
                null,
                null,
                null,
                null,
                null,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                TimeZoneInfo.Local.SupportsDaylightSavingTime,
                null,
                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);
        }
Esempio n. 21
0
        /// <summary>
        /// Logins the or create user.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="parameters">
        /// The parameters.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if Login was successful or not
        /// </returns>
        public bool LoginOrCreateUser(HttpRequest request, string parameters, out string message)
        {
            var oAuth = new OAuthTwitter
            {
                ConsumerKey    = Config.TwitterConsumerKey,
                ConsumerSecret = Config.TwitterConsumerSecret
            };

            // Get the access token and secret.
            oAuth.AccessTokenGet(request["oauth_token"], request["oauth_verifier"]);

            if (oAuth.TokenSecret.Length > 0)
            {
                var tweetAPI = new TweetAPI(oAuth);

                var twitterUser = tweetAPI.GetUser();

                if (twitterUser.UserId > 0)
                {
                    // Check if user exists
                    var checkUser = YafContext.Current.Get <MembershipProvider>().GetUser(twitterUser.UserName, false);

                    // Login user if exists
                    if (checkUser == null)
                    {
                        return(CreateTwitterUser(twitterUser, oAuth, out message));
                    }

                    // LOGIN Existing User
                    var yafUser = YafUserProfile.GetProfile(checkUser.UserName);

                    var yafUserData = new CombinedUserDataHelper(checkUser);

                    if (yafUser.Twitter.IsNotSet() && yafUser.TwitterId.IsNotSet())
                    {
                        // user with the same name exists but account is not connected, exit!
                        message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                        return(false);
                    }

                    if (yafUser.Twitter.Equals(twitterUser.UserName) &&
                        yafUser.TwitterId.Equals(twitterUser.UserId.ToString()))
                    {
                        LoginTwitterSuccess(false, oAuth, yafUserData.UserID, checkUser);

                        message = string.Empty;

                        return(true);
                    }

                    message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTERID_NOTMATCH");

                    return(false);

                    // User does not exist create new user
                }
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

            return(false);
        }
Esempio n. 22
0
        /// <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;
            }

            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"];
                }
            }

            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);

            var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            LegacyDb.user_save(
                userID: userId,
                boardID: YafContext.Current.PageBoardID,
                userName: facebookUser.UserName,
                displayName: facebookUser.UserName,
                email: facebookUser.Email,
                timeZone: TimeZoneInfo.Local.Id,
                languageFile: null,
                culture: null,
                themeFile: null,
                textEditor: null,
                useMobileTheme: null,
                approved: null,
                pmNotification: YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopics: autoWatchTopicsEnabled,
                dSTUser: TimeZoneInfo.Local.SupportsDaylightSavingTime,
                hideUser: null,
                notificationType: null);

            // 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);
        }
Esempio n. 23
0
        /// <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 static bool CreateFacebookUser(FacebookUser facebookUser, 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(facebookUser.UserName, facebookUser.Email, userIpAddress, out var result))
            {
                BoardContext.Current.Get <ILogger>().Log(
                    null,
                    "Bot Detected",
                    $"Bot Check detected a possible SPAM BOT: (user name : '{facebookUser.UserName}', email : '{facebookUser.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(
                facebookUser.UserName,
                pass,
                facebookUser.Email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out var status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, facebookUser.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 = 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())
            {
                var ci = CultureInfo.CreateSpecificCulture("en-US");
                DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out var 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;
            }

            if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService)
            {
                var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator();

                if (userIpLocator != null)
                {
                    userProfile.Country = userIpLocator["CountryCode"];
                }
            }

            userProfile.Save();

            // setup their initial profile information
            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_FACEBOOK_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,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.Email,
                TimeZoneInfo.Local.Id,
                null,
                null,
                null,
                null,
                BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                TimeZoneInfo.Local.SupportsDaylightSavingTime,
                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,
                $"https://graph.facebook.com/v3.3/{facebookUser.UserID}/picture",
                null,
                null);

            BoardContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));

            SingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
Esempio n. 24
0
        /// <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)
        {
            var 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...
            var userID = RoleMembershipHelper.CreateForumUser(user, displayName, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var 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);
            }

            if (this.IsPossibleSpamBot)
            {
                if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1))
                {
                    this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
                }
            }
            else
            {
                // 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);
                }
            }
        }
        /// <summary>
        /// The update user profile.
        /// </summary>
        /// <param name="userName">
        /// The user name.
        /// </param>
        private void UpdateUserProfile([NotNull] string userName)
        {
            YafUserProfile userProfile = YafUserProfile.GetProfile(userName);

            userProfile.Country = this.Country.SelectedItem != null
                                      ? this.Country.SelectedItem.Value.Trim()
                                      : string.Empty;

            userProfile.Region = this.Region.SelectedItem != null && this.Country.SelectedItem != null &&
                                 this.Country.SelectedItem.Value.Trim().IsSet()
                                     ? this.Region.SelectedItem.Value.Trim()
                                     : string.Empty;
            userProfile.City       = this.City.Text.Trim();
            userProfile.Location   = this.Location.Text.Trim();
            userProfile.Homepage   = this.HomePage.Text.Trim();
            userProfile.MSN        = this.MSN.Text.Trim();
            userProfile.YIM        = this.YIM.Text.Trim();
            userProfile.AIM        = this.AIM.Text.Trim();
            userProfile.ICQ        = this.ICQ.Text.Trim();
            userProfile.Facebook   = this.Facebook.Text.Trim();
            userProfile.Twitter    = this.Twitter.Text.Trim();
            userProfile.Google     = this.Google.Text.Trim();
            userProfile.XMPP       = this.Xmpp.Text.Trim();
            userProfile.Skype      = this.Skype.Text.Trim();
            userProfile.RealName   = this.Realname.Text.Trim();
            userProfile.Occupation = this.Occupation.Text.Trim();
            userProfile.Interests  = this.Interests.Text.Trim();
            userProfile.Gender     = this.Gender.SelectedIndex;
            userProfile.Blog       = this.Weblog.Text.Trim();

            DateTime userBirthdate;

            if (this.Get <YafBoardSettings>().UseFarsiCalender&& this.CurrentCultureInfo.IsFarsiCulture())
            {
                var persianDate = new PersianDate(this.Birthday.Text);
                userBirthdate = PersianDateConverter.ToGregorianDateTime(persianDate);

                if (userBirthdate > DateTime.MinValue.Date)
                {
                    userProfile.Birthday = userBirthdate.Date;
                }
            }
            else
            {
                DateTime.TryParse(this.Birthday.Text, this.CurrentCultureInfo, DateTimeStyles.None, out userBirthdate);

                if (userBirthdate > DateTime.MinValue.Date)
                {
                    // Attention! This is stored in profile in the user timezone date
                    userProfile.Birthday = userBirthdate.Date;
                }
            }

            userProfile.BlogServiceUrl      = this.WeblogUrl.Text.Trim();
            userProfile.BlogServiceUsername = this.WeblogUsername.Text.Trim();
            userProfile.BlogServicePassword = this.WeblogID.Text.Trim();

            try
            {
                // Sync to User Profile Mirror table while it's dirty
                SettingsPropertyValueCollection settingsPropertyValueCollection = userProfile.PropertyValues;

                LegacyDb.SetPropertyValues(
                    this.PageContext.PageBoardID,
                    UserMembershipHelper.ApplicationName(),
                    this.currentUserID,
                    settingsPropertyValueCollection);
            }
            catch (Exception ex)
            {
                this.Logger.Log(
                    "Error while syncinng the User Profile",
                    EventLogTypes.Error,
                    this.PageContext.PageUserName,
                    "Edit User Profile page",
                    ex);
            }

            userProfile.Save();
        }
Esempio n. 26
0
        /// <summary>
        /// Setups the user profile.
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        /// <param name="userId">
        /// The user identifier.
        /// </param>
        private void SetupUserProfile(MembershipUser 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         = (ImageListBox)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
            var 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;

                // Flag user as spam bot
                this.IsPossibleSpamBot = true;

                var userIpAddress = this.Get <HttpRequestBase>().GetUserRealIPAddress();

                if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1))
                {
                    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.danger);
                }

                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();

                var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting
                                             == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

                // save the time zone...
                this.GetRepository <User>().Save(
                    userID: userId,
                    boardID: this.PageContext.PageBoardID,
                    userName: null,
                    displayName: null,
                    email: null,
                    timeZone: timeZones.SelectedValue,
                    languageFile: null,
                    culture: null,
                    themeFile: null,
                    textEditor: null,
                    approved: null,
                    pmNotification: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                    autoWatchTopics: autoWatchTopicsEnabled,
                    dSTUser: dstUser.Checked,
                    hideUser: null,
                    notificationType: null);

                // save the settings...
                this.GetRepository <User>().SaveNotification(
                    userId,
                    true,
                    autoWatchTopicsEnabled,
                    this.Get <YafBoardSettings>().DefaultNotificationSetting,
                    this.Get <YafBoardSettings>().DefaultSendDigestEmail);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// The migrate users from <paramref name="dataTable"/>.
        /// </summary>
        /// <param name="approved">
        /// The approved.
        /// </param>
        /// <param name="dataTable">
        /// The dataTable.
        /// </param>
        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;
                }

                MembershipUser 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());
                    }
                }
            });
        }
Esempio n. 28
0
        /// <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);
            }

            // send user register notification to the user...
            YafContext.Current.Get <ISendNotification>()
            .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER");    // TODO : LOCALIZE

            // 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);
        }