Beispiel #1
0
        private bool HandleLiveId(string token, string host)
        {
            Tuple <bool, bool> inCache = IsInCache(host, token);

            if (inCache.Item1)
            {
                return(inCache.Item2);
            }

            WindowsLiveLogin wll = new WindowsLiveLogin(Constants.LiveIdappId, Constants.LiveIdappsecret, Constants.LiveIdsecurityAlgorithm, true, Constants.LiveIdpolicyURL, Constants.LiveIdreturnURL);

            WindowsLiveLogin.User user = wll.ProcessToken(token);


            if (user == null)
            {
                ThrowRejection(HttpStatusCode.Unauthorized, "Invalid user token in authorization header.");
            }

            if (DateTime.UtcNow.Subtract(user.Timestamp).TotalMilliseconds > Constants.PrivilegeLevelTokenExpiry[Constants.LiveId] * 1000)
            {
                ThrowRejection(HttpStatusCode.Unauthorized, "Expired token being presented. Token Expiry: " + Constants.PrivilegeLevelTokenExpiry[Constants.LiveId] + " seconds");
            }

            bool retVal = IsValidAccess(host, Constants.LiveId, user.Id);

            UpdateCache(host, token, user.Timestamp, retVal);     // *** updating cache

            return(retVal);
        }
    /// <summary>
    /// SignOut click event handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (currentUser == null)
        {
            currentUser = MembershipContext.AuthenticatedUser;
        }
        if (AuthenticationHelper.IsAuthenticated())
        {
            string redirectUrl = SignOutPath != "" ? GetUrl(SignOutPath) : RequestContext.CurrentURL;

            // If the user is Windows Live user
            if (!string.IsNullOrEmpty(currentUser.UserSettings.WindowsLiveID))
            {
                string siteName = SiteContext.CurrentSiteName;

                // Get LiveID settings
                string appId  = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");
                string secret = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                // Check valid Windows LiveID parameters
                if ((appId != string.Empty) && (secret != string.Empty))
                {
                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // Redirect to Windows Live
                    redirectUrl = wll.GetLogoutUrl();
                }
            }

            AuthenticationHelper.SignOut();

            Response.Cache.SetNoStore();
            URLHelper.Redirect(redirectUrl);
        }
    }
        private void PopulateMessenger()
        {
            if (WebConfigSettings.GloballyDisableMemberUseOfWindowsLiveMessenger)
            {
                return;
            }
            if (!siteSettings.AllowWindowsLiveMessengerForMembers)
            {
                return;
            }
            if (siteUser == null)
            {
                return;
            }
            if (!siteUser.EnableLiveMessengerOnProfile)
            {
                return;
            }
            if (siteUser.LiveMessengerId.Length == 0)
            {
                return;
            }

            divLiveMessenger.Visible = true;
            chat1.Invitee            = siteUser.LiveMessengerId;
            //chat1.InviteeDisplayName = siteUser.Name;

            if (WebConfigSettings.TestLiveMessengerDelegation)
            {
                WindowsLiveLogin     wl             = WindowsLiveHelper.GetWindowsLiveLogin();
                WindowsLiveMessenger m              = new WindowsLiveMessenger(wl);
                ConsentToken         token          = m.DecodeToken(siteUser.LiveMessengerDelegationToken);
                ConsentToken         refreshedToken = m.RefreshConsent(token);
                if (refreshedToken != null)
                {
                    chat1.DelegationToken = refreshedToken.DelegationToken;
                    string signedParams = WindowsLiveMessenger.SignParameters(
                        refreshedToken.SessionKey,
                        siteUser.Name,
                        string.Empty,
                        string.Empty);
                    chat1.SignedParams = signedParams;
                }
                else
                {
                    //chat1.DelegationToken = siteUser.LiveMessengerDelegationToken;
                    chat1.DelegationToken = token.DelegationToken;
                    string signedParams = WindowsLiveMessenger.SignParameters(
                        token.SessionKey,
                        siteUser.Name,
                        string.Empty,
                        string.Empty);

                    chat1.SignedParams = signedParams;
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Initializes the Live Authentication Service.
        /// </summary>
        public LiveService()
        {
            String AppId             = Storage.StorageManager.getEnvValue("liveAppId");
            String SecretKey         = Storage.StorageManager.getEnvValue("liveSecretKey");
            String securityAlgorithm = Storage.StorageManager.getEnvValue("liveSecurityAlgorithm");
            String policyUrl         = Storage.StorageManager.getEnvValue("livePolicyUrl");
            String returnUrl         = Storage.StorageManager.getEnvValue("liveReturnUrl");

            wll = new WindowsLiveLogin(AppId, SecretKey, securityAlgorithm, true, policyUrl, returnUrl);
        }
        private WindowsLiveLogin.User GetWindowsLiveLoginUser(string token)
        {
            var user = new WindowsLiveLogin(true).ProcessToken(token);

            if (user == null)
            {
                Tracing.FrameworkError(ToString(), "GetPuid", "The Live ID token was not valid or could not be parsed -- No user created");
                return(null);
            }

            return(user);
        }
        private void LoadSettings()
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            siteRoot     = SiteUtils.GetNavigationSiteRoot();

            winliveCookieName = "winliveid"
                                + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            returnUrlCookieName = "ret"
                                  + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);


            windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
        }
        private void LoadSettings()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, Resource.RegistrationConfirmation);
            winliveCookieName = "winliveid" + siteSettings.SiteId.ToInvariantString();

            windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
            if (windowsLive == null) { return; }

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);
            if (winLiveToken.Length > 0)
            {
                liveUser = windowsLive.ProcessToken(winLiveToken);
            }

            AddClassToBody("confirmregistration");
        }
        private void LoadSettings()
        {
            siteSettings      = CacheHelper.GetCurrentSiteSettings();
            siteRoot          = SiteUtils.GetNavigationSiteRoot();
            winliveCookieName = "winliveid"
                                + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            returnUrlCookieName = "ret"
                                  + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            litSignInAddendum.Text = Resource.WindowsLiveSignInAddendum;
            if (SiteUtils.SslIsAvailable())
            {
                protocol = "https://";
            }

            string wlAppId = siteSettings.WindowsLiveAppId;

            if (ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"] != null)
            {
                wlAppId = ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"].Trim();
                if (wlAppId.Length == 0)
                {
                    wlAppId = siteSettings.WindowsLiveAppId.Trim();
                }
            }

            if (wlAppId.Length > 0)
            {
                try
                {
                    windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
                    if (windowsLive == null)
                    {
                        this.Visible = false;
                        return;
                    }
                    windowsLiveAppId = windowsLive.AppId;
                }
                catch (ArgumentException)
                {
                    windowsLive = null;
                }
            }
        }
        private void LoadSettings()
        {
            Title             = SiteUtils.FormatPageTitle(siteSettings, Resource.RegistrationConfirmation);
            winliveCookieName = "winliveid" + siteSettings.SiteId.ToInvariantString();

            windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
            if (windowsLive == null)
            {
                return;
            }

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);

            if (winLiveToken.Length > 0)
            {
                liveUser = windowsLive.ProcessToken(winLiveToken);
            }

            AddClassToBody("confirmregistration");
        }
        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone   = SiteUtils.GetUserTimeZone();

            if (SiteUtils.SslIsAvailable())
            {
                protocol = "https://";
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                if ((propertyDefinition.RequiredForRegistration) || (propertyDefinition.ShowOnRegistration))
                {
                    requiredProfileProperties.Add(propertyDefinition);
                }
            }

            winliveCookieName = "winliveid" + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
            if (windowsLive == null)
            {
                return;
            }

            windowsLiveAppId = windowsLive.AppId;

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);

            if (winLiveToken.Length > 0)
            {
                liveUser = windowsLive.ProcessToken(winLiveToken);
            }


            AddClassToBody("registerwinlivepage");
        }
        private void AssertConfiguration()
        {
            var missingHandlerException = new ConfigurationErrorsException("The LiveIdLoginStatus control requires a '{0}' or '{1}' to be configured.".FormatWith(typeof(LiveIdMembershipProvider), typeof(LiveIdAccountTransferHandler)));

            if (LiveIdMembershipProvider.Current == null)
            {
                throw missingHandlerException;
            }

            if (!LiveIdWebAuthenticationHandlerExists())
            {
                throw missingHandlerException;
            }

            var windowsLive = new WindowsLiveLogin(true);

            if (string.IsNullOrEmpty(windowsLive.AppId))
            {
                throw new ConfigurationErrorsException("The LiveIdLoginStatus control requires the application ID that you obtained when you registered your site to be specified in the LiveIdMembershipProvider connection string.");
            }
        }
