Beispiel #1
0
        private static void CreateYAFUser(string sUsername, string sPassword, string email)
        {
            if (!UserMembershipHelper.UserExists(sUsername, email))
            {
                YafMembershipProvider mb = (YafMembershipProvider)System.Web.Security.Membership.Providers["YafMembershipProvider"];
                int?forumUserID          = 0;

                if (!mb.ValidateUser(sUsername, sPassword))
                {
                    MembershipCreateStatus status;
                    MembershipUser         forumUser = mb.CreateUser(sUsername, sPassword, email, "question", "answer", true, null, out status);
                    // create the user in the YAF DB as well as sync roles...
                    forumUserID = RoleMembershipHelper.CreateForumUser(forumUser, 1);

                    RoleMembershipHelper.SetupUserRoles(1, sUsername);
                    RoleMembershipHelper.AddUserToRole(sUsername, "Registered");

                    // create empty profile just so they have one
                    YafUserProfile userProfile = YafUserProfile.GetProfile(sUsername);
                    userProfile.Homepage = "fwd.com";

                    // setup their inital profile information
                    userProfile.Save();
                }
                else
                {
                    return;
                }
            }
        }
        /// <summary>
        /// The update user profile.
        /// </summary>
        /// <param name="userName">
        /// The user name.
        /// </param>
        private void UpdateUserProfile(string userName)
        {
            YafUserProfile userProfile = YafUserProfile.GetProfile(userName);

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

            if (this.PageContext.BoardSettings.EnableDNACalendar && this.datePicker.Value > DateTime.MinValue.Date)
            {
                userProfile.Birthday = this.datePicker.Value.Date;
            }

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

            userProfile.Save();
        }
Beispiel #3
0
        /// <summary>
        /// The update user profile.
        /// </summary>
        /// <param name="userName">
        /// The user name.
        /// </param>
        private void UpdateUserProfile([NotNull] string userName)
        {
            var 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.ICQ        = this.ICQ.Text.Trim();
            userProfile.Facebook   = this.Facebook.Text.Trim();
            userProfile.Twitter    = this.Twitter.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 <BoardSettings>().UseFarsiCalender&& this.CurrentCultureInfo.IsFarsiCulture())
            {
                try
                {
                    var persianDate = new PersianDate(this.Birthday.Text);

                    userBirthdate = PersianDateConverter.ToGregorianDateTime(persianDate);
                }
                catch (Exception)
                {
                    userBirthdate = DateTimeHelper.SqlDbMinTime().Date;
                }

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

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

            userProfile.Save();
        }
        /// <summary>
        /// Handles the CreatedUser event of the CreateUserWizard1 control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="EventArgs"/> instance containing the event data.
        /// </param>
        protected void CreateUserWizard1_CreatedUser([NotNull] object sender, [NotNull] EventArgs e)
        {
            SitecoreMembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, this.CreateUserWizard1.UserName);

            var displayName = user.UserName;

            if (this.Get <YafBoardSettings>().EnableDisplayName)
            {
                displayName = this.CreateUserStepContainer.FindControlAs <TextBox>("DisplayName").Text.Trim();
            }

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, displayName, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName);

            // setup their inital profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                YafBuildLink.RedirectInfoPage(InfoMessage.Failure);
            }

            // handle e-mail verification if needed
            if (this.Get <YafBoardSettings>().EmailVerification)
            {
                // get the user email
                var emailTextBox =
                    (TextBox)this.CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email");
                var email = emailTextBox.Text.Trim();

                this.Get <ISendNotification>().SendVerificationEmail(user, email, userID);
            }
            else
            {
                // Send welcome mail/pm to user
                this.Get <ISendNotification>().SendUserWelcomeNotification(user, userID.Value);
            }

            if (this.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (this.IsPossibleSpamBot)
            {
                this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }
        }
Beispiel #5
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 (!YafContext.Current.Get <YafBoardSettings>().AllowSingleSignOn)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_DEACTIVATED");

                return(false);
            }

            var googleUser = this.GetGoogleUser(request, parameters);

            var userGender = 0;

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

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

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

            if (userName.IsNotSet())
            {
                // Create User if not exists?!
                return(this.CreateGoogleUser(googleUser, userGender, out message));
            }

            var yafUser = YafUserProfile.GetProfile(userName);

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

            if (!yafUser.GoogleId.Equals(googleUser.UserID))
            {
                // TODO
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_GOOGLE_FAILED");

                return(false);
            }

            YafSingleSignOnUser.LoginSuccess(AuthService.google, userName, yafUserData.UserID, true);

            message = string.Empty;

            return(true);
        }
