Exemple #1
0
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with liveid token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(facebookUserId))
        {
            string password        = passStrength.Text;
            string currentSiteName = CMSContext.CurrentSiteName;

            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.facebook.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.facebook.fillvalidemail")).Result;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (String.IsNullOrEmpty(errorMessage)))
            {
                if (String.IsNullOrEmpty(password))
                {
                    errorMessage = GetString("mem.facebook.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if ((String.IsNullOrEmpty(errorMessage)) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), currentSiteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if ((String.IsNullOrEmpty(errorMessage)) && UserInfoProvider.NameIsReserved(currentSiteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (String.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    // Register new user
                    string error = this.DisplayMessage;
                    ui = UserInfoProvider.AuthenticateFacebookConnectUser(facebookUserId, currentSiteName, true, false, ref error);
                    this.DisplayMessage = error;

                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // Remove live user object from session, won't be needed
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        // Send registration e-mails
                        UserInfoProvider.SendRegistrationEmails(ui, this.ApprovalPage, password, true, this.SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty))
                        {
                            UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress);
                        }

                        // Log registration into analytics
                        UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, currentSiteName, ui);

                        // Log activity
                        if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) &&
                            ActivitySettingsHelper.UserRegistrationEnabled(currentSiteName))
                        {
                            int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId);
                            TreeNode currDoc = CMSContext.CurrentDocument;
                            ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath,
                                                                        (currDoc != null ? currDoc.NodeID : 0), currentSiteName, CMSContext.Campaign, (currDoc != null ? currDoc.DocumentCulture : null));
                        }

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        // Display error message
                        if (!String.IsNullOrEmpty(this.DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = this.DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect(ResolveUrl("~/Default.aspx"));
                        }
                    }
                }
            }
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            this.Visible = false;
        }
        else
        {
            if (QueryHelper.GetInteger("logout", 0) > 0)
            {
                // Sign out from CMS
                FormsAuthentication.SignOut();
                CMSContext.ClearShoppingCart();
                CMSContext.CurrentUser = null;
                Response.Cache.SetNoStore();
                URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, "logout"));
                return;
            }

            string currentSiteName = CMSContext.CurrentSiteName;
            if (!String.IsNullOrEmpty(currentSiteName) && SettingsKeyProvider.GetBoolValue(currentSiteName + ".CMSEnableFacebookConnect"))
            {
                // Check Facebook Connect settings
                if (!FacebookConnectHelper.FacebookIsAvailable(currentSiteName))
                {
                    // Display warning message in "Design mode"
                    if (DisplayMessage())
                    {
                        return;
                    }

                    this.Visible = false;
                    return;
                }

                // Try to retrieve return URL from query
                string returnUrl = QueryHelper.GetString("returnurl", null);

                // Init Facebook Connect
                if (this.Page is ContentPage)
                {
                    // Adding XML namespace
                    ((ContentPage)this.Page).XmlNamespace = FacebookConnectHelper.GetFacebookXmlNamespace();
                }
                // Init FB connect
                ltlScript.Text = FacebookConnectHelper.GetFacebookInitScriptForSite(currentSiteName);
                // Return URL
                string currentUrl       = URLHelper.AddParameterToUrl(URLHelper.CurrentURL, "logout", "1");
                string additionalScript = "window.location.href=" + ScriptHelper.GetString(URLHelper.GetAbsoluteUrl(currentUrl)) + "; return false;";
                // Logout script for FB connect
                string logoutScript = FacebookConnectHelper.GetFacebookLogoutScriptForSignOut(URLHelper.CurrentURL, FacebookConnectHelper.GetFacebookApiKey(currentSiteName), additionalScript);

                string facebookUserId       = "";
                bool   facebookCookiesValid = FacebookConnectHelper.GetFacebookSessionInfo(currentSiteName, out facebookUserId) == FacebookValidationEnum.ValidSignature;

                // If user is already authenticated
                if (CMSContext.CurrentUser.IsAuthenticated())
                {
                    // Is user logged in using Facebook Connect?
                    if (!facebookCookiesValid || ((CMSContext.CurrentUser.UserSettings != null) &&
                                                  (CMSContext.CurrentUser.UserSettings.UserFacebookID != facebookUserId)))
                    {  // no, user is not logged in by Facebook Connect
                        logoutScript = additionalScript;
                    }

                    // Hide Facebook Connect button
                    plcFBButton.Visible = false;

                    // If signout should be visible and user has FacebookID registered
                    if (ShowSignOut && !String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.UserFacebookID))
                    {
                        // If only text is set use text/button link
                        if (!String.IsNullOrEmpty(SignOutText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                btnSignOut.OnClientClick = logoutScript;
                                btnSignOut.Text          = SignOutText;
                                btnSignOut.Visible       = true;
                            }
                            // Text link
                            else
                            {
                                lnkSignOutLink.Text    = SignOutText;
                                lnkSignOutLink.Visible = true;
                                lnkSignOutLink.Attributes.Add("onclick", logoutScript);
                                lnkSignOutLink.Attributes.Add("style", "cursor:pointer;");
                            }
                        }
                        // Image link
                        else
                        {
                            string signOutImageUrl = SignOutImageURL;
                            // Use default image if none is specified
                            if (String.IsNullOrEmpty(signOutImageUrl))
                            {
                                signOutImageUrl = GetImageUrl("Others/FacebookConnect/signout.gif");
                            }
                            imgSignOut.ImageUrl        = ResolveUrl(signOutImageUrl);
                            imgSignOut.Visible         = true;
                            imgSignOut.AlternateText   = GetString("webparts_membership_signoutbutton.signout");
                            lnkSignOutImageBtn.Visible = true;
                            lnkSignOutImageBtn.Attributes.Add("onclick", logoutScript);
                            lnkSignOutImageBtn.Attributes.Add("style", "cursor:pointer;");
                        }
                    }
                    else
                    {
                        Visible = false;
                    }
                }
                // Sign In
                else
                {
                    if ((QueryHelper.GetInteger(CONFIRMATION_URLPARAMETER, 0) > 0) && facebookCookiesValid)
                    {
                        if (!String.IsNullOrEmpty(facebookUserId))
                        {
                            UserInfo ui = UserInfoProvider.GetUserInfoByFacebookConnectID(facebookUserId);
                            // Claimed Facebook ID is in DB
                            if (ui != null)
                            {
                                // Login existing user
                                if ((ui != null) && ui.Enabled)
                                {
                                    // Ban IP addresses which are blocked for login
                                    BannedIPInfoProvider.CheckIPandRedirect(currentSiteName, BanControlEnum.Login);

                                    // Create autentification cookie
                                    UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" });
                                    UserInfoProvider.SetPreferredCultures(ui);

                                    // Log activity
                                    if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.UserLoginEnabled(currentSiteName))
                                    {
                                        int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                        ActivityLogHelper.UpdateContactLastLogon(contactId);
                                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                                        {
                                            TreeNode currDoc = CMSContext.CurrentDocument;
                                            ActivityLogProvider.LogLoginActivity(contactId,
                                                                                 ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture);
                                        }
                                    }

                                    // Redirect user
                                    if (String.IsNullOrEmpty(returnUrl))
                                    {
                                        returnUrl = URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, CONFIRMATION_URLPARAMETER);
                                    }

                                    URLHelper.Redirect(returnUrl);
                                }
                                // Otherwise is user disabled
                                else
                                {
                                    lblError.Text    = GetString("membership.userdisabled");
                                    lblError.Visible = true;
                                }
                            }
                            // Claimed Facebook ID not found  = save new user
                            else
                            {
                                // Check whether additional user info page is set
                                string additionalInfoPage = SettingsKeyProvider.GetStringValue(currentSiteName + ".CMSRequiredFacebookPage").Trim();

                                // No page set, user can be created
                                if (String.IsNullOrEmpty(additionalInfoPage))
                                {
                                    // Register new user
                                    string error = null;
                                    ui = UserInfoProvider.AuthenticateFacebookConnectUser(facebookUserId, currentSiteName, false, true, ref error);

                                    // If user was found or successfuly created
                                    if (ui != null)
                                    {
                                        // If user is enabled
                                        if (ui.Enabled)
                                        {
                                            // Create authentification cookie
                                            UserInfoProvider.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new string[] { "facebooklogon" });
                                            // Log activity
                                            if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.UserLoginEnabled(currentSiteName))
                                            {
                                                int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                                ActivityLogHelper.UpdateContactLastLogon(contactId);
                                                if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                                                {
                                                    TreeNode currDoc = CMSContext.CurrentDocument;
                                                    ActivityLogProvider.LogLoginActivity(contactId,
                                                                                         ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture);
                                                }
                                            }
                                        }

                                        // Send registration e-mails
                                        // E-mail confirmation is not required as user already provided confirmation by successful login using Facebook connect
                                        UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false);

                                        // Notify administrator
                                        if (this.NotifyAdministrator && !String.IsNullOrEmpty(this.FromAddress) && !String.IsNullOrEmpty(this.ToAddress))
                                        {
                                            UserInfoProvider.NotifyAdministrator(ui, this.FromAddress, this.ToAddress);
                                        }

                                        // Log registration into analytics
                                        UserInfoProvider.TrackUserRegistration(this.TrackConversionName, this.ConversionValue, currentSiteName, ui);

                                        // Log activity
                                        if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(currentSiteName) && ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui) &&
                                            ActivitySettingsHelper.UserRegistrationEnabled(currentSiteName))
                                        {
                                            int contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                                            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(ui, contactId);
                                            TreeNode currDoc = CMSContext.CurrentDocument;
                                            ActivityLogProvider.LogRegistrationActivity(contactId,
                                                                                        ui, URLHelper.CurrentRelativePath, currDoc.NodeID, currentSiteName, CMSContext.Campaign, currDoc.DocumentCulture);
                                        }
                                    }

                                    // Redirect when authentication was succesfull
                                    if (String.IsNullOrEmpty(error))
                                    {
                                        if (!String.IsNullOrEmpty(returnUrl))
                                        {
                                            URLHelper.Redirect(URLHelper.GetAbsoluteUrl(returnUrl));
                                        }
                                        else
                                        {
                                            URLHelper.Redirect(URLHelper.RemoveParameterFromUrl(URLHelper.CurrentURL, CONFIRMATION_URLPARAMETER));
                                        }
                                    }
                                    // Display error otherwise
                                    else
                                    {
                                        lblError.Text    = error;
                                        lblError.Visible = true;
                                    }
                                }
                                // Additional information page is set
                                else
                                {
                                    // Store user object in session for additional info page
                                    SessionHelper.SetValue(SESSION_NAME_USERDATA, facebookUserId);

                                    // Redirect to additional info page
                                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                                    if (!String.IsNullOrEmpty(returnUrl))
                                    {
                                        // Add return URL to parameter
                                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                                    }
                                    URLHelper.Redirect(targetURL);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                // Show warning message in "Design mode"
                this.Visible = DisplayMessage();
            }
        }
    }