Beispiel #12
0
        static void GetAuthHeader()
        {
            //TODO: replace this with scraping and return the right response values for the 4 variables
            //i.e.: call method ContactsAuthentication.AuthenticateContactsSharing(username, password)
            string responseConsentToken = "eact%3Duw5Ym5wpNL9Jo51f9N38Div7B9HmBTkwDof75T22MRvbToDeXSEYvZzWRuRMjHkw%252B8kbWcbKJ4ZwWdGcKm%252FeCJYCPIKTHMSCzx4gZscI9w21NKV%252BqjKFkQ6t9b6%252FccObokDfN6XCU1MBFddNoenuIAyo2o44luRpkDcokM3TgfSdtj%252Bg0hZUR8V8IIIvLmelc1KTjcI%252F3GJ2pBQXkxur0O4YKGu8cFF0y8gNVuXJvpL%252BcFq5%252Fdq8wMzTT6SnGbZgHyPqJv6UQZsYpC9EM%252FQmSlcxinLZf%252BV%252BxB25qNHE2GD05SFiUYKwEf%252FSS5a9RMziv8jThJTReCeFaBLbJClvGIr7D3zHh051REFWl97FlvH2oGcNMze5K9R%252Fxb9pi0%252BFcUCA6hTveVuyih0zOZY5TFyhvltaU2aemq3BBFOa%252FHRbTMu5kGAoW%252FUJiNf4FODvuZCF%252BrH%252BMMEV5V5b3WEsTPlytEG9HhzAjWpMV6i784pqXQjB7gF6Iuy2T8JKujk2wN%252FuFIS6F4Z%252BGMUbRYBxgmuLZMALShiscC6gC4JQuW7fr2zcTqBEmChmJAi9D9T97AVBWL5cyzrjxpkqm8Dr7z8KYqGcoWQ8VVy1JMcxW3vMGMJZPZBQUz1AOYut2xqd7kt1sssDfI7Owv4M7uU55K16IImxPR4LAmapujGLtTjWwfSoKYZBl2%252B41%252BuzPcvyUw%252BQqDu2aOCe1YuZ%252FaJry3tcIk43R0V9LFQ9HFEto8g8R7PeUlx9469jFhNPGPqzFy7Qlc%252BYGwf4nRwbrizAx5HKx9QuIcl%252FByK227CX0u7e7UkUzMQ%252FfTc13TpfvFk%252FBo5aXeoxjAKwrnyFeeDUKHiEsHwjwu2EW7kGfTdAOodUACDsoQDnrrrs%252BOX80Q4BzfVhZYy3F8XDAmdczqqzaGimQLK9UETvr%252F03GzCZdJResKRJNAeaaZ6Ahdy9ebJ64qvSvFq8jBOV1%252FY1rq8clX%252F5GZxnXzqT8gN%252F%252B9%252F8ktllYZi4QLmxaT2ChY2qnE8Fxx7GomY0k%252B5sDWhdqD18Ddu9HSFSaAFq4DflnTWis6jCLJ6WpqaeBGwJyPEGm0IYlVbQ0k7X5WnKYjKrC3kl68%252BqU6lL0T1nRoa8mZNXdeXZ72W%252FLQp21IrOH6NZhnomPBID2myyJ09QtuUkXlSaWbT5A0oRcE9ywPY4EvplbggyLxpke9jL%252BtIUQtNXdGN%252B%252FwjQhREw8dfMRHoRl6VN%252BmGLONeVvoR6Lvi%252BXJZhBz36XwwfhXtGb7kKIud8E9as%252FMC6YZcUNBn%252F28Zj9YdcRmM2iAAs9DBvw5tTmgAfPYU%253D";
            string responseResponseCode = "RequestApproved";
            string responseAction       = "delauth";
            string responseAppctx       = "";

            NameValueCollection nvc = new NameValueCollection(4);
            WindowsLiveLogin    wll = new WindowsLiveLogin(appId, secretKey);

            nvc.Add("ConsentToken", responseConsentToken);
            nvc.Add("ResponseCode", responseResponseCode);
            nvc.Add("action", responseAction);
            nvc.Add("appctx", responseAppctx);

            WindowsLiveLogin.ConsentToken ct = wll.ProcessConsent(nvc);
            authHeader = String.Format("DelegatedToken dt=\"{0}\"", ct.DelegationToken);
            lid        = ct.LocationID;
        }
        private string GetUserName(string scheme, string stoken)
        {
            // if this is a liveID authenticated user. he must have a name associated with this token
            if (scheme.Equals(Constants.LiveId, StringComparison.CurrentCultureIgnoreCase))
            {
                WindowsLiveLogin      wll = new WindowsLiveLogin(Constants.LiveIdappId, Constants.LiveIdappsecret, Constants.LiveIdsecurityAlgorithm, true, Constants.LiveIdpolicyURL, Constants.LiveIdreturnURL);
                WindowsLiveLogin.User windowsliveiduser = wll.ProcessToken(stoken);
                string name = platform.GetLiveIdUserName(windowsliveiduser.Id);
                if (string.IsNullOrEmpty(name))
                {
                    return("unknown");
                }
                else
                {
                    return(name);
                }
            }


            return(scheme);
        }
        private string HandleAddUserGuiWebPage(string stoken, Dictionary <string, string> dict)
        {
            string html = "";

            try
            {
                WindowsLiveLogin      wll = new WindowsLiveLogin(Constants.LiveIdappId, Constants.LiveIdappsecret, Constants.LiveIdsecurityAlgorithm, true, Constants.LiveIdpolicyURL, Constants.LiveIdreturnURL);
                WindowsLiveLogin.User windowsliveiduser = wll.ProcessToken(stoken);

                if (windowsliveiduser == null)
                {
                    throw new Exception("unable to decrypt liveid token");
                }
                else if (DateTime.UtcNow.Subtract(windowsliveiduser.Timestamp).TotalMilliseconds <= Constants.PrivilegeLevelTokenExpiry[Constants.LiveId] * 1000)
                {
                    dict["liveIdUniqueUserToken"] = windowsliveiduser.Id;
                    string redirectTo = "../" + Constants.GuiServiceSuffixWeb + "/" + GuiWebAddLiveIdUserPage;

                    foreach (string param in dict.Keys)
                    {
                        redirectTo += param + "=" + dict[param] + ",";
                    }
                    redirectTo = redirectTo.TrimEnd(',');

                    html += "<html> " + redirectJS + "<script type='text/javascript'>redirect(\"" + redirectTo + "\");</script>";
                }
                else
                {
                    throw new Exception("Token provided is expired.");
                }
            }
            catch (Exception e)
            {
                logger.Log("Unable to add user. Exception : " + e);
                string redirectTo = "../" + Constants.GuiServiceSuffixWeb + "/" + GuiWebAddLiveIdUserPage + "?function=message,message= User add failed! " + e.Message;
                html += "<html> " + redirectJS + "<script type='text/javascript'>redirect(\"" + redirectTo + "\");</script>";
            }
            return(html);
        }
    /// <summary>
    /// Manages some actions, after user authorized and page postbacked
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Args</param>
    protected void btnHidden_Click(object sender, EventArgs e)
    {
        string arg = Request[Page.postEventArgumentID];

        switch (arg.ToLowerCSafe())
        {
        case "redirecttoadditionalpage":

            // Get additional page
            string additionalInfoPage = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSLiveIDRequiredUserDataPage");

            if (!String.IsNullOrEmpty(additionalInfoPage))
            {
                // Redirect to additional info page
                URLHelper.Redirect(UrlResolver.ResolveUrl(additionalInfoPage));
            }

            break;

        case "clearcookieandredirect":
            WindowsLiveLogin.ClearCookieAndRedirect(logonPage);
            break;

        default:
            string returnUrl = QueryHelper.GetString("returnUrl", null);

            if (URLHelper.IsLocalUrl(returnUrl))
            {
                URLHelper.Redirect(returnUrl);
            }
            else
            {
                URLHelper.Redirect(RequestContext.CurrentURL);
            }
            break;
        }
    }