Beispiel #6
0
        /// <summary>
        /// The create user wizard 1_ created user.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
            MembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, this.CreateUserWizard1.UserName);

            string displayName = user.UserName;

            if (this.PageContext.BoardSettings.EnableDisplayName)
            {
                displayName = this.CreateUserStepContainer.FindControlAs <TextBox>("DisplayName").Text.Trim();
            }

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, displayName, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName);

            // setup their inital profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                YafBuildLink.RedirectInfoPage(InfoMessage.Failure);
            }

            // handle e-mail verification if needed
            if (this.PageContext.BoardSettings.EmailVerification)
            {
                // get the user email
                this.SendVerificationEmail(user, userID);
            }

            if (this.PageContext.BoardSettings.NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                this.SendRegistrationNotificationEmail(user);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Sets the location.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Returns the Location</returns>
        protected string SetLocation([NotNull] string userName)
        {
            string location;

            try
            {
                location = YafUserProfile.GetProfile(userName).Location;

                if (location.IsNotSet())
                {
                    location = "-";
                }
            }
            catch (Exception)
            {
                location = "-";
            }

            return(this.HtmlEncode(this.Get <IBadWordReplace>().Replace(location)));
        }
Beispiel #8
0
        /// <summary>
        /// Sets the location.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Returns the Location</returns>
        protected string SetLocation([NotNull] string userName)
        {
            string location;

            try
            {
                location = YafUserProfile.GetProfile(Eval("UserName").ToString()).Location;

                if (string.IsNullOrEmpty(location))
                {
                    location = "-";
                }
            }
            catch (Exception)
            {
                location = "-";
            }

            return(this.HtmlEncode(this.Get <IBadWordReplace>().Replace(location)));
        }
Beispiel #9
0
        /// <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(
                    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();
        }
Beispiel #10
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;
            }
        }
Beispiel #11
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);

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

                    if (dnnUserInfo.IsDeleted)
                    {
                        // TODO : Delete user in yaf
                        continue;
                    }

                    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)
                    {
                        CreateYafHostUser(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);
        }
Beispiel #12
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>());
        }
Beispiel #13
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...
                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: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                    autoWatchTopics: autoWatchTopicsEnabled,
                    dSTUser: dstUser.Checked,
                    hideUser: null,
                    notificationType: null);

                // save the settings...
                LegacyDb.user_savenotification(
                    userId,
                    true,
                    autoWatchTopicsEnabled,
                    this.Get <YafBoardSettings>().DefaultNotificationSetting,
                    this.Get <YafBoardSettings>().DefaultSendDigestEmail);
            }
        }
Beispiel #14
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;
            }

            userProfile.Save();

            // setup their initial profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (isPossibleSpamBot)
            {
                YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }

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

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

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.Email,
                0,
                null,
                null,
                true,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

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

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

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

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

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

            message = string.Empty;

            return(true);
        }
Beispiel #15
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 conncected, 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);
        }
Beispiel #16
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);
            }

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

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

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.Email,
                facebookUser.Timezone,
                null,
                null,
                true,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

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

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

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

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

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

            message = string.Empty;

            return(true);
        }
Beispiel #17
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);
        }
