Beispiel #1
0
 public string loadfooter(string url)
 {
     try
     {
         var uri    = new Uri(url);
         var doc    = new HtmlWeb().Load(url);
         var footer = doc.DocumentNode.SelectNodes("//footer");
         if (footer != null)
         {
             var    sbNavigation = new StringBuilder(footer[0].InnerHtml);
             string remoteBase   = string.Format("https://{0}", uri.Host);
             sbNavigation.Replace("href=\"/", String.Format("href=\"{0}/", remoteBase));
             sbNavigation.Replace("src=\"/", String.Format("src=\"{0}/", remoteBase));
             sbNavigation.Replace("resultsurl=\"/", String.Format("resultsurl=\"{0}/", remoteBase));
             return(sbNavigation.ToString());
         }
         else
         {
             LoginUsertokentico.WriteError("Doesnt Load for this-----loadfooter>>>>", "For skinng the Navigation for  : " + url);
             return("");
         }
     }
     catch (Exception ex)
     {
         LoginUsertokentico.WriteError(ex.ToString(), "For skinng the Navigation for loadfooter----> : " + url);
         return(null);
     }
 }
Beispiel #2
0
 public string loadTopNavigation(string url)
 {
     try
     {
         string ret        = "";
         var    uri        = new Uri(url);
         var    doc        = new HtmlWeb().Load(url);
         var    navigation = doc.DocumentNode.SelectNodes("//ul[@class='uti-nav']");
         if (navigation != null)
         {
             var    sbNavigation = new StringBuilder(navigation[0].InnerHtml);
             string remoteBase   = string.Format("https://{0}", uri.Host);
             sbNavigation.Replace("href=\"/", String.Format("href=\"{0}/", remoteBase));
             sbNavigation.Replace("src=\"/", String.Format("src=\"{0}/", remoteBase));
             sbNavigation.Replace("resultsurl=\"/", String.Format("resultsurl=\"{0}/", remoteBase));
             if (url.Contains("uca"))
             {
                 ret = sbNavigation.ToString();
                 ret = ret.Replace("<li><a href='/uca/login'>Login </a></li>", "");
             }
             else
             {
                 ret = sbNavigation.ToString();
                 ret = ret.Replace("<li><a href='/personifyebusiness/login-join'>Login </a></li>", "");
             }
             return(ret);
         }
         else
         {
             LoginUsertokentico.WriteError("Doesnt Load for this-----loadTopNavigation>>>>", "For skinng the Navigation for  : " + url);
             return("");
         }
     }
     catch (Exception ex)
     {
         LoginUsertokentico.WriteError(ex.ToString(), "For skinng the Navigation for loadNavigation : " + url);
         return(null);
     }
 }
    /// <summary>
    /// Verify User in Kentico
    /// </summary>
    /// <param name="customerToken">Decrypted Customer Token</param>
    /// <param name="userName">Username of Customer</param>
    private void VerifyKenticoUser(string customerToken, string userName)
    {
        // Get CustomerID
        var res = ssoClient.TIMSSCustomerIdentifierGet(_personifySsoVendorName, _personifySsoVendorPassword, customerToken);

        if (res != null && !String.IsNullOrEmpty(res.CustomerIdentifier))
        {
            var    aIdentifiers      = res.CustomerIdentifier.Split('|');
            string sMasterCustomerId = aIdentifiers[0];
            int    subCustomerId     = int.Parse(aIdentifiers[1]);

            Uri ServiceUri = new Uri(svcUri_Base);

            LoginUsertokentico.WriteError("AuthenticateCustomer ID ==>", sMasterCustomerId.ToString());

            // Get User details from Personify
            PersonifyEntitiesBase DataAccessLayer = new PersonifyEntitiesBase(ServiceUri);
            DataAccessLayer.Credentials = new NetworkCredential(svcLogin, svcPassword);

            var userdetails =
                DataAccessLayer.CusNameDemographics.Where(p => p.MasterCustomerId == sMasterCustomerId)
                .Select(o => o)
                .ToList()
                .FirstOrDefault();

            string pfirstname = null;
            string plastname  = null;

            if (userdetails == null)
            {
                pfirstname = @"&nbsp;";
                plastname  = @"&nbsp;";
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.FirstName))
            {
                pfirstname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    pfirstname = userdetails.FirstName;
                }
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.LastName))
            {
                plastname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    plastname = userdetails.LastName;
                }
            }
            //*******End Custom Dataservice code to get Firstname, Lastname***********//

            string[] memberGroups = GetImsroles(customerToken);

            string groupslist = String.Empty;

            if (memberGroups.Length > 0)
            {
                foreach (string s in memberGroups)
                {
                    if (s.Length > 0)
                    {
                        groupslist += s + ",";
                    }
                }
            }

            groupslist += "peronifyUser" + ",";



            string login = new LoginUsertokentico().CreateUpdateLoginUserinKentico(
                userName,
                pfirstname,
                plastname,
                userName,
                groupslist,
                true,
                false, res.CustomerIdentifier, customerToken);
            userinfo uInfo = new userinfo
            {
                ID         = sMasterCustomerId,
                Token      = Session[PersonifySessionKey].ToString(),
                email      = userName,
                firstname  = pfirstname,
                lastname   = plastname,
                username   = userName,
                groupNames = groupslist
            };

            // Add info to Session variable
            Session["userClass"] = uInfo;
        }
        else
        {
            EventLogProvider.LogException("SSOHandler", "Verify", new Exception("Unable to retrieve personify ID. Customer Token: " + Request.QueryString["ct"].ToString() + " <br />Decrypted Token: " + customerToken + "  <br />Username: " + userName));
            // should not get here
            URLHelper.Redirect(_loginErrorUrl);
        }
    }
    private void LoginMember(string Username, string Password, bool RememberMember)
    {
        try
        {
            var    vendorPassword = ConfigurationManager.AppSettings["PersonifySSO_Password"].ToString();
            var    vendorBlock    = ConfigurationManager.AppSettings["PersonifySSO_Block"].ToString();
            var    vendorId       = ConfigurationManager.AppSettings["PersonifySSO_VendorID"];
            string returnURl      = Request.Url.AbsoluteUri;
            string fullUrl        = Request.RawUrl;
            if (Request.QueryString["ReturnUrl"] != null)
            {
                //  string url = Request.Url.ToString();
                //  Uri originalUrl = new Uri(url); // Request.Url
                //  string domainUrl = String.Concat(originalUrl.Scheme, Uri.SchemeDelimiter, originalUrl.Host); // http://www.mydomain.com
                ////  UrlParameterHelper.ConstructURLWithExistingQueryString(Step2Url, Request.QueryString, QueryStringParametersToPreserve);
                //  returnURl = domainUrl + "/CMSPages/PortalTemplate.aspx?aliaspath=" + Request.QueryString["ReturnUrl"].ToString();
                string Rurl = fullUrl.Replace("?site=sme&", "?");
                Rurl = Rurl.ToLower().Replace("/memberredirect/default.aspx?returnurl=", "");
                Rurl = Rurl.Replace("&site=sme", "");
                if (Request.QueryString["ReturnUrl"].ToString().ToLower().Contains("personifyebusiness"))
                {
                    if ((Request.QueryString["ReturnUrl"].ToString().ToLower().Contains("http://")))///check if user is redirected from Personify Pages
                    {
                        string urlRed = Server.UrlDecode(Request.QueryString["ReturnUrl"].ToString().ToLower());
                        string login  = "******";
                        urlRed.Replace("http://smemi.personifycloud.com/", "");

                        Session["redirectUrl"] = login + (urlRed);
                        // Session["redirectUrl"] =   Request.QueryString["ReturnUrl"].ToString();//Server.UrlEncode(Rurl) ;//Request.QueryString["ReturnUrl"].ToString();
                    }
                    else
                    {
                        Session["redirectUrl"] = Server.UrlEncode(Rurl);//Request.QueryString["ReturnUrl"].ToString();
                    }
                }
                else
                {
                    Session["redirectUrl"] = Request.QueryString["ReturnUrl"].ToString();//Server.UrlDecode(Rurl);
                }
            }

            else if (Request.QueryString["rurl"] != null)
            {
                string Rurl = fullUrl.Replace("?site=sme&", "?");
                Rurl = Rurl.Replace("/memberredirect/default.aspx?rurl=", "");
                Rurl = Rurl.Replace("&site=sme", "");
                string login = "******";
                Session["redirectUrl"] = login + (Session["rurlValues"]);
                //Response.Write(Request.QueryString["rurl"] +" <br/>") ;
            }
            else if (Request.QueryString["loginurl"] != null)
            {
                Session["redirectUrl"] = Request.QueryString["loginurl"];
            }
            else
            {
                Session["redirectUrl"] = null;
            }
            var encryptedVendorToken = RijndaelAlgorithm.GetVendorToken(returnURl, vendorPassword,
                                                                        vendorBlock, Username, Password, RememberMember);


            string URL = string.Format("{0}?vi={1}&vt={2}", PersonifyAutoLoginUrl, vendorId, encryptedVendorToken);
            //  var ssoRedirect = "http://smemitst.personifycloud.com/SSO/autologin.aspx" + "?vi=" + vendorId + "&vt=" + encryptedVendorToken;
            LoginUsertokentico.WriteError("URL which is sent via Autologin  --->", URL);
            Response.Redirect(URL);
        }
        catch (Exception exception)
        {
            // ApplicationEngine.HandleException(exception);
            Response.Write(exception.ToString());
            // LoginUsertokentico.WriteError("LoginMember", exception.ToString());

            EventLogProvider.LogException("LoginMember", "Get", exception);
        }
    }
    private void CheckSsoToken()
    {
        bool loggedin = objKenticoService.CheckLoginUser("");

        if (!loggedin)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ct"]))
            {
                var customerToken = Request.QueryString["ct"];
                Session["cuctomerReturnToken"] = customerToken;
                var decryptedToken = DecryptCustomerToken(customerToken);
                Session["OpenLoginBox"] = true;

                var finalToken = "";
                if (decryptedToken != "")
                {
                    finalToken = ValidateCustomerToken(decryptedToken);
                }
                // in case of corrupted decrypted token, until success, retry authentication x times as specified in web config to get new customer token
                if (finalToken == null && Convert.ToInt32(Session["retryAuth"]) < Convert.ToInt32(ConfigurationManager.AppSettings["PersonifyRetryCount"]))
                {
                    EventLogProvider.LogInformation("Personify corrupt decryption string", "Personify", "customer token: " + customerToken + "decrypted token: " + decryptedToken);
                    RetryAuth();
                }
                Session.Remove("uname");
                Session.Remove("pwd");
                var    customerIdentifier = "";
                string emailaddress       = null;
                string userName           = null;

                if (finalToken != "")
                {
                    customerIdentifier          = ValidateUser(finalToken, ref emailaddress, ref userName);
                    Session["PersonifyToken"]   = finalToken;
                    Session["redirecttomember"] = true;
                    Session["retryAuth"]        = Convert.ToInt32(ConfigurationManager.AppSettings["PersonifyRetryCount"]);
                    LoginUsertokentico.WriteError("token for " + userName, finalToken);
                }


                var eUserData = AuthenticateCustomer(customerIdentifier, emailaddress, userName);

                if (eUserData == null)
                {
                    return;
                }

                //use master customer id as the default password
                if (customerIdentifier != null)
                {
                    var defaultPassword = customerIdentifier.Split('|')[0];
                    if (Session["PersonifyToken"] == null && !string.IsNullOrEmpty(finalToken))
                    {
                        Session["PersonifyToken"] = finalToken;
                    }
                }

                if (_wsSso != null)
                {
                    _wsSso.Dispose();
                }

                var hasToken = Request.Url.AbsoluteUri.IndexOf("ct=", StringComparison.Ordinal) > 0;
                Session["redirecttomember"] = true;

                Response.Redirect(
                    hasToken
                        ? Request.Url.AbsoluteUri.Substring(0,
                                                            Request.Url.AbsoluteUri.IndexOf("ct=", StringComparison.Ordinal) - 1)
                        : Request.Url.AbsoluteUri, true);
            }
            else
            {
                if (Session["LoginAttempted"] != null)
                {
                    bool loginAttempted;
                    bool.TryParse(Session["LoginAttempted"].ToString(), out loginAttempted);
                    if (loginAttempted)
                    {
                        Session["OpenLoginBox"] = true;
                        Session.Remove("LoginAttempted");
                    }
                }
            }
        }
        else
        {
            bool flagpersonifyMember = false;
            //if logged in as admin user  keep the userlogged in
            /// If personify token is expired logout user
            ///
            if (CMS.Membership.AuthenticationHelper.IsAuthenticated())
            {
                UserInfo userdata =
                    CMS.Membership.UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserName);

                DataTable dt = UserInfoProvider.GetUserRoles(userdata);

                if (dt.Rows.Count > 0 && dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["RoleName"].ToString().ToLower().Contains("peronifyuser"))
                        {
                            flagpersonifyMember = true;
                        }
                    }
                }

                ///if personify key is null or empty
                ///
                if (flagpersonifyMember)
                {
                    string tokenReturn = null;
                    if (Session[PersonifySessionKey] != null)
                    {
                        tokenReturn = this.ValidateCustomerToken(Session[PersonifySessionKey].ToString());
                    }

                    if ((Session[PersonifySessionKey] == null) || tokenReturn == null)
                    {
                        /* Response.Redirect(
                         * Request.ServerVariables["PATH_INFO"] + "?action=logout&returnurl=" +
                         * Server.UrlEncode(Request.Url.AbsoluteUri), true);*/

                        //logout user
                        if (Session["userClass"] != null && Session["userClass"] != "")
                        {
                            userinfo ui = (userinfo)Session["userClass"];
                            objKenticoService.Logout(ui.username);
                            System.Web.Security.FormsAuthentication.SignOut();
                            HttpContext.Current.Response.Cookies["ASPXFORMSAUTH"].Expires = DateTime.Now.AddYears(-1);


                            Response.Redirect("/logout.aspx");
                        }
                    }
                }
            }
        }
    }
    //This method uses the msterCustomerID (remoteID) and looks up the coresponding UserID value in the database for this user.
    //This is done because looking up user by UserName will not work when the username is updated in AMS (Personify).
    //This method returns the UserId in Ektron based on RemoteID/CustomerID from Personify.

    private string AuthenticateCustomer(string customerIdentifier, string email, string userName)
    {
        string sMasterCustomerId = "";
        string pfirstname        = "";
        string plastname         = "";
        int    subCustomerId     = 0;
        string groupslist        = "";

        try
        {
            if (customerIdentifier.Contains('|'))
            {
                var aIdentifiers = customerIdentifier.Split('|');
                sMasterCustomerId = aIdentifiers[0];
                subCustomerId     = int.Parse(aIdentifiers[1]);
            }
            else
            {
                sMasterCustomerId = customerIdentifier;
            }

            //*******Start Custom Dataservice code to get Firstname, Lastname***********//
            Uri ServiceUri = new Uri(svcUri_Base);
            LoginUsertokentico.WriteError("AuthenticateCustomer ID ==>", sMasterCustomerId.ToString());
            PersonifyEntitiesBase DataAccessLayer = new PersonifyEntitiesBase(ServiceUri);
            DataAccessLayer.IgnoreMissingProperties = true;
            DataAccessLayer.Credentials             = new NetworkCredential(svcLogin, svcPassword);

            var userdetails =
                DataAccessLayer.CusNameDemographics.Where(p => p.MasterCustomerId == sMasterCustomerId)
                .Select(o => o)
                .ToList()
                .FirstOrDefault();

            pfirstname = null;
            plastname  = null;
            if (userdetails == null)
            {
                pfirstname = @"&nbsp;";
                plastname  = @"&nbsp;";
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.FirstName))
            {
                pfirstname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    pfirstname = userdetails.FirstName;
                }
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.LastName))
            {
                plastname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    plastname = userdetails.LastName;
                }
            }
            //*******End Custom Dataservice code to get Firstname, Lastname***********//

            string[] memberGroups = GetImsroles(sMasterCustomerId, subCustomerId);

            if (memberGroups.Length > 0)
            {
                foreach (string s in memberGroups)
                {
                    if (s.Length > 0)
                    {
                        groupslist += s + ",";
                    }
                }
            }

            groupslist += "peronifyUser" + ",";



            string login = objKenticoService.CreateUpdateLoginUserinKentico(
                userName,
                pfirstname,
                plastname,
                email,
                groupslist,
                true,
                false);
            userinfo uInfo = new userinfo
            {
                ID         = sMasterCustomerId,
                Token      = Session["PersonifyToken"].ToString(),
                email      = email,
                firstname  = pfirstname,
                lastname   = plastname,
                username   = userName,
                groupNames = groupslist
            };


            Session["userClass"] = uInfo;
            return(login);
        }
        catch (Exception exception)
        {
            EventLogProvider.LogException("AuthenticateCustomer", "Get", exception);
            LoginUsertokentico.WriteError("AuthenticateCustomer", exception.ToString());
            return(null);
        }
    }