Beispiel #16
0
    /// <summary>
    /// Manages some actions, after user authorized and page postbacked
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Args</param>
    protected void btnHidden_Click(object sender, EventArgs e)
    {
        string arg = Request["__EVENTARGUMENT"];

        switch (arg.ToLower())
        {
        case "redirecttoadditionalpage":

            // Get additional page
            string additionalInfoPage = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSLiveIDRequiredUserDataPage");

            if (!String.IsNullOrEmpty(additionalInfoPage))
            {
                // Redirect to additional info page
                URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
            }

            break;

        case "clearcookieandredirect":
            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
            break;
        }
    }
Beispiel #17
0
    /// <summary>
    /// Manages some actions, after user authorized and page postbacked
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Args</param>
    protected void btnHidden_Click(object sender, EventArgs e)
    {
        string arg = Request[Page.postEventArgumentID];

        switch (arg.ToLowerCSafe())
        {
        case "redirecttoadditionalpage":

            // Get additional page
            string additionalInfoPage = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSLiveIDRequiredUserDataPage");

            if (!String.IsNullOrEmpty(additionalInfoPage))
            {
                // Redirect to additional info page
                URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
            }

            break;

        case "clearcookieandredirect":
            WindowsLiveLogin.ClearCookieAndRedirect(LOGON_PAGE_SETTINGS_KEY);
            break;
        }
    }
        public static WindowsLiveLogin GetWindowsLiveLogin()
        {
            string       WindowsLiveSecurityAlgorithm = "wsignin1.0";
            bool         forceDelAuthNonProvisioned   = true;
            SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();

            if (siteSettings == null)
            {
                return(null);
            }

            string siteRoot = SiteUtils.GetNavigationSiteRoot();
            string privacyPolicyUrl;

            if (siteSettings.PrivacyPolicyUrl.StartsWith("http"))
            {
                privacyPolicyUrl = siteSettings.PrivacyPolicyUrl;
            }
            else
            {
                privacyPolicyUrl = siteRoot + siteSettings.PrivacyPolicyUrl;
            }

            string returnUrl = siteRoot + "/Secure/WindowsLiveAuthHandler.aspx";
            string appId     = siteSettings.WindowsLiveAppId;
            string appKey    = siteSettings.WindowsLiveKey;

            if (SiteUtils.SslIsAvailable())
            {
                if (returnUrl.StartsWith("http://"))
                {
                    returnUrl = returnUrl.Replace("http://", "https://");
                }
            }

            // I use this forthe demo site since I let people log in admin but don't want them to change the setting in siteSettigns
            if (ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"] != null)
            {
                appId = ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"];
                if (appId.Length == 0)
                {
                    appId = siteSettings.WindowsLiveAppId;
                }
            }

            if (ConfigurationManager.AppSettings["GlobalWindowsLiveAppKey"] != null)
            {
                appKey = ConfigurationManager.AppSettings["GlobalWindowsLiveAppKey"];
                if (appKey.Length == 0)
                {
                    appKey = siteSettings.WindowsLiveKey;
                }
            }


            if (
                (appId.Length > 0) &&
                (appKey.Length > 0)
                )
            {
                WindowsLiveLogin windowsLive = new WindowsLiveLogin(
                    appId,
                    appKey,
                    WindowsLiveSecurityAlgorithm,
                    forceDelAuthNonProvisioned,
                    privacyPolicyUrl,
                    returnUrl);

                windowsLive.AppName = siteSettings.SiteName;
                if (siteSettings.AppLogoForWindowsLive.Length > 0)
                {
                    windowsLive.AppLogoUrl = siteRoot + siteSettings.AppLogoForWindowsLive;
                }

                return(windowsLive);
            }



            return(null);
        }
Beispiel #19
0
        private void PopulateControls()
        {
            this.lnkChangePassword.NavigateUrl = SiteRoot + "/Secure/ChangePassword.aspx";
            this.lnkChangePassword.Text        = Resource.UserChangePasswordLabel;

            if (siteSettings.AllowUserSkins)
            {
                this.ddSkins.DataSource = SiteUtils.GetSkinList(this.siteSettings);
                this.ddSkins.DataBind();

                ListItem listItem;
                listItem = this.ddSkins.Items.FindByValue("printerfriendly");
                if (listItem != null)
                {
                    this.ddSkins.Items.Remove(listItem);
                }

                listItem = this.ddSkins.Items.FindByValue(".svn");
                if (listItem != null)
                {
                    this.ddSkins.Items.Remove(listItem);
                }

                listItem       = new ListItem();
                listItem.Value = "";
                listItem.Text  = Resource.PageLayoutDefaultSkinLabel;
                this.ddSkins.Items.Insert(0, listItem);

                if (siteUser != null)
                {
                    if (siteUser.Skin.Length > 0)
                    {
                        listItem = ddSkins.Items.FindByValue(siteUser.Skin);
                        if (listItem != null)
                        {
                            ddSkins.ClearSelection();
                            listItem.Selected = true;
                        }
                    }
                }
            }

            if (siteUser != null)
            {
                txtName.Text                 = siteUser.Name;
                lblLoginName.Text            = siteUser.LoginName;
                txtEmail.Text                = siteUser.Email;
                gravatar1.Email              = siteUser.Email;
                lblOpenID.Text               = siteUser.OpenIdUri;
                txtPasswordQuestion.Text     = siteUser.PasswordQuestion;
                txtPasswordAnswer.Text       = siteUser.PasswordAnswer;
                lblCreatedDate.Text          = siteUser.DateCreated.AddHours(timeOffset).ToString();
                lblTotalPosts.Text           = siteUser.TotalPosts.ToString();
                lnkUserPosts.UserId          = siteUser.UserId;
                lnkUserPosts.TotalPosts      = siteUser.TotalPosts;
                lnkPublicProfile.NavigateUrl = SiteRoot + "/ProfileView.aspx?userid=" + siteUser.UserId.ToString(CultureInfo.InvariantCulture);

                if (divLiveMessenger.Visible)
                {
                    WindowsLiveLogin     wl = WindowsLiveHelper.GetWindowsLiveLogin();
                    WindowsLiveMessenger m  = new WindowsLiveMessenger(wl);

                    if (WebConfigSettings.TestLiveMessengerDelegation)
                    {
                        lnkAllowLiveMessenger.NavigateUrl = m.ConsentOptInUrl;
                    }
                    else
                    {
                        lnkAllowLiveMessenger.NavigateUrl = m.NonDelegatedSignUpUrl;
                    }

                    if (siteUser.LiveMessengerId.Length > 0)
                    {
                        chkEnableLiveMessengerOnProfile.Checked = siteUser.EnableLiveMessengerOnProfile;
                        chkEnableLiveMessengerOnProfile.Enabled = true;
                    }
                    else
                    {
                        chkEnableLiveMessengerOnProfile.Checked = false;
                        chkEnableLiveMessengerOnProfile.Enabled = false;
                    }
                }


                if ((!allowGravatars) && (!disableAvatars))
                {
                    if (siteUser.AvatarUrl.Length > 0)
                    {
                        //if (!WebConfigSettings.OnlyAdminsCanEditCheesyAvatars)
                        //{
                        //    ddAvatars.SelectedValue = siteUser.AvatarUrl;
                        //}

                        imgAvatar.Src = avatarPath + siteUser.AvatarUrl;
                    }
                    else
                    {
                        imgAvatar.Src = Page.ResolveUrl("~/Data/SiteImages/1x1.gif");
                    }
                }
            }


            DoTabSelection();
        }
        private void LoadSettings()
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            siteRoot = SiteUtils.GetNavigationSiteRoot();
            winliveCookieName = "winliveid"
                + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            returnUrlCookieName = "ret"
                + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            litSignInAddendum.Text = Resource.WindowsLiveSignInAddendum;
            if (SiteUtils.SslIsAvailable()) protocol = "https://";

            string wlAppId = siteSettings.WindowsLiveAppId;
            if (ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"] != null)
            {
                wlAppId = ConfigurationManager.AppSettings["GlobalWindowsLiveAppId"].Trim();
                if (wlAppId.Length == 0) { wlAppId = siteSettings.WindowsLiveAppId.Trim(); }
            }

            if (wlAppId.Length > 0)
            {
                try
                {
                    windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
                    if (windowsLive == null)
                    {
                        this.Visible = false;
                        return;
                    }
                    windowsLiveAppId = windowsLive.AppId;
                }
                catch (ArgumentException )
                {
                    windowsLive = null;
                }
            }
        }
Beispiel #21
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                string siteName = SiteContext.CurrentSiteName;
                if (!string.IsNullOrEmpty(siteName))
                {
                    // Get LiveID settings
                    string appId  = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");
                    string secret = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                    if (!WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Add windows live ID script
                        ScriptHelper.RegisterClientScriptInclude(Page, typeof(string), "WLScript", LIVE_CONNECT_API_URL);

                        // Add login functions
                        String loginLiveIDClientScript = @"

                            function signUserIn() {
                                var scopesArr = ['wl.signin'];
                                WL.login({ scope: scopesArr });
                            }
                    
                            function refreshLiveID(param)
                            {
                                " + ControlsHelper.GetPostBackEventReference(btnHidden, "#").Replace("'#'", "param") + @" 
                            }                                       
                        ";

                        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ClientInitLiveIDScript", ScriptHelper.GetScript(loginLiveIDClientScript));
                    }

                    // Check valid Windows LiveID parameters
                    if ((appId == string.Empty) || (secret == string.Empty))
                    {
                        lblError.Visible = true;
                        lblError.Text    = GetString("liveid.incorrectsettings");
                        return;
                    }

                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // If user is already authenticated
                    if (AuthenticationHelper.IsAuthenticated())
                    {
                        // If signout should be visible and user has LiveID registered

                        if (ShowSignOut && !String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID))
                        {
                            // Get data from auth cookie
                            string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                            // Check if user has truly logged in by LiveID
                            if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                            {
                                // Redirect to Windows Live and back to "home" page
                                string defaultAliasPath = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSDefaultAliasPath");
                                string url    = DocumentURLProvider.GetUrl(defaultAliasPath);
                                string navUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url));

                                // If text is set use text/button link
                                if (!string.IsNullOrEmpty(SignOutText))
                                {
                                    // Button link
                                    if (ShowAsButton)
                                    {
                                        btnSignOut.CommandArgument = navUrl;
                                        btnSignOut.Text            = SignOutText;
                                        btnSignOut.Visible         = true;
                                    }
                                    // Text link
                                    else
                                    {
                                        btnSignOutLink.CommandArgument = navUrl;
                                        btnSignOutLink.Text            = SignOutText;
                                        btnSignOutLink.Visible         = true;
                                    }
                                }
                                // Image link
                                else
                                {
                                    btnSignOutImage.CommandArgument = navUrl;
                                    btnSignOutImage.ImageUrl        = ResolveUrl(SignOutImageURL);
                                    btnSignOutImage.Visible         = true;
                                    btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout");
                                }
                            }
                        }
                        else
                        {
                            Visible = false;
                        }
                    }
                    // Sign In
                    else
                    {
                        // Create return URL
                        string returnUrl = QueryHelper.GetText("returnurl", "");
                        returnUrl = (returnUrl == String.Empty) ? RequestContext.CurrentURL : returnUrl;

                        // Create parameters for LiveID request URL
                        String[] parameters = new String[3];
                        parameters[0] = returnUrl;
                        parameters[1] = TrackConversionName;
                        parameters[2] = ConversionValue.ToString();
                        SessionHelper.SetValue("LiveIDInformtion", parameters);

                        returnUrl = wll.GetLoginUrl();

                        // Get App ID
                        appId = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");

                        // Create full LiveID request URL
                        string navUrl = AUTHORIZATION_URL + "?client_id=" + appId + "&redirect=true&scope=wl.signin&response_type=code&redirect_uri=" + HttpUtility.UrlEncode(returnUrl);

                        // If text is set use text/button link
                        if (!string.IsNullOrEmpty(SignInText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                AssignButtonControl(navUrl, returnUrl, appId);
                                btnSignIn.Text = SignInText;
                            }
                            // Text link
                            else
                            {
                                AssignHyperlinkControl(navUrl, returnUrl, appId);
                                lnkSignIn.Text = SignInText;
                            }
                        }
                        // Image link
                        else
                        {
                            AssignHyperlinkControl(navUrl, returnUrl, appId);
                            lnkSignIn.ImageUrl = ResolveUrl(SignInImageURL);
                            lnkSignIn.Text     = GetString("webparts_membership_signoutbutton.signin");
                        }
                    }
                }
            }
            else
            {
                // Error label is displayed in Design mode when Windows Live ID is disabled
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmswindowsliveid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(UIContextHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text    = String.Format(GetString("mem.liveid.disabled"), parameter);
                    lblError.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
    /// <summary>
    /// SignOut handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            if (AuthenticationHelper.IsAuthenticated())
            {
                string redirectUrl = RedirectToUrl;

                // If the user has registered Windows Live ID
                if (!String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID))
                {
                    // Get data from auth cookie
                    string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                    // If user has logged in using Windows Live ID, then sign him out from Live too
                    if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                    {
                        string siteName = SiteContext.CurrentSiteName;

                        // Get LiveID settings
                        string appId = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationID");
                        string secret = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                        // Check valid Windows LiveID parameters
                        if ((appId != string.Empty) && (secret != string.Empty))
                        {
                            WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                            // Redirect to Windows Live
                            redirectUrl = wll.GetLogoutUrl();
                        }
                    }
                }

                PortalContext.ViewMode = ViewModeEnum.LiveSite;
                AuthenticationHelper.SignOut();

                Response.Cache.SetNoStore();
                URLHelper.Redirect(redirectUrl);
            }
            else
            {
                string returnUrl = null;
                string signInUrl = null;

                if (SignInUrl != "")
                {
                    signInUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(SignInUrl)));
                }
                else
                {
                    signInUrl = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                }

                if (ReturnPath != "")
                {
                    returnUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(ReturnPath)));
                }
                else
                {
                    returnUrl = RequestContext.CurrentURL;
                }

                if (signInUrl != "")
                {
                    // Prevent multiple returnUrl parameter
                    returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl");
                    URLHelper.Redirect(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", Server.UrlEncode(returnUrl)));
                }
            }
        }
    }
