Esempio n. 1
0
        /// <summary>
        /// Connects the user.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="parameters">
        /// The access token.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the connect was successful or not
        /// </returns>
        public bool ConnectUser(HttpRequest request, string parameters, out string message)
        {
            var 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;
                }
            }

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

                    return(false);
                }

                // Update profile with Google informations
                var userProfile = YafContext.Current.Profile;

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

                userProfile.Gender = userGender;

                userProfile.Save();

                // save avatar
                LegacyDb.user_saveavatar(YafContext.Current.PageUserID, googleUser.ProfileImage, null, null);

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

                message = string.Empty;

                return(true);
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_GOOGLE_FAILED");
            return(false);
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        /// <summary>
        /// Handles the CreatedUser event of the CreateUserWizard1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void CreateUserWizard1_CreatedUser([NotNull] object sender, [NotNull] EventArgs e)
        {
            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.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");
                string email = emailTextBox.Text.Trim();

                this.SendVerificationEmail(user, email, userID);
            }

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

            if (this.IsPossibleSpamBot)
            {
                YafSingleSignOnUser.SendSpamBotNotificationToAdmins(user, userID.Value);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Call the Events when the Twitter Login was Successfully
        /// </summary>
        /// <param name="newUser">
        /// The new user.
        /// </param>
        /// <param name="oAuth">
        /// The twitter oAUTH.
        /// </param>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <param name="user">
        /// The user.
        /// </param>
        private static void LoginTwitterSuccess(
            [NotNull] bool newUser,
            [NotNull] OAuthTwitter oAuth,
            [NotNull] int userId,
            [CanBeNull] MembershipUser user)
        {
            if (newUser)
            {
                YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));
            }
            else
            {
                // Clearing cache with old Active User Lazy Data ...
                YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(userId));
            }

            // Store Tokens in Session (Could Bes Stored in DB but it would be a Security Problem)
            YafContext.Current.Get <IYafSession>().TwitterToken       = oAuth.Token;
            YafContext.Current.Get <IYafSession>().TwitterTokenSecret = oAuth.TokenSecret;

            YafSingleSignOnUser.LoginSuccess(AuthService.twitter, user.UserName, userId, true);
        }
Esempio n. 5
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);
        }
Esempio n. 6
0
        /// <summary>
        /// Connects the user.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="parameters">
        /// The access token.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the connect was successful or not
        /// </returns>
        public bool ConnectUser(HttpRequest request, string parameters, out string message)
        {
            var facebookUser = this.GetFacebookUser(request, parameters);

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

            var userGender = 0;

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

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

            // Only validated logins can go here
            if (!YafContext.Current.IsGuest)
            {
                // match the email address...
                if (facebookUser.Email != YafContext.Current.CurrentUserData.Email)
                {
                    message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOKNAME_NOTMATCH");

                    return(false);
                }

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

                userProfile.Facebook   = facebookUser.ProfileURL;
                userProfile.FacebookId = facebookUser.UserID;
                userProfile.Homepage   = facebookUser.ProfileURL;

                if (facebookUser.Birthday.IsSet())
                {
                    DateTime userBirthdate;
                    var      ci = CultureInfo.CreateSpecificCulture("en-US");
                    DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate);

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

                userProfile.RealName = facebookUser.Name;
                userProfile.Gender   = userGender;

                if (facebookUser.Location != null && facebookUser.Location.Name.IsSet())
                {
                    userProfile.Location = facebookUser.Location.Name;
                }

                userProfile.Save();

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

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

                message = string.Empty;

                return(true);
            }

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED");
            return(false);
        }
Esempio n. 7
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);
        }
Esempio n. 8
0
        /// <summary>
        /// Creates the or assign twitter user.
        /// </summary>
        /// <param name="twitterUser">The twitter user.</param>
        /// <param name="oAuth">The oAUTH.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Create User if not exists?! Doesnt work because there is no Email
            var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

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

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

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

                var twitterUser = tweetAPI.GetUser();

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

                            return(false);
                        }

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

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

                        userProfile.Save();

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

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

                        message = string.Empty;

                        return(true);
                    }
                }
            }

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

            return(false);
        }