Beispiel #18
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 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?! Doesn't work because there is no Email
            var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

            // Check user for bot

            /*var spamChecker = new YafSpamCheck();
             * string result;
             * var isPossibleSpamBot = false;
             *
             * var userIpAddress = YafContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress();
             *
             * // Check content for spam
             * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result))
             * {
             *  YafContext.Current.Get<ILogger>().Log(
             *      null,
             *      "Bot Detected",
             *      "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected."
             *          .FormatWith(twitterUser.UserName, twitterUser.Email, userIpAddress, result),
             *      EventLogTypes.SpamBotDetected);
             *
             *  if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(1))
             *  {
             *      // Flag user as spam bot
             *      isPossibleSpamBot = true;
             *  }
             *  else if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(2))
             *  {
             *      message = YafContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE");
             *
             *      if (!YafContext.Current.Get<YafBoardSettings>().BanBotIpOnDetection)
             *      {
             *          return false;
             *      }
             *
             *      YafContext.Current.GetRepository<BannedIP>()
             *          .Save(
             *              null,
             *              userIpAddress,
             *              "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
             *              YafContext.Current.PageUserID);
             *
             *      // Clear cache
             *      YafContext.Current.Get<IDataCache>().Remove(Constants.Cache.BannedIP);
             *
             *      if (YafContext.Current.Get<YafBoardSettings>().LogBannedIP)
             *      {
             *          YafContext.Current.Get<ILogger>()
             *              .Log(
             *                  null,
             *                  "IP BAN of Bot During Registration",
             *                  "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
             *                      userIpAddress),
             *                  EventLogTypes.IpBanSet);
             *      }
             *
             *      return false;
             *  }
             * }*/

            // Create User if not exists?!
            MembershipCreateStatus status;

            var 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 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/{0}".FormatWith(twitterUser.UserName);
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            if (YafContext.Current.Get <YafBoardSettings>().EnableIPInfoService&& this.UserIpLocator == null)
            {
                this.UserIpLocator = new IPDetails().GetData(
                    YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(),
                    "text",
                    false,
                    YafContext.Current.CurrentForumPage.Localization.Culture.Name,
                    string.Empty,
                    string.Empty);

                if (this.UserIpLocator != null && this.UserIpLocator["StatusCode"] == "OK" &&
                    this.UserIpLocator.Count > 0)
                {
                    userProfile.Country = this.UserIpLocator["CountryCode"];

                    var location = new StringBuilder();

                    if (this.UserIpLocator["RegionName"] != null && this.UserIpLocator["RegionName"].IsSet() &&
                        !this.UserIpLocator["RegionName"].Equals("-"))
                    {
                        location.Append(this.UserIpLocator["RegionName"]);
                    }

                    if (this.UserIpLocator["CityName"] != null && this.UserIpLocator["CityName"].IsSet() &&
                        !this.UserIpLocator["CityName"].Equals("-"))
                    {
                        location.AppendFormat(", {0}", this.UserIpLocator["CityName"]);
                    }

                    userProfile.Location = location.ToString();
                }
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_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);
            }

            // 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 <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

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

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

            // save avatar
            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);
        }
Beispiel #19
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 memberShipProvider = YafContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                googleUser.UserName,
                pass,
                googleUser.Email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(googleUser.UserName);

            // setup their initial profile information
            userProfile.Save();

            userProfile.GoogleId = googleUser.UserID;
            userProfile.Homepage = googleUser.ProfileURL;

            userProfile.Gender = userGender;

            if (YafContext.Current.Get <YafBoardSettings>().EnableIPInfoService&& this.UserIpLocator == null)
            {
                this.UserIpLocator = new IPDetails().GetData(
                    YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(),
                    "text",
                    false,
                    YafContext.Current.CurrentForumPage.Localization.Culture.Name,
                    string.Empty,
                    string.Empty);

                if (this.UserIpLocator != null && this.UserIpLocator["StatusCode"] == "OK" &&
                    this.UserIpLocator.Count > 0)
                {
                    userProfile.Country = this.UserIpLocator["CountryCode"];

                    var location = new StringBuilder();

                    if (this.UserIpLocator["RegionName"] != null && this.UserIpLocator["RegionName"].IsSet() &&
                        !this.UserIpLocator["RegionName"].Equals("-"))
                    {
                        location.Append(this.UserIpLocator["RegionName"]);
                    }

                    if (this.UserIpLocator["CityName"] != null && this.UserIpLocator["CityName"].IsSet() &&
                        !this.UserIpLocator["CityName"].Equals("-"))
                    {
                        location.AppendFormat(", {0}", this.UserIpLocator["CityName"]);
                    }

                    userProfile.Location = location.ToString();
                }
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (isPossibleSpamBot)
            {
                YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }

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

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

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

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

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

            // save avatar
            YafContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null);

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

            YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