Beispiel #23
0
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyProvider.GetStringValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request["__EVENTARGUMENT"];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = UserInfoProvider.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false);

                        // Track registration into analytics
                        double val = ValidationHelper.GetDouble(CMSContext.CurrentResolver.ResolveMacros(conversionValue), 0);
                        UserInfoProvider.TrackUserRegistration(conversionName, val, siteName, ui);

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

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = UserInfoProvider.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
Beispiel #24
0
        private void DoLogout()
        {
            SiteSettings siteSettings      = CacheHelper.GetCurrentSiteSettings();
            string       winliveCookieName = "winliveid"
                                             + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            string roleCookieName = SiteUtils.GetRoleCookieName(siteSettings);

            HttpCookie roleCookie = new HttpCookie(roleCookieName, string.Empty);

            roleCookie.Expires = DateTime.Now.AddMinutes(1);
            roleCookie.Path    = "/";
            Response.Cookies.Add(roleCookie);

            HttpCookie displayNameCookie = new HttpCookie("DisplayName", string.Empty);

            displayNameCookie.Expires = DateTime.Now.AddMinutes(1);
            displayNameCookie.Path    = "/";
            Response.Cookies.Add(displayNameCookie);

            // apparently we need this here for folder sites using windows auth
            //https://www.mojoportal.com/Forums/EditPost.aspx?thread=13195&forumid=2&mid=34&pageid=5&pagenumber=1
            CookieHelper.ExpireCookie("siteguid" + siteSettings.SiteGuid);

            bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);

            if ((useFolderForSiteDetection) && (!WebConfigSettings.UseRelatedSiteMode))
            {
                string cookieName = "siteguid" + siteSettings.SiteGuid.ToString();

                HttpCookie siteCookie = new HttpCookie(cookieName, string.Empty);
                siteCookie.Expires = DateTime.Now.AddMinutes(1);
                siteCookie.Path    = "/";
                Response.Cookies.Add(siteCookie);

                CookieHelper.ExpireCookie("siteguid" + siteSettings.SiteGuid);
            }
            else
            {
                FormsAuthentication.SignOut();
            }

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);

            WindowsLiveLogin.User liveUser = null;
            if (winLiveToken.Length > 0)
            {
                WindowsLiveLogin windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();

                try
                {
                    liveUser = windowsLive.ProcessToken(winLiveToken);
                    if (liveUser != null)
                    {
                        Response.Redirect(windowsLive.GetLogoutUrl());
                        Response.End();
                    }
                }
                catch (InvalidOperationException)
                {
                }
            }

            try
            {
                if (Session != null)
                {
                    Session.Clear();
                    Session.Abandon();
                }
            }
            catch (HttpException) { }

            string redirectUrl = SiteUtils.GetNavigationSiteRoot() + "/Default.aspx";

            if (!siteSettings.UseSslOnAllPages)
            {
                if (redirectUrl.StartsWith("https:"))
                {
                    redirectUrl = redirectUrl.Replace("https:", "http:");
                }
            }

            WebUtils.SetupRedirect(this, redirectUrl);
        }
