Пример #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);
        }
Пример #2
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                plcPasswordNew.Visible  = this.AllowFormsAuthentication;
                pnlExistingUser.Visible = this.AllowExistingUser;

                liveUser = SessionHelper.GetValue("windowsliveloginuser") as WindowsLiveLogin.User;

                // There is no windows live user object stored in session - hide all
                if ((liveUser == null) && HideForNoLiveID)
                {
                    this.Visible = false;
                }

                // WAI validation
                lblPasswordNew.AssociatedControlClientID = passStrength.InputClientID;
            }
            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());
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                else
                {
                    this.Visible = false;
                }
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                plcPasswordNew.Visible  = AllowFormsAuthentication;
                pnlExistingUser.Visible = AllowExistingUser;

                liveUser = SessionHelper.GetValue("windowsliveloginuser") as WindowsLiveLogin.User;

                // There is no windows live user object stored in session - hide all
                if ((liveUser == null) && HideForNoLiveID)
                {
                    Visible = false;
                }

                // WAI validation
                lblPasswordNew.AssociatedControlClientID = passStrength.InputClientID;
            }
            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(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text      = String.Format(GetString("mem.liveid.disabled"), parameter.ToString());
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
        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()
        {
            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 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);
        }
        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 DoValidation()
        {
            string action = Request.QueryString.Get("action");

            if (WebConfigSettings.DebugWindowsLive)
            {
                log.Info("action was " + action);
            }

            /*
             * If action is 'logout', clear the login cookie and redirect
             * to the logout page.
             *
             * If action is 'clearcookie', clear the login cookie and
             * return a GIF as response to signify success.
             *
             * By default, try to process a login. If login was
             * successful, cache the user token in a cookie and redirect
             * If login failed, clear the cookie and redirect
             */

            if (action == "logout")
            {
                CookieHelper.ExpireCookie(winliveCookieName);
                WebUtils.SetupRedirect(this, siteRoot + "/Logoff.aspx");

                return;
            }
            else if (action == "delauth")
            {
                HandleConsent();
                return;
            }
            else if (action == "clearcookie")
            {
                CookieHelper.ExpireCookie(winliveCookieName);

                string type;
                byte[] content;
                windowsLive.GetClearCookieResponse(out type, out content);
                Response.ContentType = type;
                Response.OutputStream.Write(content, 0, content.Length);
                Response.End();
            }
            else
            {
                // action is login
                user = windowsLive.ProcessLogin(Request.Form);
                Guid userGuid = Guid.Empty;
                if (user != null)
                {
                    // auth succeeded see if its a current mojo user or not
                    // emtpy guid means new user
                    userGuid = SiteUser.GetUserGuidFromWindowsLiveId(
                        siteSettings.SiteId,
                        user.Id);
                    persistCookie = user.UsePersistentCookie;

                    CookieHelper.SetCookie(winliveCookieName,
                                           user.Token,
                                           user.UsePersistentCookie);
                }
                else
                {
                    // auth failed so clear the cookie
                    CookieHelper.ExpireCookie(winliveCookieName);
                }

                if (user != null)
                {
                    if (userGuid == Guid.Empty)
                    {
                        // WindowsLiveID Authentication succeeded
                        // no mojo user found so send to Register
                        //WebUtils.SetupRedirect(this, "RegisterWithWindowsLiveID.aspx");

                        if (siteSettings.AllowNewRegistration)
                        {
                            WebUtils.SetupRedirect(this, siteRoot + "/Secure/RegisterWithWindowsLiveID.aspx");
                            return;
                        }


                        WebUtils.SetupRedirect(this, siteRoot);

                        return;
                    }
                    else
                    {
                        // TODO: use return url cookie if normal login
                        //WebUtils.SetupRedirect(
                        //    this,
                        //    SiteUtils.GetNavigationSiteRoot());
                        DoExistingUserLogic(userGuid);

                        return;
                    }
                }
                else
                {
                    // WindowsLiveID Authentication failed
                    //WebUtils.SetupRedirect(
                    //    this,
                    //    LoginPage);
                    Response.Redirect(LoginPage);

                    return;
                }
            }
        }
        /// <summary>
        /// Set the Live ID cookie and redirect to the login destination or the registration destination.
        /// </summary>
        private static void ProcessLogin(HttpContext context)
        {
            WindowsLiveLogin.User user = WindowsLiveLogin.ProcessLogin(context.Request.Form);

            if (user == null)
            {
                SignOutAndRedirectToSignedOutUrl(context);
                return;
            }

            if (LiveIdMembershipProvider.Current.ValidateUser(user.Id, user.Id))
            {
                Tracing.FrameworkInformation(ClassName, "ProcessLogin", "User is registered -- redirecting to login destination");

                FormsAuthentication.SetAuthCookie(user.Id, user.UsePersistentCookie);

                context.Response.Redirect(SafeUrl(user.Context.LoginDestinationPath));
            }
            else
            {
                if (string.IsNullOrEmpty(user.Context.RegistrationDestinationPath) && !WindowsLiveLogin.AutoRegister)
                {
                    Tracing.FrameworkInformation(ClassName, "ProcessLogin", "User not registered -- registration destination not provided -- automatic registration not permitted -- signing out");

                    SignOutAndRedirectToSignedOutUrl(context);

                    return;
                }

                if (string.IsNullOrEmpty(user.Context.RegistrationDestinationPath) && WindowsLiveLogin.AutoRegister)
                {
                    Tracing.FrameworkInformation(ClassName, "ProcessLogin", "User not registered -- registration destination not provided -- automatically registering and redirecting");

                    MembershipCreateStatus status;

                    var membershipUser = LiveIdMembershipProvider.Current.CreateUser(user.Id, user.Id, null, null, null, true, null, out status);

                    if (membershipUser == null)
                    {
                        throw new MembershipCreateUserException(status);
                    }

                    FormsAuthentication.SetAuthCookie(user.Id, user.UsePersistentCookie);

                    context.Response.Redirect(SafeUrl(user.Context.LoginDestinationPath));
                }
                else
                {
                    Tracing.FrameworkInformation(ClassName, "ProcessLogin", "User not registered -- posting to registration destination");

                    var autoPostFormToRegistrationDestinationHtml = @"
						<html>
						<head>
							<title></title>
							<script type=""text/javascript"">
								function OnBack() {{ }}
								function DoSubmit() {{
									var submitted = false;
									if (!submitted) {{ submitted = true; document.fmHF.submit(); }}
								}}
							</script>
						</head>
						<body onload=""javascript:DoSubmit();"">
						<form name=""fmHF"" id=""fmHF"" action=""{0}"" method=""post"" target=""_top"">
							<input type=""hidden"" name=""live-id-token"" id=""live-id-token"" value=""{1}"">
							<input type=""hidden"" name=""live-id-context"" id=""live-id-context"" value=""{2}"">
							<input type=""hidden"" name=""live-id-action"" id=""live-id-action"" value=""register"">
						</form>
						</body>
						</html>"                        .FormatWith(
                        BuildSafeUrlForRegistrationDestinationWithLoginUrlOnQueryString(user.Context.RegistrationDestinationPath, user.Context.LoginDestinationPath),
                        Encoder.XmlAttributeEncode(context.Request["stoken"]),
                        Encoder.XmlAttributeEncode(context.Request["appctx"]));

                    context.Response.Write(autoPostFormToRegistrationDestinationHtml);
                }
            }
        }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                plcPasswordNew.Visible = AllowFormsAuthentication;
                pnlExistingUser.Visible = AllowExistingUser;

                liveUser = SessionHelper.GetValue("windowsliveloginuser") as WindowsLiveLogin.User;

                // There is no windows live user object stored in session - hide all
                if ((liveUser == null) && HideForNoLiveID)
                {
                    Visible = false;
                }

                // WAI validation
                lblPasswordNew.AssociatedControlClientID = passStrength.InputClientID;
            }
            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());
                    plcError.Visible = true;
                    plcContent.Visible = false;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableWindowsLiveID"))
            {
                plcPasswordNew.Visible = AllowFormsAuthentication;
                pnlExistingUser.Visible = AllowExistingUser;

                liveUser = SessionHelper.GetValue("windowsliveloginuser") as WindowsLiveLogin.User;

                // There is no windows live user object stored in session - hide all
                if ((liveUser == null) && HideForNoLiveID)
                {
                    Visible = false;
                }

                // WAI validation
                lblPasswordNew.AssociatedControlClientID = passStrength.InputClientID;
            }
            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.ToString());
                    plcError.Visible = true;
                    plcContent.Visible = false;
                }
                else
                {
                    Visible = false;
                }
            }
        }
    }
Пример #14
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);
                }
            }
        }
    }
Пример #15
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);
        }
    /// <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);
                }
            }
        }
    }
Пример #17
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);


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