Beispiel #20
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);
                }
            }

            var pass             = Membership.GeneratePassword(32, 16);
            var securityAnswer   = Membership.GeneratePassword(64, 30);
            var securityQuestion = "Answer is a generated Pass";

            if (row.Table.Columns.Contains("Password") && ((string)row["Password"]).IsSet() &&
                row.Table.Columns.Contains("SecurityQuestion") &&
                ((string)row["SecurityQuestion"]).IsSet() &&
                row.Table.Columns.Contains("SecurityAnswer") && ((string)row["SecurityAnswer"]).IsSet())
            {
                pass = (string)row["Password"];

                securityAnswer   = (string)row["SecurityAnswer"];
                securityQuestion = (string)row["SecurityQuestion"];
            }

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

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

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile((string)row["Name"]);

            // Add Profile Fields to User List Table.
            if (row.Table.Columns.Contains("RealName") && ((string)row["RealName"]).IsSet())
            {
                userProfile.RealName = (string)row["RealName"];
            }

            if (row.Table.Columns.Contains("Blog") && ((string)row["Blog"]).IsSet())
            {
                userProfile.Blog = (string)row["Blog"];
            }

            if (row.Table.Columns.Contains("Gender") && ((string)row["Gender"]).IsSet())
            {
                int.TryParse((string)row["Gender"], out var gender);

                userProfile.Gender = gender;
            }

            if (row.Table.Columns.Contains("Birthday") && ((string)row["Birthday"]).IsSet())
            {
                DateTime.TryParse((string)row["Birthday"], out var userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime())
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            if (row.Table.Columns.Contains("BlogServiceUsername") &&
                ((string)row["BlogServiceUsername"]).IsSet())
            {
                userProfile.BlogServiceUsername = (string)row["BlogServiceUsername"];
            }

            if (row.Table.Columns.Contains("BlogServicePassword") &&
                ((string)row["BlogServicePassword"]).IsSet())
            {
                userProfile.BlogServicePassword = (string)row["BlogServicePassword"];
            }

            if (row.Table.Columns.Contains("GoogleId") && ((string)row["GoogleId"]).IsSet())
            {
                userProfile.GoogleId = (string)row["GoogleId"];
            }

            if (row.Table.Columns.Contains("Location") && ((string)row["Location"]).IsSet())
            {
                userProfile.Location = (string)row["Location"];
            }

            if (row.Table.Columns.Contains("Country") && ((string)row["Country"]).IsSet())
            {
                userProfile.Country = (string)row["Country"];
            }

            if (row.Table.Columns.Contains("Region") && ((string)row["Region"]).IsSet())
            {
                userProfile.Region = (string)row["Region"];
            }

            if (row.Table.Columns.Contains("City") && ((string)row["City"]).IsSet())
            {
                userProfile.City = (string)row["City"];
            }

            if (row.Table.Columns.Contains("Interests") && ((string)row["Interests"]).IsSet())
            {
                userProfile.Interests = (string)row["Interests"];
            }

            if (row.Table.Columns.Contains("Homepage") && ((string)row["Homepage"]).IsSet())
            {
                userProfile.Homepage = (string)row["Homepage"];
            }

            if (row.Table.Columns.Contains("Skype") && ((string)row["Skype"]).IsSet())
            {
                userProfile.Skype = (string)row["Skype"];
            }

            if (row.Table.Columns.Contains("ICQe") && ((string)row["ICQ"]).IsSet())
            {
                userProfile.ICQ = (string)row["ICQ"];
            }

            if (row.Table.Columns.Contains("XMPP") && ((string)row["XMPP"]).IsSet())
            {
                userProfile.XMPP = (string)row["XMPP"];
            }

            if (row.Table.Columns.Contains("Occupation") && ((string)row["Occupation"]).IsSet())
            {
                userProfile.Occupation = (string)row["Occupation"];
            }

            if (row.Table.Columns.Contains("Twitter") && ((string)row["Twitter"]).IsSet())
            {
                userProfile.Twitter = (string)row["Twitter"];
            }

            if (row.Table.Columns.Contains("TwitterId") && ((string)row["TwitterId"]).IsSet())
            {
                userProfile.TwitterId = (string)row["TwitterId"];
            }

            if (row.Table.Columns.Contains("Facebook") && ((string)row["Facebook"]).IsSet())
            {
                userProfile.Facebook = (string)row["Facebook"];
            }

            if (row.Table.Columns.Contains("FacebookId") && ((string)row["FacebookId"]).IsSet())
            {
                userProfile.FacebookId = (string)row["FacebookId"];
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                return(importCount);
            }

            // send user register notification to the new users
            this.Get <ISendNotification>().SendRegistrationNotificationToUser(
                user, pass, securityAnswer, "NOTIFICATION_ON_REGISTER");

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

            var isDst = false;

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

            var timeZone = 0;

            if (row.Table.Columns.Contains("Timezone") && ((string)row["Timezone"]).IsSet())
            {
                int.TryParse((string)row["Timezone"], out timeZone);
            }

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

            this.GetRepository <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,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                isDst,
                null,
                null);

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

            importCount++;

            return(importCount);
        }