Beispiel #25
0
        private void PopulateControls()
        {
            this.lnkChangePassword.NavigateUrl = SiteRoot + "/Secure/ChangePassword.aspx";
            this.lnkChangePassword.Text        = Resource.UserChangePasswordLabel;
            ListItem listItem;

            if (allowUserSkin)
            {
                if (siteUser != null)
                {
                    SkinSetting.SetValue(siteUser.Skin);
                }
            }

            if ((siteSettings.AllowUserEditorPreference) && (siteUser != null) && (siteUser.EditorPreference.Length > 0))
            {
                listItem = ddEditorProviders.Items.FindByValue(siteUser.EditorPreference);
                if (listItem != null)
                {
                    ddEditorProviders.ClearSelection();
                    listItem.Selected = true;
                }
            }



            if (siteUser != null)
            {
#if !MONO
                ISettingControl setting = timeZoneSetting as ISettingControl;
                if (setting != null)
                {
                    setting.SetValue(siteUser.TimeZoneId);
                }
#endif

                txtName.Text      = SecurityHelper.RemoveMarkup(siteUser.Name);
                txtName.Enabled   = siteSettings.AllowUserFullNameChange;
                lblLoginName.Text = SecurityHelper.RemoveMarkup(siteUser.LoginName);
                txtEmail.Text     = siteUser.Email;
                //gravatar1.Email = siteUser.Email;
                lblOpenID.Text           = siteUser.OpenIdUri;
                txtPasswordQuestion.Text = siteUser.PasswordQuestion;
                txtPasswordAnswer.Text   = siteUser.PasswordAnswer;
                lblCreatedDate.Text      = siteUser.DateCreated.AddHours(timeOffset).ToString();
                lblTotalPosts.Text       = siteUser.TotalPosts.ToString();
                lnkUserPosts.UserId      = siteUser.UserId;
                lnkUserPosts.TotalPosts  = siteUser.TotalPosts;
                //lnkPublicProfile.NavigateUrl = SiteRoot + "/ProfileView.aspx?userid=" + siteUser.UserId.ToInvariantString();
                lnkPubProfile.NavigateUrl = SiteRoot + "/ProfileView.aspx?userid=" + siteUser.UserId.ToInvariantString();

                if (divLiveMessenger.Visible)
                {
                    WindowsLiveLogin     wl = WindowsLiveHelper.GetWindowsLiveLogin();
                    WindowsLiveMessenger m  = new WindowsLiveMessenger(wl);

                    if (WebConfigSettings.TestLiveMessengerDelegation)
                    {
                        lnkAllowLiveMessenger.NavigateUrl = m.ConsentOptInUrl;
                    }
                    else
                    {
                        lnkAllowLiveMessenger.NavigateUrl = m.NonDelegatedSignUpUrl;
                    }

                    if (siteUser.LiveMessengerId.Length > 0)
                    {
                        chkEnableLiveMessengerOnProfile.Checked = siteUser.EnableLiveMessengerOnProfile;
                        chkEnableLiveMessengerOnProfile.Enabled = true;
                    }
                    else
                    {
                        chkEnableLiveMessengerOnProfile.Checked = false;
                        chkEnableLiveMessengerOnProfile.Enabled = false;
                    }
                }


                //if ((!allowGravatars)&&(!disableAvatars))
                //{
                //    if (siteUser.AvatarUrl.Length > 0)
                //    {
                //        imgAvatar.Src = avatarPath + siteUser.AvatarUrl;
                //    }
                //    else
                //    {
                //        imgAvatar.Src = Page.ResolveUrl(WebConfigSettings.DefaultBlankAvatarPath);
                //    }
                //}

                userAvatar.UseGravatar      = allowGravatars;
                userAvatar.Email            = siteUser.Email;
                userAvatar.UserName         = siteUser.Name;
                userAvatar.UserId           = siteUser.UserId;
                userAvatar.AvatarFile       = siteUser.AvatarUrl;
                userAvatar.MaxAllowedRating = MaxAllowedGravatarRating;
                userAvatar.Disable          = disableAvatars;
                userAvatar.SiteId           = siteSettings.SiteId;
                userAvatar.UseLink          = false;
            }

            // this doesn't work
            //DoTabSelection();
        }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Get login parameters
        String[] parameters = SessionHelper.GetValue("LiveIDInformtion") as String[];
        ParseParameters(parameters);
        Session.Remove("LiveIDInformtion");

        // Process login via Live ID
        WindowsLiveLogin.User liveUser = wwl.ProcessLogin(code, relativeURL);

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                string additionalInfoPage = SettingsKeyProvider.GetStringValue(siteName + ".CMSLiveIDRequiredUserDataPage");

                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = UserInfoProvider.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        UserInfoProvider.SendRegistrationEmails(ui, null, null, false, false);

                        // Track registration into analytics
                        double val = ValidationHelper.GetDouble(CMSContext.CurrentResolver.ResolveMacros(conversionValue), 0);
                        UserInfoProvider.TrackUserRegistration(conversionName, val, siteName, ui);

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

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        ClearCookieAndRedirect();
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    // Redirect to additional info page
                    URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                }
            }
            else
            {
                UserInfo ui = UserInfoProvider.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
Beispiel #27
0
    /// <summary>
    /// SignOut click event handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (currentUser == null)
        {
            currentUser = CMSContext.CurrentUser;
        }
        if (CMSContext.CurrentUser.IsAuthenticated())
        {
            FormsAuthentication.SignOut();
            CMSContext.ClearShoppingCart();

            string redirectUrl = SignOutPath != "" ? GetUrl(SignOutPath) : URLHelper.CurrentURL;

            // If the user is Windows Live user
            if (!string.IsNullOrEmpty(currentUser.UserSettings.WindowsLiveID))
            {
                string siteName = CMSContext.CurrentSiteName;

                // Get LiveID settings
                string appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID");
                string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                // Check valid Windows LiveID parameters
                if ((appId != string.Empty) && (secret != string.Empty))
                {
                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // Redirect to Windows Live
                    redirectUrl = wll.GetLogoutUrl();
                }
            }

            CMSContext.CurrentUser = null;

            Response.Cache.SetNoStore();
            URLHelper.Redirect(redirectUrl);
        }
    }
    /// <summary>
    /// SignOut handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            if (CMSContext.CurrentUser.IsAuthenticated())
            {
                CMSContext.LogoutUser();
                string redirectUrl = RedirectToUrl;

                // If the user has registered Windows Live ID
                if (!String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.WindowsLiveID))
                {
                    // Get data from auth cookie
                    string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                    // If user has logged in using Windows Live ID, then sign him out from Live too
                    if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                    {
                        string siteName = CMSContext.CurrentSiteName;

                        // Get LiveID settings
                        string appId  = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID");
                        string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                        // Check valid Windows LiveID parameters
                        if ((appId != string.Empty) && (secret != string.Empty))
                        {
                            WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                            // Store info about logout request, for validation logout request
                            SessionHelper.SetValue("liveidlogout", DateTime.Now);

                            // Redirect to Windows Live
                            redirectUrl = wll.GetLogoutUrl();
                        }
                    }
                }

                CMSContext.ViewMode    = ViewModeEnum.LiveSite;
                CMSContext.CurrentUser = null;

                Response.Cache.SetNoStore();
                URLHelper.Redirect(redirectUrl);
            }
            else
            {
                string returnUrl = null;
                string signInUrl = null;

                if (SignInUrl != "")
                {
                    signInUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(SignInUrl)));
                }
                else
                {
                    signInUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                }

                if (ReturnPath != "")
                {
                    returnUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(ReturnPath)));
                }
                else
                {
                    returnUrl = URLHelper.CurrentURL;
                }

                if (signInUrl != "")
                {
                    // Prevent multiple returnUrl parameter
                    returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl");
                    URLHelper.Redirect(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", returnUrl));
                }
            }
        }
    }
    /// <summary>
    /// SignOut click event handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (currentUser == null)
        {
            currentUser = MembershipContext.AuthenticatedUser;
        }
        if (AuthenticationHelper.IsAuthenticated())
        {

            string redirectUrl = SignOutPath != "" ? GetUrl(SignOutPath) : RequestContext.CurrentURL;

            // If the user is Windows Live user
            if (!string.IsNullOrEmpty(currentUser.UserSettings.WindowsLiveID))
            {
                string siteName = SiteContext.CurrentSiteName;

                // Get LiveID settings
                string appId = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID");
                string secret = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationSecret");

                // Check valid Windows LiveID parameters
                if ((appId != string.Empty) && (secret != string.Empty))
                {
                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // Redirect to Windows Live and back to "home" page
                    string defaultAliasPath = SettingsKeyInfoProvider.GetValue(siteName + ".CMSDefaultAliasPath");
                    string url = DocumentURLProvider.GetUrl(defaultAliasPath);
                    redirectUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url));
                }
            }

            AuthenticationHelper.SignOut();

            Response.Cache.SetNoStore();
            URLHelper.Redirect(redirectUrl);
        }
    }