Esempio n. 10
0
        /// <summary>
        /// Check if we need to display the Login form
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void SingleSignOnOptionsChanged(object sender, EventArgs e)
        {
            var singleSignOnOptions = this.Login1.FindControlAs <RadioButtonList>("SingleSignOnOptions");

            var userNameRow = this.Login1.FindControlAs <HtmlTableRow>("UserNameRow");
            var passwordRow = this.Login1.FindControlAs <HtmlTableRow>("PasswordRow");
            var forumLogin  = this.Login1.FindControlAs <Button>("LoginButton");

            var facebookHolder = this.Login1.FindControlAs <PlaceHolder>("FacebookHolder");
            var twitterHolder  = this.Login1.FindControlAs <PlaceHolder>("TwitterHolder");
            var googleHolder   = this.Login1.FindControlAs <PlaceHolder>("GoogleHolder");

            var loginAuth =
                (AuthService)
                Enum.Parse(typeof(AuthService), this.Get <HttpRequestBase>().QueryString.GetFirstOrDefaultAs <string>("auth"), true);

            switch (singleSignOnOptions.SelectedValue)
            {
            case "connect":
            {
                userNameRow.Visible = true;
                passwordRow.Visible = true;
                forumLogin.Visible  = true;

                facebookHolder.Visible = false;
                twitterHolder.Visible  = false;
                googleHolder.Visible   = false;

                switch (loginAuth)
                {
                case AuthService.twitter:
                {
                    this.Login1.DestinationPageUrl = YafSingleSignOnUser.GenerateLoginUrl(
                        AuthService.twitter,
                        false,
                        true);
                }

                break;

                case AuthService.facebook:
                {
                    this.Login1.DestinationPageUrl = YafSingleSignOnUser.GenerateLoginUrl(
                        AuthService.facebook,
                        false,
                        true);
                }

                break;

                case AuthService.google:
                {
                    this.Login1.DestinationPageUrl = YafSingleSignOnUser.GenerateLoginUrl(
                        AuthService.google,
                        false,
                        true);
                }

                break;
                }
            }

            break;

            default:
            {
                userNameRow.Visible = false;
                passwordRow.Visible = false;
                forumLogin.Visible  = false;

                switch (loginAuth)
                {
                case AuthService.twitter:
                {
                    twitterHolder.Visible = true;
                }

                break;

                case AuthService.facebook:
                {
                    facebookHolder.Visible = true;
                }

                break;

                case AuthService.google:
                {
                    googleHolder.Visible = true;
                }

                break;
                }
            }

            break;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (this.IsPostBack)
            {
                return;
            }

            this.Login1.MembershipProvider = Config.MembershipProvider;

            this.PageLinks.AddRoot();
            this.PageLinks.AddLink(this.GetText("title"));

            // Login1.CreateUserText = "Sign up for a new account.";
            // Login1.CreateUserUrl = YafBuildLink.GetLink( ForumPages.register );
            this.Login1.PasswordRecoveryText = this.GetText("lostpassword");
            this.Login1.PasswordRecoveryUrl  = YafBuildLink.GetLink(ForumPages.recoverpassword);
            this.Login1.FailureText          = this.GetText("password_error");

            this.Login1.DestinationPageUrl =
                this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("ReturnUrl").IsSet()
                    ? this.HtmlEncode(this.Server.UrlDecode(this.Request.QueryString.GetFirstOrDefault("ReturnUrl")))
                    : YafBuildLink.GetLink(ForumPages.forum);

            // localize controls
            var rememberMe       = this.Login1.FindControlAs <CheckBox>("RememberMe");
            var userName         = this.Login1.FindControlAs <TextBox>("UserName");
            var password         = this.Login1.FindControlAs <TextBox>("Password");
            var forumLogin       = this.Login1.FindControlAs <Button>("LoginButton");
            var passwordRecovery = this.Login1.FindControlAs <Button>("PasswordRecovery");
            var cancelAuthLogin  = this.Login1.FindControlAs <ThemeButton>("Cancel");

            var userNameRow = this.Login1.FindControlAs <PlaceHolder>("UserNameRow");
            var passwordRow = this.Login1.FindControlAs <PlaceHolder>("PasswordRow");

            var singleSignOnOptionsRow = this.Login1.FindControlAs <PlaceHolder>("SingleSignOnOptionsRow");
            var singleSignOnOptions    = this.Login1.FindControlAs <RadioButtonList>("SingleSignOnOptions");

            var registerLink            = this.Login1.FindControlAs <ThemeButton>("RegisterLink");
            var registerLinkPlaceHolder = this.Login1.FindControlAs <PlaceHolder>("RegisterLinkPlaceHolder");

            var singleSignOnRow = this.Login1.FindControlAs <PlaceHolder>("SingleSignOnRow");

            var facebookHolder = this.Login1.FindControlAs <PlaceHolder>("FacebookHolder");
            var facebookLogin  = this.Login1.FindControlAs <ThemeButton>("FacebookLogin");

            var twitterHolder = this.Login1.FindControlAs <PlaceHolder>("TwitterHolder");
            var twitterLogin  = this.Login1.FindControlAs <ThemeButton>("TwitterLogin");

            var googleHolder = this.Login1.FindControlAs <PlaceHolder>("GoogleHolder");
            var googleLogin  = this.Login1.FindControlAs <ThemeButton>("GoogleLogin");

            var facebookRegister = this.Login1.FindControlAs <ThemeButton>("FacebookRegister");
            var twitterRegister  = this.Login1.FindControlAs <ThemeButton>("TwitterRegister");
            var googleRegister   = this.Login1.FindControlAs <ThemeButton>("GoogleRegister");

            userName.Focus();

            /*
             *  RequiredFieldValidator usernameRequired = ( RequiredFieldValidator ) Login1.FindControl( "UsernameRequired" );
             *  RequiredFieldValidator passwordRequired = ( RequiredFieldValidator ) Login1.FindControl( "PasswordRequired" );
             *
             *  usernameRequired.ToolTip = usernameRequired.ErrorMessage = GetText( "REGISTER", "NEED_USERNAME" );
             *  passwordRequired.ToolTip = passwordRequired.ErrorMessage = GetText( "REGISTER", "NEED_PASSWORD" );
             */
            if (rememberMe != null)
            {
                rememberMe.Text = this.GetText("auto");
            }

            if (forumLogin != null)
            {
                forumLogin.Text = this.GetText("FORUM_LOGIN");
            }

            if (passwordRecovery != null)
            {
                passwordRecovery.Text = this.GetText("LOSTPASSWORD");
            }

            if (password != null && forumLogin != null)
            {
                password.Attributes.Add(
                    "onkeydown",
                    $@"if(event.which || event.keyCode){{if ((event.which == 13) || (event.keyCode == 13)) {{
                              document.getElementById('{forumLogin.ClientID}').click();return false;}}}} else {{return true}}; ");
            }

            if (registerLinkPlaceHolder != null && this.PageContext.IsGuest &&
                !this.Get <YafBoardSettings>().DisableRegistrations&& !Config.IsAnyPortal)
            {
                registerLinkPlaceHolder.Visible = true;

                registerLink.TextLocalizedTag = "REGISTER_INSTEAD";
            }

            if (this.Get <YafBoardSettings>().AllowSingleSignOn &&
                (Config.FacebookAPIKey.IsSet() || Config.TwitterConsumerKey.IsSet() || Config.GoogleClientID.IsSet()))
            {
                singleSignOnRow.Visible = true;

                var facebookEnabled = Config.FacebookAPIKey.IsSet() && Config.FacebookSecretKey.IsSet();
                var twitterEnabled  = Config.TwitterConsumerKey.IsSet() && Config.TwitterConsumerSecret.IsSet();
                var googleEnabled   = Config.GoogleClientID.IsSet() && Config.GoogleClientSecret.IsSet();

                var loginAuth = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("auth");

                if (loginAuth.IsNotSet())
                {
                    if (facebookEnabled)
                    {
                        facebookRegister.Visible           = true;
                        facebookRegister.Text              = this.GetTextFormatted("AUTH_CONNECT", "Facebook");
                        facebookRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP";
                        facebookRegister.ParamTitle0       = "Facebook";
                    }

                    if (twitterEnabled)
                    {
                        twitterRegister.Visible           = true;
                        twitterRegister.Text              = this.GetTextFormatted("AUTH_CONNECT", "Twitter");
                        twitterRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP";
                        twitterRegister.ParamTitle0       = "Twitter";
                    }

                    if (googleEnabled)
                    {
                        googleRegister.Visible           = true;
                        googleRegister.Text              = this.GetTextFormatted("AUTH_CONNECT", "Google");
                        googleRegister.TitleLocalizedTag = "AUTH_CONNECT_HELP";
                        googleRegister.ParamTitle0       = "Google";
                    }
                }
                else
                {
                    singleSignOnOptionsRow.Visible = true;

                    facebookRegister.Visible = false;
                    twitterRegister.Visible  = false;
                    googleRegister.Visible   = false;

                    userNameRow.Visible             = false;
                    passwordRow.Visible             = false;
                    registerLinkPlaceHolder.Visible = false;
                    passwordRecovery.Visible        = false;
                    forumLogin.Visible = false;
                    rememberMe.Visible = false;

                    cancelAuthLogin.Visible = true;

                    switch ((AuthService)Enum.Parse(typeof(AuthService), loginAuth, true))
                    {
                    case AuthService.twitter:
                    {
                        twitterHolder.Visible = twitterEnabled;

                        singleSignOnOptions.Items.Clear();

                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value    = "login",
                                Text     = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Twitter"),
                                Selected = true
                            });
                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value = "connect",
                                Text  =
                                    this.GetTextFormatted(
                                        "AUTH_CONNECT_ACCOUNT",
                                        "Twitter",
                                        this.GetText("AUTH_CONNECT_TWITTER"))
                            });

                        if (twitterEnabled)
                        {
                            try
                            {
                                var twitterLoginUrl = YafSingleSignOnUser.GenerateLoginUrl(AuthService.twitter, true);

                                // Redirect the user to Twitter for authorization.
                                twitterLogin.Attributes.Add("onclick", twitterLoginUrl);
                            }
                            catch (Exception exception)
                            {
                                this.Logger.Warn(
                                    exception,
                                    "YAF encountered an error when loading the Twitter Login Link");

                                twitterHolder.Visible = false;
                            }
                        }
                    }

                    break;

                    case AuthService.facebook:
                    {
                        facebookHolder.Visible = facebookEnabled;

                        singleSignOnOptions.Items.Clear();

                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value    = "login",
                                Text     = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Facebook"),
                                Selected = true
                            });
                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value = "connect",
                                Text  =
                                    this.GetTextFormatted(
                                        "AUTH_CONNECT_ACCOUNT",
                                        "Facebook",
                                        this.GetText("AUTH_CONNECT_FACEBOOK"))
                            });

                        if (facebookEnabled)
                        {
                            try
                            {
                                var facebookLoginUrl = YafSingleSignOnUser.GenerateLoginUrl(AuthService.facebook, true);

                                // Redirect the user to Twitter for authorization.
                                facebookLogin.Attributes.Add(
                                    "onclick",
                                    $"location.href='{facebookLoginUrl}'");
                            }
                            catch (Exception exception)
                            {
                                this.Logger.Warn(
                                    exception,
                                    "YAF encountered an error when loading the facebook Login Link");

                                facebookHolder.Visible = false;
                            }
                        }
                    }

                    break;

                    case AuthService.google:
                    {
                        googleHolder.Visible = googleEnabled;

                        singleSignOnOptions.Items.Clear();

                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value    = "login",
                                Text     = this.GetTextFormatted("AUTH_LOGIN_EXISTING", "Google"),
                                Selected = true
                            });
                        singleSignOnOptions.Items.Add(
                            new ListItem
                            {
                                Value = "connect",
                                Text  =
                                    this.GetTextFormatted(
                                        "AUTH_CONNECT_ACCOUNT",
                                        "Facebook",
                                        this.GetText("AUTH_CONNECT_GOOGLE"))
                            });

                        if (googleEnabled)
                        {
                            try
                            {
                                var googleLoginUrl = YafSingleSignOnUser.GenerateLoginUrl(AuthService.google, true);

                                // Redirect the user to Twitter for authorization.
                                googleLogin.Attributes.Add(
                                    "onclick",
                                    $"location.href='{googleLoginUrl}'");
                            }
                            catch (Exception exception)
                            {
                                this.Logger.Warn(
                                    exception,
                                    "YAF encountered an error when loading the Google Login Link");

                                googleHolder.Visible = false;
                            }
                        }
                    }

                    break;
                    }
                }
            }

            this.DataBind();
        }
Esempio n. 12
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);
        }
Esempio n. 13
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);
        }
Esempio n. 14
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);
        }
Esempio n. 15
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);
        }