Beispiel #21
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(object sender, WizardNavigationEventArgs e)
        {
            if (this.CreateUserWizard1.WizardSteps[e.CurrentStepIndex].ID == "profile")
            {
                // this is the "Profile Information" step. Save the data to their profile (+ defaults).
                var timeZones       = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones");
                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);

                // Trying to consume data about user IP whereabouts

                /*  if (_userIpLocator.Status == "OK" && String.IsNullOrEmpty(locationTextBox.Text.Trim()))
                 * {
                 *
                 *    if (!String.IsNullOrEmpty(_userIpLocator.CountryName))
                 *    {
                 *        userProfile.Location += _userIpLocator.CountryName;
                 *    }
                 *    if (!String.IsNullOrEmpty(_userIpLocator.RegionName))
                 *    {
                 *        userProfile.Location += ", " + _userIpLocator.RegionName;
                 *    }
                 *    if (!String.IsNullOrEmpty(_userIpLocator.City))
                 *    {
                 *        userProfile.Location += ", " + _userIpLocator.City;
                 *    }
                 * }
                 * else
                 * {
                 *     userProfile.Location = locationTextBox.Text.Trim();
                 * } */
                userProfile.Location = locationTextBox.Text.Trim();
                userProfile.Homepage = homepageTextBox.Text.Trim();

                userProfile.Save();

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

                DB.user_save(
                    userId,
                    this.PageContext.PageBoardID,
                    null,
                    null,
                    null,
                    timeZones.SelectedValue.ToType <int>(),
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    dstUser.Checked,
                    null,
                    null);

                bool autoWatchTopicsEnabled = this.PageContext.BoardSettings.DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

                // save the settings...
                DB.user_savenotification(
                    userId,
                    true,
                    autoWatchTopicsEnabled,
                    this.PageContext.BoardSettings.DefaultNotificationSetting,
                    PageContext.BoardSettings.DefaultSendDigestEmail);

                // Clearing cache with old Active User Lazy Data ...
                this.PageContext.Cache.Remove(YafCache.GetBoardCacheKey(Constants.Cache.ActiveUserLazyData.FormatWith(userId)));
            }
        }
Beispiel #22
0
        /// <summary>
        /// The forum register_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void ForumRegister_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return;
            }

            var newEmail    = this.Email.Text.Trim();
            var newUsername = this.UserName.Text.Trim();

            if (!ValidationHelper.IsValidEmail(newEmail))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_INVALID_MAIL"));
                return;
            }

            if (UserMembershipHelper.UserExists(this.UserName.Text.Trim(), newEmail))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS"));
                return;
            }

            MembershipCreateStatus status;
            MembershipUser         user = this.Get <MembershipProvider>()
                                          .CreateUser(
                newUsername,
                this.Password.Text.Trim(),
                newEmail,
                this.Question.Text.Trim(),
                this.Answer.Text.Trim(),
                !this.Get <YafBoardSettings>().EmailVerification,
                null,
                out status);

            if (status != MembershipCreateStatus.Success)
            {
                // error of some kind
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_ERROR_CREATE").FormatWith(status));
                return;
            }

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, newUsername);

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create profile
            YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername);

            // setup their inital profile information
            userProfile.Location = this.Location.Text.Trim();
            userProfile.Homepage = this.HomePage.Text.Trim();
            userProfile.Save();

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

            // save the time zone...
            LegacyDb.user_save(
                UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey),
                this.PageContext.PageBoardID,
                null,
                null,
                null,
                this.TimeZones.SelectedValue.ToType <int>(),
                null,
                null,
                null,
                null,
                null,
                null,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                null,
                null,
                null);

            if (this.Get <YafBoardSettings>().EmailVerification)
            {
                this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userID, newUsername);
            }

            LegacyDb.user_savenotification(
                UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey),
                true,
                autoWatchTopicsEnabled,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                this.Get <YafBoardSettings>().DefaultSendDigestEmail);

            // success
            this.PageContext.AddLoadMessage(
                this.GetText("ADMIN_REGUSER", "MSG_CREATED").FormatWith(this.UserName.Text.Trim()));
            YafBuildLink.Redirect(ForumPages.admin_reguser);
        }