Beispiel #30
0
 //added by Joe Audette
 public WindowsLiveMessenger(WindowsLiveLogin liveLogin)
 {
     this.windowsLiveLogin = liveLogin;
 }
Beispiel #31
0
 public WindowsLiveMessenger()
 {
     this.windowsLiveLogin = new WindowsLiveLogin(true);
 }
        private void DoLogout()
        {
            SiteSettings siteSettings      = CacheHelper.GetCurrentSiteSettings();
            string       winliveCookieName = "winliveid"
                                             + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            string roleCookieName = SiteUtils.GetRoleCookieName(siteSettings);

            HttpCookie roleCookie = new HttpCookie(roleCookieName, string.Empty);

            roleCookie.Expires = DateTime.Now.AddMinutes(1);
            roleCookie.Path    = "/";
            Response.Cookies.Add(roleCookie);

            HttpCookie displayNameCookie = new HttpCookie("DisplayName", string.Empty);

            displayNameCookie.Expires = DateTime.Now.AddMinutes(1);
            displayNameCookie.Path    = "/";
            Response.Cookies.Add(displayNameCookie);


            bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);

            if ((useFolderForSiteDetection) && (!WebConfigSettings.UseRelatedSiteMode))
            {
                string cookieName = "siteguid" + siteSettings.SiteGuid.ToString();

                HttpCookie siteCookie = new HttpCookie(cookieName, string.Empty);
                siteCookie.Expires = DateTime.Now.AddMinutes(1);
                siteCookie.Path    = "/";
                Response.Cookies.Add(siteCookie);
            }
            else
            {
                FormsAuthentication.SignOut();
            }

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);

            WindowsLiveLogin.User liveUser = null;
            if (winLiveToken.Length > 0)
            {
                WindowsLiveLogin windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();

                try
                {
                    liveUser = windowsLive.ProcessToken(winLiveToken);
                    if (liveUser != null)
                    {
                        Response.Redirect(windowsLive.GetLogoutUrl());
                        Response.End();
                    }
                }
                catch (InvalidOperationException)
                {
                }
            }

            try
            {
                if (Session != null)
                {
                    Session.Abandon();
                }
            }
            catch (HttpException) { }

            WebUtils.SetupRedirect(this, SiteUtils.GetNavigationSiteRoot() + "/Default.aspx");
        }
