/// <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 <BoardSettings>().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.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; userProfile.Save(); // save avatar YafContext.Current.GetRepository <User>().SaveAvatar(YafContext.Current.PageUserID, googleUser.ProfileImage, null, null); SingleSignOnUser.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); }
/// <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 <BoardSettings>().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(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)) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_GOOGLE_FAILED2"); return(false); } SingleSignOnUser.LoginSuccess(AuthService.google, userName, yafUserData.UserID, true); message = string.Empty; return(true); }
/// <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(string.Format(Constants.Cache.ActiveUserLazyData, userId)); } // Store Tokens in Session (Could Bes Stored in DB but it would be a Security Problem) YafContext.Current.Get <ISession>().TwitterToken = oAuth.Token; YafContext.Current.Get <ISession>().TwitterTokenSecret = oAuth.TokenSecret; SingleSignOnUser.LoginSuccess(AuthService.twitter, user.UserName, userId, true); }
/// <summary> /// Creates the facebook user /// </summary> /// <param name="facebookUser"> /// The facebook user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateFacebookUser(FacebookUser facebookUser, int userGender, out string message) { if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var isPossibleSpamBot = false; var userIpAddress = BoardContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (BoardContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(facebookUser.UserName, facebookUser.Email, userIpAddress, out var result)) { BoardContext.Current.Get <ILogger>().Log( null, "Bot Detected", $"Bot Check detected a possible SPAM BOT: (user name : '{facebookUser.UserName}', email : '{facebookUser.Email}', ip: '{userIpAddress}', reason : {result}), user was rejected.", EventLogTypes.SpamBotDetected); if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(2)) { message = BoardContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!BoardContext.Current.Get <BoardSettings>().BanBotIpOnDetection) { return(false); } BoardContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, $"A spam Bot who was trying to register was banned by IP {userIpAddress}", BoardContext.Current.PageUserID); // Clear cache BoardContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (BoardContext.Current.Get <BoardSettings>().LogBannedIP) { BoardContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", $"A spam Bot who was trying to register was banned by IP {userIpAddress}", EventLogTypes.IpBanSet); } return(false); } } var memberShipProvider = BoardContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( facebookUser.UserName, pass, facebookUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out var status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, facebookUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = Utils.UserProfile.GetProfile(facebookUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.Facebook = facebookUser.ProfileURL; userProfile.FacebookId = facebookUser.UserID; userProfile.Homepage = facebookUser.ProfileURL; if (facebookUser.Birthday.IsSet()) { var ci = CultureInfo.CreateSpecificCulture("en-US"); DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out var userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date) { userProfile.Birthday = userBirthdate; } } userProfile.RealName = facebookUser.Name; userProfile.Gender = userGender; if (facebookUser.Location != null && facebookUser.Location.Name.IsSet()) { userProfile.Location = facebookUser.Location.Name; } if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService) { var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator(); if (userIpLocator != null) { userProfile.Country = userIpLocator["CountryCode"]; } } userProfile.Save(); // setup their initial profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (BoardContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... BoardContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { BoardContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... BoardContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_FACEBOOK_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; BoardContext.Current.GetRepository <User>().Save( userId, BoardContext.Current.PageBoardID, facebookUser.UserName, facebookUser.UserName, facebookUser.Email, TimeZoneInfo.Local.Id, null, null, null, null, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, TimeZoneInfo.Local.SupportsDaylightSavingTime, null, null); // save the settings... BoardContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), BoardContext.Current.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar BoardContext.Current.GetRepository <User>().SaveAvatar( userId, $"https://graph.facebook.com/v3.3/{facebookUser.UserID}/picture", null, null); BoardContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); SingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true); message = string.Empty; return(true); }
/// <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 (!BoardContext.Current.IsGuest) { // match the email address... if (facebookUser.Email != BoardContext.Current.CurrentUserData.Email) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOKNAME_NOTMATCH"); return(false); } // Update profile with facebook informations var userProfile = BoardContext.Current.Profile; userProfile.Facebook = facebookUser.ProfileURL; userProfile.FacebookId = facebookUser.UserID; userProfile.Homepage = facebookUser.ProfileURL; if (facebookUser.Birthday.IsSet()) { var ci = CultureInfo.CreateSpecificCulture("en-US"); DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out var userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date) { userProfile.Birthday = userBirthdate; } } userProfile.RealName = facebookUser.Name; userProfile.Gender = userGender; if (facebookUser.Location != null && facebookUser.Location.Name.IsSet()) { userProfile.Location = facebookUser.Location.Name; } userProfile.Save(); // save avatar BoardContext.Current.GetRepository <User>().SaveAvatar( BoardContext.Current.PageUserID, $"https://graph.facebook.com/v3.3/{facebookUser.UserID}/picture", null, null); SingleSignOnUser.LoginSuccess(AuthService.facebook, null, BoardContext.Current.PageUserID, false); message = string.Empty; return(true); } message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED"); return(false); }
/// <summary> /// Logins the or create user. /// </summary> /// <param name="request"> /// The request. /// </param> /// <param name="parameters"> /// The access token. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if Login was successful or not /// </returns> public bool LoginOrCreateUser(HttpRequest request, string parameters, out string message) { if (!BoardContext.Current.Get <BoardSettings>().AllowSingleSignOn) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_DEACTIVATED"); return(false); } var facebookUser = this.GetFacebookUser(request, parameters); // Check if user name is null if (facebookUser.UserName.IsNotSet()) { facebookUser.UserName = facebookUser.Name; } if (facebookUser.Email.IsNotSet()) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED3"); return(false); } // Check if user exists var userName = BoardContext.Current.Get <MembershipProvider>().GetUserNameByEmail(facebookUser.Email); if (userName.IsNotSet()) { var userGender = 0; if (!facebookUser.Gender.IsSet()) { return(CreateFacebookUser(facebookUser, userGender, out message)); } switch (facebookUser.Gender) { case "male": userGender = 1; break; case "female": userGender = 2; break; } // Create User if not exists?! return(CreateFacebookUser(facebookUser, userGender, out message)); } var yafUser = Utils.UserProfile.GetProfile(userName); var yafUserData = new CombinedUserDataHelper(BoardContext.Current.Get <MembershipProvider>().GetUser(userName, true)); // Legacy Handling if (ValidationHelper.IsNumeric(yafUser.Facebook)) { if (!yafUser.Facebook.Equals(facebookUser.UserID)) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED2"); return(false); } } if (!yafUser.FacebookId.Equals(facebookUser.UserID)) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FACEBOOK_FAILED2"); return(false); } SingleSignOnUser.LoginSuccess(AuthService.facebook, userName, yafUserData.UserID, true); message = string.Empty; return(true); }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser"> /// The Google user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (YafContext.Current.Get <BoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var isPossibleSpamBot = false; var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (YafContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result)) { YafContext.Current.Get <ILogger>().Log( null, "Bot Detected", $"Bot Check detected a possible SPAM BOT: (user name : '{googleUser.UserName}', email : '{googleUser.Email}', ip: '{userIpAddress}', reason : {result}), user was rejected.", EventLogTypes.SpamBotDetected); if (YafContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (YafContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(2)) { message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!YafContext.Current.Get <BoardSettings>().BanBotIpOnDetection) { return(false); } YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, $"A spam Bot who was trying to register was banned by IP {userIpAddress}", YafContext.Current.PageUserID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <BoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", $"A spam Bot who was trying to register was banned by IP {userIpAddress}", EventLogTypes.IpBanSet); } return(false); } } var memberShipProvider = YafContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( googleUser.UserName, pass, googleUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out var status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(googleUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; if (YafContext.Current.Get <BoardSettings>().EnableIPInfoService) { var userIpLocator = YafContext.Current.Get <IIpInfoService>().GetUserIpLocator(); if (userIpLocator != null) { userProfile.Country = userIpLocator["CountryCode"]; var location = new StringBuilder(); if (userIpLocator["RegionName"] != null && userIpLocator["RegionName"].IsSet() && !userIpLocator["RegionName"].Equals("-")) { location.Append(userIpLocator["RegionName"]); } if (userIpLocator["CityName"] != null && userIpLocator["CityName"].IsSet() && !userIpLocator["CityName"].Equals("-")) { location.AppendFormat(", {0}", userIpLocator["CityName"]); } userProfile.Location = location.ToString(); } } userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } 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 <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; YafContext.Current.GetRepository <User>().Save( userId, YafContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, TimeZoneInfo.Local.Id, null, null, null, null, null, YafContext.Current.Get <BoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, TimeZoneInfo.Local.SupportsDaylightSavingTime, null, null); // save the settings... YafContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <BoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar YafContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); SingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }
/// <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 <BoardSettings>().DisableRegistrations) { // Because twitter doesn't 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 var userProfile = YafContext.Current.Profile; userProfile.TwitterId = twitterUser.UserId.ToString(); userProfile.Twitter = twitterUser.UserName; userProfile.Homepage = twitterUser.Url.IsSet() ? twitterUser.Url : $"http://twitter.com/{twitterUser.UserName}"; userProfile.RealName = twitterUser.Name; userProfile.Interests = twitterUser.Description; userProfile.Location = twitterUser.Location; userProfile.Save(); // save avatar if (twitterUser.ProfileImageUrl.IsSet()) { YafContext.Current.GetRepository <User>().SaveAvatar( YafContext.Current.PageUserID, twitterUser.ProfileImageUrl, null, null); } SingleSignOnUser.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); }