Beispiel #7
0
    public string loadNavigation(string url)
    {
        try
        {
            string ret = "";
            var    uri = new Uri(url);
            var    doc = new HtmlWeb().Load(url);

            if (url.Contains("uca"))
            {
                var navigation = doc.DocumentNode.SelectNodes("//nav");
                if (navigation != null)
                {
                    var    sbNavigation = new StringBuilder(navigation[0].InnerHtml);
                    string remoteBase   = string.Format("https://{0}", uri.Host);
                    sbNavigation.Replace("href=\"/", String.Format("href=\"{0}/", remoteBase));
                    sbNavigation.Replace("src=\"/", String.Format("src=\"{0}/", remoteBase));
                    sbNavigation.Replace("resultsurl=\"/", String.Format("resultsurl=\"{0}/", remoteBase));

                    string x = "<div class=\"container\">" +
                               " <button class=\" btn-responsive-nav btn-inverse\" data-toggle=\"collapse\" data-target=\".nav-main-collapse\">" +
                               " <i class=\"fa fa-bars\">MENU</i></button>" +
                               " </div><div class=\"navbar-collapse nav-main-collapse collapse\">  <nav class=\"nav-main mega-menu\">";

                    ret = x + sbNavigation.ToString() + "</nav> </div>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/jquery.easing.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/bootstrap.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/commom.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/theme.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/theme.init.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org/CMSScripts/Custom/SME/bootstrap.js\"></script>";


                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=UCA_Theme\" type=\"text/css\" rel=\"stylesheet\" /> ";
                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=SME-bootstrap\" type=\"text/css\" rel=\"stylesheet\" /> ";
                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=UCA-Styles\" type=\"text/css\" rel=\"stylesheet\" /> ";
                    ret = ret + "<link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\" type=\"text/css\" rel=\"stylesheet\" /> ";

                    ret = ret + "<script type=\"text/javascript\">  $(\"#header .container .btn-responsive-nav\").click(function(e) { e.preventDefault();}); </script>";
                }
            }
            else
            {
                var navigation = doc.DocumentNode.SelectNodes("//nav");
                if (navigation != null)
                {
                    var    sbNavigation = new StringBuilder(navigation[0].InnerHtml);
                    string remoteBase   = string.Format("https://{0}", uri.Host);
                    sbNavigation.Replace("href=\"/", String.Format("href=\"{0}/", remoteBase));
                    sbNavigation.Replace("src=\"/", String.Format("src=\"{0}/", remoteBase));
                    sbNavigation.Replace("resultsurl=\"/", String.Format("resultsurl=\"{0}/", remoteBase));

                    string x = "<div class=\"container\">" +
                               " <button class=\" btn-responsive-nav btn-inverse\" data-toggle=\"collapse\" data-target=\".nav-main-collapse\">" +
                               " <i class=\"fa fa-bars\">MENU</i></button>" +
                               " </div><div class=\"navbar-collapse nav-main-collapse collapse\">  <nav class=\"nav-main mega-menu\">";

                    ret = x + sbNavigation.ToString() + "</nav> </div>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/jquery.easing.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/bootstrap.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/commom.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/theme.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org//CMSScripts/Custom/mob-nav/theme.init.js\"></script>";
                    ret = ret + "<script type=\"text/javascript\" src=\"https://www.smenet.org/CMSScripts/Custom/SME/bootstrap.js\"></script>";

                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=SME-bootstrap\" type=\"text/css\" rel=\"stylesheet\" /> ";
                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=SMETheme\" type=\"text/css\" rel=\"stylesheet\" /> ";

                    ret = ret + "<link href=\"https://www.smenet.org/CMSPages/GetResource.ashx?stylesheetname=SME-Styles\" type=\"text/css\" rel=\"stylesheet\" /> ";
                    ret = ret + "<link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\" type=\"text/css\" rel=\"stylesheet\" /> ";

                    ret = ret + " <script type=\"text/javascript\">  $(\"#header .container .btn-responsive-nav\").click(function(e) { e.preventDefault();}); </script>";
                }
            }
            return(ret);
        }
        catch (Exception ex)
        {
            LoginUsertokentico.WriteError(ex.ToString(), "For skinng the Navigation for loadNavigation : " + url);
            return(null);
        }
    }
    private void CheckSsoToken()
    {
        //  var userApi = new UserAPI();
        bool loggedin = objKenticoService.CheckLoginUser("");

        if (!loggedin)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ct"]))
            {
                lblMessage.Text = Request.QueryString["ct"];
                //  Ektron.Cms.Instrumentation.Log.WriteError(Request.QueryString["ct"]);
                var customerToken = Request.QueryString["ct"];
                ////
                Session["cuctomerReturnToken"] = customerToken;
                var decryptedToken = DecryptCustomerToken(customerToken);
                // Ektron.Cms.Instrumentation.Log.WriteError(decryptedToken);
                Session["OpenLoginBox"] = true;

                var finalToken = "";
                if (decryptedToken != "")
                {
                    finalToken = ValidateCustomerToken(decryptedToken);
                }

                var    customerIdentifier = "";
                string emailaddress       = null;
                string userName           = null;

                if (finalToken != "")
                {
                    customerIdentifier          = ValidateUser(finalToken, ref emailaddress, ref userName);
                    Session["PersonifyToken"]   = finalToken;
                    Session["redirecttomember"] = true;

                    LoginUsertokentico.WriteError("token for " + userName, finalToken);
                    if (string.IsNullOrEmpty(customerIdentifier))
                    {
                        //Response.Redirect("http://rapstst75.ebiz.uapps.net/Home/RegisterCustomer.aspx?Email=" +
                        //                  emailaddress + "&returnurl=" +
                        //                  "http://ek9-raps.syscomservices.com/sso_test.aspx");
                    }
                }


                var eUserData = AuthenticateCustomer(customerIdentifier, emailaddress, userName);

                if (eUserData == null)
                {
                    return;
                }

                //use master customer id as the default password
                if (customerIdentifier != null)
                {
                    var defaultPassword = customerIdentifier.Split('|')[0];

                    // var result = MyProvider.ValidateUser(eUserData.Username, defaultPassword);

                    if (Session["PersonifyToken"] == null && !string.IsNullOrEmpty(finalToken))
                    {
                        Session["PersonifyToken"] = finalToken;
                    }
                }

                if (_wsSso != null)
                {
                    _wsSso.Dispose();
                }

                var hasToken = Request.Url.AbsoluteUri.IndexOf("ct=", StringComparison.Ordinal) > 0;
                Session["redirecttomember"] = true;

                Response.Redirect(
                    hasToken
                        ? Request.Url.AbsoluteUri.Substring(0,
                                                            Request.Url.AbsoluteUri.IndexOf("ct=", StringComparison.Ordinal) - 1)
                        : Request.Url.AbsoluteUri, true);
            }
            else
            {
                if (Session["LoginAttempted"] != null)
                {
                    bool loginAttempted;
                    bool.TryParse(Session["LoginAttempted"].ToString(), out loginAttempted);
                    if (loginAttempted)
                    {
                        Session["OpenLoginBox"] = true;
                        Session.Remove("LoginAttempted");
                    }
                }
            }
        }
        else
        {
            bool flagpersonifyMember = false;
            //if logged in as admin user  keep the userlogged in
            /// If personify token is expired logout user
            ///
            if (CMS.Membership.AuthenticationHelper.IsAuthenticated())
            {
                UserInfo userdata =
                    CMS.Membership.UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserName);

                DataTable dt = UserInfoProvider.GetUserRoles(userdata);

                if (dt.Rows.Count > 0 && dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["RoleName"].ToString().ToLower().Contains("peronifyuser"))
                        {
                            flagpersonifyMember = true;
                        }
                    }
                }

                ///if personify key is null or empty
                ///
                if (flagpersonifyMember)
                {
                    string tokenReturn = null;
                    if (Session[PersonifySessionKey] != null)
                    {
                        tokenReturn = this.ValidateCustomerToken(Session[PersonifySessionKey].ToString());
                    }

                    if (Session[PersonifySessionKey] == null)//|| tokenReturn == null)
                    {
                        /* Response.Redirect(
                         * Request.ServerVariables["PATH_INFO"] + "?action=logout&returnurl=" +
                         * Server.UrlEncode(Request.Url.AbsoluteUri), true);*/

                        //logout user
                        if (Session["userClass"] != null && Session["userClass"] != "")
                        {
                            /* userinfo ui = (userinfo)Session["userClass"];  //Session["userClass"];
                             * objKenticoService.Logout(ui.username);
                             * System.Web.Security.FormsAuthentication.SignOut();
                             * HttpContext.Current.Response.Cookies["ASPXFORMSAUTH"].Expires = DateTime.Now.AddYears(-1);
                             *
                             */
                            // Response.Redirect("/logout.aspx");
                        }
                    }
                }
            }
        }
    }
    //This method uses the msterCustomerID (remoteID) and looks up the coresponding UserID value in the database for this user.
    //This is done because looking up user by UserName will not work when the username is updated in AMS (Personify).
    //This method returns the UserId in Ektron based on RemoteID/CustomerID from Personify.

    private string AuthenticateCustomer(string customerIdentifier, string email, string userName)
    {
        string sMasterCustomerId = "";
        string pfirstname        = "";
        string plastname         = "";
        int    subCustomerId     = 0;
        string groupslist        = "";

        try
        {
            var aIdentifiers = customerIdentifier.Split('|');
            sMasterCustomerId = aIdentifiers[0];
            subCustomerId     = int.Parse(aIdentifiers[1]);

            //*******Custom Dataservice code to get Firstname, Lastname*****//
            var personifyuser = new Personify.WebControls.Base.Business.PersonifyIdentity
            {
                ContainerName    = "Kentico",
                CurrencyCode     = "USD",
                MasterCustomerId =
                    sMasterCustomerId,
                SubCustomerId =
                    subCustomerId
            };
            //  var userdetails = new DemographicProvider().GetCusNameDemographic(personifyuser);
            // Uri ServiceUri = new Uri("http://smemi.personifycloud.com/PersonifyDataServices/PersonifyDatasme.svc");
            Uri ServiceUri = new Uri(svcUri_Base);

            LoginUsertokentico.WriteError("AuthenticateCustomer ID ==>", sMasterCustomerId.ToString());

            PersonifyEntitiesBase DataAccessLayer = new PersonifyEntitiesBase(ServiceUri);
            //  DataAccessLayer.Credentials = new NetworkCredential("admin", "admin123");
            DataAccessLayer.Credentials = new NetworkCredential(svcLogin, svcPassword);
            // var userdetails = DataAccessLayer.CusNameDemographics.Where(p => p.MasterCustomerId == sMasterCustomerId).Select(o => o).ToList().FirstOrDefault();
            var userdetails =
                DataAccessLayer.CusNameDemographics.Where(p => p.MasterCustomerId == sMasterCustomerId)
                .Select(o => o)
                .ToList()
                .FirstOrDefault();
            // var userdetails = new DemographicProvider().GetCusNameDemographic(personifyuser);
            pfirstname = null;
            plastname  = null;

            if (userdetails == null)
            {
                pfirstname = @"&nbsp;";
                plastname  = @"&nbsp;";
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.FirstName))
            {
                pfirstname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    pfirstname = userdetails.FirstName;
                }
            }
            if (userdetails != null && string.IsNullOrWhiteSpace(userdetails.LastName))
            {
                plastname = @"&nbsp;";
            }
            else
            {
                if (userdetails != null)
                {
                    plastname = userdetails.LastName;
                }
            }
            //*******End Custom Dataservice code to get Firstname, Lastname***********//

            string[] memberGroups = GetImsroles(sMasterCustomerId, subCustomerId);

            if (memberGroups.Length > 0)
            {
                foreach (string s in memberGroups)
                {
                    if (s.Length > 0)
                    {
                        groupslist += s + ",";
                    }
                }
            }

            groupslist += "peronifyUser" + ",";



            string login = objKenticoService.CreateUpdateLoginUserinKentico(
                userName,
                pfirstname,
                plastname,
                email,
                groupslist,
                true,
                false);
            userinfo uInfo = new userinfo
            {
                ID         = sMasterCustomerId,
                Token      = Session["PersonifyToken"].ToString(),
                email      = email,
                firstname  = pfirstname,
                lastname   = plastname,
                username   = userName,
                groupNames = groupslist
            };


            Session["userClass"] = uInfo;
            return(login);
        }
        catch (Exception exception)
        {
            EventLogProvider.LogException("AuthenticateCustomer", "Get", exception);
            LoginUsertokentico.WriteError("AuthenticateCustomer", exception.ToString());
            return(null);
            // evp.LogEvent("Source", "EventCode", exception,1);
            //evp.LogEvent("AuthenticateCustomer", "Get", exception.ToString(),"","",0,"",0,"","",0,"","","",DateTime.Now);
        }
    }