Beispiel #33
0
    /// <summary>
    /// SignOut handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            if (AuthenticationHelper.IsAuthenticated())
            {
                string redirectUrl = RedirectToUrl;

                // If the user has registered Windows Live ID
                if (!String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID))
                {
                    // Get data from auth cookie
                    string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie();

                    // If user has logged in using Windows Live ID, then sign him out from Live too
                    if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                    {
                        string siteName = SiteContext.CurrentSiteName;

                        // Get LiveID settings
                        string appId  = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID");
                        string secret = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationSecret");

                        // Check valid Windows LiveID parameters
                        if ((appId != string.Empty) && (secret != string.Empty))
                        {
                            WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                            // Redirect to Windows Live and back to "home" page
                            string defaultAliasPath = SettingsKeyInfoProvider.GetValue(siteName + ".CMSDefaultAliasPath");
                            string url = DocumentURLProvider.GetUrl(defaultAliasPath);
                            redirectUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url));
                        }
                    }
                }

                PortalContext.ViewMode = ViewModeEnum.LiveSite;
                AuthenticationHelper.SignOut();

                Response.Cache.SetNoStore();
                URLHelper.Redirect(UrlResolver.ResolveUrl(redirectUrl));
            }
            else
            {
                string returnUrl = null;
                string signInUrl = null;

                if (SignInUrl != "")
                {
                    signInUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(SignInUrl)));
                }
                else
                {
                    signInUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName);
                }

                if (ReturnPath != "")
                {
                    returnUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(ReturnPath)));
                }
                else
                {
                    returnUrl = RequestContext.CurrentURL;
                }

                if (signInUrl != "")
                {
                    // Prevent multiple returnUrl parameter
                    returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl");
                    URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", Server.UrlEncode(returnUrl))));
                }
            }
        }
    }
    /// <summary>
    /// SignOut handler.
    /// </summary>
    protected void btnSignOut_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            if (CMSContext.CurrentUser.IsAuthenticated())
            {
                FormsAuthentication.SignOut();
                CMSContext.ClearShoppingCart();

                string redirectUrl = RedirectToUrl;

                // If the user has registered Windows Live ID
                if (!String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.WindowsLiveID))
                {
                    // Get data from auth cookie
                    string[] userData = UserInfoProvider.GetUserDataFromAuthCookie();

                    // If user has logged in using Windows Live ID, then sign him out from Live too
                    if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                    {
                        string siteName = CMSContext.CurrentSiteName;

                        // Get LiveID settings
                        string appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID");
                        string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                        // Check valid Windows LiveID parameters
                        if ((appId != string.Empty) && (secret != string.Empty))
                        {
                            WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                            // Store info about logout request, for validation logout request
                            SessionHelper.SetValue("liveidlogout", DateTime.Now);

                            // Redirect to Windows Live
                            redirectUrl = wll.GetLogoutUrl();
                        }
                    }
                }

                CMSContext.ViewMode = ViewModeEnum.LiveSite;
                CMSContext.CurrentUser = null;

                Response.Cache.SetNoStore();
                URLHelper.Redirect(redirectUrl);
            }
            else
            {
                string returnUrl = null;
                string signInUrl = null;

                if (SignInUrl != "")
                {
                    signInUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(SignInUrl)));
                }
                else
                {
                    signInUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage");
                }

                if (ReturnPath != "")
                {
                    returnUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(ReturnPath)));
                }
                else
                {
                    returnUrl = URLHelper.CurrentURL;
                }

                if (signInUrl != "")
                {
                    URLHelper.Redirect(URLHelper.AddParameterToUrl(signInUrl, "returnurl", returnUrl));
                }
            }
        }
    }