Beispiel #23
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);

            // Check user for bot

            /*var spamChecker = new YafSpamCheck();
             * string result;
             * var isPossibleSpamBot = false;
             *
             * var userIpAddress = YafContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress();
             *
             * // Check content for spam
             * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result))
             * {
             *  YafContext.Current.Get<ILogger>().Log(
             *      null,
             *      "Bot Detected",
             *      "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected."
             *          .FormatWith(twitterUser.UserName, twitterUser.Email, userIpAddress, result),
             *      EventLogTypes.SpamBotDetected);
             *
             *  if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(1))
             *  {
             *      // Flag user as spam bot
             *      isPossibleSpamBot = true;
             *  }
             *  else if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(2))
             *  {
             *      message = YafContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE");
             *
             *      if (!YafContext.Current.Get<YafBoardSettings>().BanBotIpOnDetection)
             *      {
             *          return false;
             *      }
             *
             *      YafContext.Current.GetRepository<BannedIP>()
             *          .Save(
             *              null,
             *              userIpAddress,
             *              "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
             *              YafContext.Current.PageUserID);
             *
             *      // Clear cache
             *      YafContext.Current.Get<IDataCache>().Remove(Constants.Cache.BannedIP);
             *
             *      if (YafContext.Current.Get<YafBoardSettings>().LogBannedIP)
             *      {
             *          YafContext.Current.Get<ILogger>()
             *              .Log(
             *                  null,
             *                  "IP BAN of Bot During Registration",
             *                  "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
             *                      userIpAddress),
             *                  EventLogTypes.IpBanSet);
             *      }
             *
             *      return false;
             *  }
             * }*/

            // Create User if not exists?!
            MembershipCreateStatus status;

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            MembershipUser user = YafContext.Current.Get <MembershipProvider>()
                                  .CreateUser(
                twitterUser.UserName,
                pass,
                email,
                "Answer is a generated Pass",
                securityAnswer,
                true,
                null,
                out status);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(twitterUser.UserName);

            userProfile.TwitterId = twitterUser.UserId.ToString();
            userProfile.Twitter   = twitterUser.UserName;
            userProfile.Homepage  = twitterUser.Url.IsSet()
                                       ? twitterUser.Url
                                       : "http://twitter.com/{0}".FormatWith(twitterUser.UserName);
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            userProfile.Save();

            // setup their inital profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafSingleSignOnUser.SendRegistrationNotificationEmail(user, userID.Value);
            }

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

            // send user register notification to the following admin users...
            SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                twitterUser.UserName,
                null,
                email,
                0,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

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

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

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

            LoginTwitterSuccess(true, oAuth, userId, user);

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

            return(true);
        }
Beispiel #24
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);
        }
Beispiel #25
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 (!YafContext.Current.Get <YafBoardSettings>().AllowSingleSignOn)
            {
                message = YafContext.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 = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED3");

                return(false);
            }

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

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

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

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

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

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

            var yafUser = YafUserProfile.GetProfile(userName);

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

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

                    return(false);
                }
            }

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

                return(false);
            }

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

            message = string.Empty;

            return(true);
        }
Beispiel #26
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));
        }
Beispiel #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?
            var isYafProvider = YafContext.Current.Get <MembershipProvider>().Name == "YafMembershipProvider";
            var 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;
                }

                var name  = row.Field <string>("Name").Trim();
                var 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;
                }

                var user = UserMembershipHelper.GetUser(name, false);

                if (user == null)
                {
                    var 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 {name}: {status}");
                    }
                    else
                    {
                        // update the YAF table with the ProviderKey -- update the provider table if this is the YAF provider...
                        YafContext.Current.GetRepository <User>().Migrate(row["UserID"].ToType <int>(), user.ProviderUserKey.ToString(), 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...
                        var userProfile = YafUserProfile.GetProfile(name);

                        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...
                    YafContext.Current.GetRepository <User>().Migrate(row["UserID"].ToType <int>(), user.ProviderUserKey.ToString(), false);
                }

                // setup roles for this user...
                using (var dtGroups = YafContext.Current.GetRepository <UserGroup>().ListAsDataTable(row["UserID"]))
                {
                    foreach (DataRow rowGroup in dtGroups.Rows)
                    {
                        AddUserToRole(user.UserName, rowGroup["Name"].ToString());
                    }
                }
            });
        }
Beispiel #28
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);

            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>());
        }
Beispiel #29
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); ");
        }
Beispiel #30
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, 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);
        }