Beispiel #35
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                string siteName = CMSContext.CurrentSiteName;
                if (!string.IsNullOrEmpty(siteName))
                {
                    // Get LiveID settings
                    string appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID");
                    string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret");

                    if (!WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Add windows live ID script
                        ScriptHelper.RegisterClientScriptInclude(Page, typeof(string), "WLScript", "https://js.live.net/v5.0/wl.js");

                        // Add login functions
                        String loginLiveIDClientScript = @"

                            function signUserIn() {
                                var scopesArr = ['wl.signin'];
                                WL.login({ scope: scopesArr });
                            }

                            function refreshLiveID(param)
                            {
                                " + ControlsHelper.GetPostBackEventReference(btnHidden, "#").Replace("'#'", "param") + @"
                            }
                        ";

                        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ClientInitLiveIDScript", ScriptHelper.GetScript(loginLiveIDClientScript));
                    }

                    // Check valid Windows LiveID parameters
                    if ((appId == string.Empty) || (secret == string.Empty))
                    {
                        lblError.Visible = true;
                        lblError.Text = GetString("liveid.incorrectsettings");
                        return;
                    }

                    WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret);

                    // If user is already authenticated
                    if (CMSContext.CurrentUser.IsAuthenticated())
                    {
                        // If signout should be visible and user has LiveID registered
                        if ((ShowSignOut) && (!String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.WindowsLiveID)))
                        {
                            // Get data from auth cookie
                            string[] userData = UserInfoProvider.GetUserDataFromAuthCookie();

                            // Check if user has truly logged in by LiveID
                            if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0))
                            {
                                string navUrl = wll.GetLogoutUrl();

                                // If text is set use text/button link
                                if (!string.IsNullOrEmpty(SignOutText))
                                {
                                    // Button link
                                    if (ShowAsButton)
                                    {
                                        btnSignOut.CommandArgument = navUrl;
                                        btnSignOut.Text = SignOutText;
                                        btnSignOut.Visible = true;
                                    }
                                    // Text link
                                    else
                                    {
                                        btnSignOutLink.CommandArgument = navUrl;
                                        btnSignOutLink.Text = SignOutText;
                                        btnSignOutLink.Visible = true;
                                    }
                                }
                                // Image link
                                else
                                {
                                    btnSignOutImage.CommandArgument = navUrl;
                                    btnSignOutImage.ImageUrl = ResolveUrl(SignOutImageURL);
                                    btnSignOutImage.Visible = true;
                                    btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout");
                                }
                            }
                        }
                        else
                        {
                            Visible = false;
                        }
                    }
                    // Sign In
                    else
                    {

                        // Create return URL
                        string returnUrl = QueryHelper.GetText("returnurl", "");
                        returnUrl = (returnUrl == String.Empty) ? URLHelper.CurrentURL : returnUrl;

                        // Create parameters for LiveID request URL
                        String[] parameters = new String[3];
                        parameters[0] = returnUrl;
                        parameters[1] = TrackConversionName;
                        parameters[2] = ConversionValue.ToString();
                        SessionHelper.SetValue("LiveIDInformtion", parameters);

                        returnUrl = wll.GetLoginUrl();

                        // Get App ID
                        appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID");

                        // Create full LiveID request URL
                        string navUrl = "https://oauth.live.com/authorize?&client_id=" + appId + "&redirect=true&scope=wl.signin&response_type=code&redirect_uri=" + HttpUtility.UrlEncode(returnUrl);

                        // If text is set use text/button link
                        if (!string.IsNullOrEmpty(SignInText))
                        {
                            // Button link
                            if (ShowAsButton)
                            {
                                AssignButtonControl(navUrl, returnUrl, appId);
                                btnSignIn.Text = SignInText;
                            }
                            // Text link
                            else
                            {
                                AssignHyperlinkControl(navUrl, returnUrl, appId);
                                lnkSignIn.Text = SignInText;
                            }
                        }
                        // Image link
                        else
                        {
                            AssignHyperlinkControl(navUrl, returnUrl, appId);
                            lnkSignIn.ImageUrl = ResolveUrl(SignInImageURL);
                            lnkSignIn.Text = GetString("webparts_membership_signoutbutton.signin");
                        }
                    }
                }
            }
            else
            {
                // Error label is displayed in Design mode when Windows Live ID is disabled
                if (CMSContext.ViewMode == ViewModeEnum.Design)
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(GetString("header.sitemanager") + " -> ");
                    parameter.Append(GetString("settingscategory.cmssettings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmswindowsliveid"));
                    if (CMSContext.CurrentUser.UserSiteManagerAdmin)
                    {
                        // Make it link for SiteManager Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl("~/CMSSiteManager/default.aspx?section=settings") + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text = String.Format(GetString("mem.liveid.disabled"), parameter.ToString());
                    lblError.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-/]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization successful
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfully created
                    if ((ui != null) && (ui.Enabled))
                    {
                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(UrlResolver.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();

            if (SiteUtils.SslIsAvailable()) protocol = "https://";

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                if ((propertyDefinition.RequiredForRegistration)||(propertyDefinition.ShowOnRegistration))
                {
                    requiredProfileProperties.Add(propertyDefinition);
                }
            }

            winliveCookieName = "winliveid" + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            windowsLive = WindowsLiveHelper.GetWindowsLiveLogin();
            if (windowsLive == null) { return; }

            windowsLiveAppId = windowsLive.AppId;

            string winLiveToken = CookieHelper.GetCookieValue(winliveCookieName);
            if (winLiveToken.Length > 0)
            {
                liveUser = windowsLive.ProcessToken(winLiveToken);
            }

            AddClassToBody("registerwinlivepage");
        }