Imports Microsoft.VisualBasic
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports CharterDotCom.CommonEntities.Library.Common
Imports CharterDotCom.WebSite.Library
Imports System.Web

Namespace Utilities

    Public Class LoginHandler
        Private Const cMYACCOUNT_ASPX As String = "~/Account/MyAccount.aspx"

        '***************************************
        'JPirkey 4-2010 MyAccount Feature Update
        '***************************************
        'This routine was broken out into a separate piece because it's not being called from three different places.
        'However, the source routine has a number of dependencies, such as the Request, Response and Application objects
        'This is the reason for the PageContext As HttpContext parameter.
        '
        'I also had to move the GetRedirectsUrl function since it was also dependent on this routine.
        'However, it made sense since it's only use was from within the login page and it's function is
        'specific to the login procedure.

        Public Shared Function Login(ByRef PageContext As HttpContext, ByVal RememberMe As Boolean, ByVal UserName As String, ByVal Password As String, ByVal ZipCode As String, ByVal validator As CustomValidator, ByVal IsAuthor As Boolean) As Boolean

            Try
                Dim Application As HttpApplicationState = PageContext.Application
                Dim Response As HttpResponse = PageContext.Response
                Dim Request As HttpRequest = PageContext.Request
                Dim Server As HttpServerUtility = PageContext.Server
                Dim reqURL As String = Request.Url.ToString().ToLower()

                Dim cookie As HttpCookie
                Dim ticket As FormsAuthenticationTicket
                Dim encryptedText As String
                Dim roleName As String
                ' issue 26553
                Dim accountInfo As IAccount

                Dim blSignInResult As Boolean = False
                If Not (Application("USE_ZIP_VERIFICATION") Is Nothing) Then
                    If Application("USE_ZIP_VERIFICATION").ToString().Trim().ToUpper() = "T" Then
                        'naqib -- 
                        blSignInResult = AccountManager.Instance.SignIn(UserName, Password, ZipCode, IsAuthor)
                    Else
                        blSignInResult = AccountManager.Instance.SignIn(UserName, Password, IsAuthor)
                    End If
                Else
                    blSignInResult = AccountManager.Instance.SignIn(UserName, Password, IsAuthor)
                End If

                If blSignInResult Then
                    If RememberMe Then
                        cookie = New HttpCookie(CookieName.m_UserName, UserName)
                        cookie.Expires = DateTime.Now.AddYears(1)
                        Response.Cookies.Add(cookie)

                        cookie = New HttpCookie(CookieName.m_ZipCode, ZipCode)
                        cookie.Expires = DateTime.Now.AddYears(1)
                        Response.Cookies.Add(cookie)

                    Else
                        Response.Cookies(CookieName.m_UserName).Expires = DateTime.Now.AddYears(-1)
                        Response.Cookies(CookieName.m_ZipCode).Expires = DateTime.Now.AddYears(-1)
                    End If

                    If Not (validator Is Nothing) Then
                        validator.IsValid = True
                    End If

                    If IsAuthor Then
                        roleName = "author"
                    Else
                        roleName = "member"
                    End If

                    ticket = New FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(60), False, roleName)
                    encryptedText = FormsAuthentication.Encrypt(ticket)
                    cookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedText)
                    Response.Cookies.Add(cookie)
                    ' issue 26553
                    accountInfo = AccountManager.Instance.GetAccount()
                    CookieHandler.StoreCookies(UserName, accountInfo.OSSProvidedAccountNumber, Response, Server, Application("COOKIE_DOMAIN"))

                    ' default redirect path (home page)
                    Dim defaultRedirectPath As String = cMYACCOUNT_ASPX

                    ' a few pages need special handling
                    If reqURL.IndexOf("payyourbill.aspx") > -1 Then
                        Response.Redirect(cMYACCOUNT_ASPX)
                        ' issue 28648
                    ElseIf reqURL.IndexOf("register.aspx") > -1 Then
                        Response.Redirect(cMYACCOUNT_ASPX)
                    ElseIf reqURL.IndexOf("home.aspx") > -1 Then
                        Response.Redirect(cMYACCOUNT_ASPX)
                    ElseIf (reqURL.IndexOf("order/login.aspx") > -1) OrElse _
                          (reqURL.IndexOf("order/retrieveusername.aspx") > -1) Then
                        '#######################################################################
                        '10/02/2007     ROD COPELAND    
                        'TO SATISFY ISSUE ID 2718 AND ALLOW THE CHARTER.NET FOLKS TO REDIRECT TO 
                        'SPECIFIC PAGES AFTER LOGIN, READ THE QUERYSTRING VALUE FOR THE TARGET 
                        'URL AND REDIRECT THE USER TO THE LOCATION.
                        '#######################################################################
                        Dim returnurl As String = Request.QueryString("returnurl")
                        Dim _account As IAccount = AccountManager.Instance.GetAccount()
                        If returnurl Is Nothing OrElse returnurl.Equals(String.Empty) Then
                            '###################################################
                            'DO THE NORMAL REDIRECT TO THE LANDING PAGE LIKELY
                            '###################################################

                            '###############################################################
                            'MODIFICATION   SIVA DOLA   CHARTER BUSINESS    11/02/2008
                            'To enable CB MyAccount section
                            '###############################################################
                            Dim blnCBMyAccountUse As String = Application("ENABLE_CHARTER_BUSINESS_MYACCOUNT_SECTION")
                            Dim url As String = reqURL
                            If Not (blnCBMyAccountUse Is Nothing) Then
                                Select Case blnCBMyAccountUse.Trim().ToUpper()
                                    Case "T"

                                        '#############################################################################
                                        '5/19/2008     Siva Dola  
                                        'To enable CB MYAccount section based on EXPOSE_CB_TO_INTERNAL_TRAFFIC_ONLY value
                                        'To enable CB MYAccount section for internal users who are Commercial or Business
                                        '#############################################################################
                                        Dim strIPAddress As String = ""
                                        If Not _account Is Nothing Then
                                            If Not (_account.AccountType Is Nothing) Then
                                                Select Case _account.AccountType.ToLower().Trim()
                                                    Case "commercial", "bus"
                                                        Dim blnExposeCBToInternalTrafficOnly As String = Application("EXPOSE_CB_TO_INTERNAL_TRAFFIC_ONLY")
                                                        Select Case blnExposeCBToInternalTrafficOnly.Trim().ToUpper()
                                                            Case "T"
                                                                '#############################################################################
                                                                '6/11/2008     Siva Dola  
                                                                'To enable CB MYAccount section for internal users(based on mathced IP ADDRESS)
                                                                '#############################################################################

                                                                Dim strUserIP As String = ""
                                                                Dim arrIPAddress() As String
                                                                Dim intLoop As Integer
                                                                Dim strIp As String
                                                                Dim blnCBShow As Boolean

                                                                '########################################################################
                                                                'ROD COPELAND   MODIFICATION JULY 9, 2008
                                                                'NEED A BETTER WAY TO OBTAIN THE SOURCE IP WHEN SITTING BEHIND THE F5.
                                                                '########################################################################
                                                                Dim ipChecker As New Utilities.IPRestriction
                                                                strUserIP = ipChecker.getF5SourceIP()
                                                                If (strUserIP Is Nothing) Then
                                                                    '######################################################################
                                                                    'IF THE F5 DERIVED SOURCE IP IS NOT AVAILABLE, THEN ATTEMPT TO USE THE 
                                                                    'DEFAULT WAY OF OBTAINING THE SOURCE IP.
                                                                    '######################################################################
                                                                    strUserIP = Request.ServerVariables("REMOTE_ADDR")
                                                                End If
                                                                '########################################################################

                                                                If strUserIP.Trim() <> "" Then
                                                                    strIPAddress = Application("CB_MYACCOUNT_ALLOWED_IP_ADDRESS_LIST")
                                                                    If strIPAddress.Length > 0 Then
                                                                        arrIPAddress = strIPAddress.Split(",")
                                                                        For intLoop = 0 To arrIPAddress.Length - 1
                                                                            strIp = arrIPAddress(intLoop)
                                                                            If (0 = String.Compare(strUserIP, strIp)) Then
                                                                                blnCBShow = True
                                                                            End If
                                                                        Next
                                                                    End If
                                                                End If

                                                                If blnCBShow Then
                                                                    Call GetRedirectsurl(Response, url, UserName, Password, _account.AccountType.ToLower().Trim())
                                                                Else
                                                                    Response.Redirect(cMYACCOUNT_ASPX)
                                                                End If

                                                            Case Else
                                                                'ALLOW ALL PEOPLE TO USE THE CB SECTION, INTERNAL AND EXTERNAL, FULL GOLIVE.
                                                                Call GetRedirectsurl(Response, url, UserName, Password, _account.AccountType.ToLower().Trim())
                                                        End Select
                                                    Case Else
                                                        '#################################################################
                                                        'CONSIDERED TO BE RESEDENTIAL CUSTOMERS, SEND TO THE RESIDENTIAL 
                                                        'MY ACCOUNT LANDING PAGE.
                                                        '#################################################################
                                                        Response.Redirect(cMYACCOUNT_ASPX)
                                                End Select
                                            Else
                                                Response.Redirect(cMYACCOUNT_ASPX)
                                            End If
                                        Else
                                            Response.Redirect(cMYACCOUNT_ASPX)
                                        End If
                                    Case Else
                                        '###############################################################
                                        'ASSUME THE CHARTER BUSINESS MYACCOUNT SECTION IS TURNED OFF, 
                                        'JUST SHOW THE NORMAL RESEDENTIAL.
                                        '###############################################################
                                        Response.Redirect(cMYACCOUNT_ASPX)

                                End Select
                            Else
                                Response.Redirect(cMYACCOUNT_ASPX)
                            End If
                        Else
                            '#########################################################################
                            'SEND THEM DIRECTLY TO THE REDIRECT PATH THEY HAVE SENT VIA QUERYSTRING
                            '#########################################################################
                            Response.Redirect(returnurl)
                        End If
                    Else
                        ' was a redirect page passed?
                        Dim formsAuthenticationRedirectUrl As String = FormsAuthentication.GetRedirectUrl(UserName, False)
                        If formsAuthenticationRedirectUrl.Length = 0 Then
                            Response.Redirect(defaultRedirectPath)
                        Else
                            Response.Redirect(formsAuthenticationRedirectUrl)
                        End If
                    End If

                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception
                Return False
            End Try
        End Function

        Private Shared Sub GetRedirectsurl(ByRef Response As HttpResponse, ByVal sURL As String, ByVal UserName As String, ByVal Password As String, ByVal AcctType As String)

            If AcctType Is Nothing Then
                Response.Redirect(cMYACCOUNT_ASPX)
            Else
                If (AcctType.Trim = String.Empty) Then
                    Response.Redirect(cMYACCOUNT_ASPX)
                End If
            End If

            Select Case True

                '###########################################################################
                'The following section is for charter.com Commercial
                '###########################################################################

                Case sURL.Contains("://business.charter.com"), sURL.Contains("://www.business.charter.com")
                    'CB PROD
                    'WE NEED TO LEAVE THE USER IN THIS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("~/CBAccount/CBMyAccount.aspx")
                    Else
                        Response.Redirect("https://www.charter.com/order/login.aspx?un=" + UserName + "&pwd=" + Password)
                    End If

                Case sURL.Contains("://business.cc2uatx")
                    'CB TEST
                    'WE NEED TO LEAVE THE USER IN THIS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("~/CBAccount/CBMyAccount.aspx")
                    Else
                        Response.Redirect("https://cc2uatx.chartercom.com/order/login.aspx?un=" + UserName + "&pwd=" + Password)
                    End If

                Case sURL.Contains("://kstlmweb65:81")
                    'CB DEV
                    'WE NEED TO LEAVE THE USER IN THIS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("~/CBAccount/CBMyAccount.aspx")
                    Else
                        Response.Redirect("https://kstlmweb65/order/login.aspx?un=" + UserName + "&pwd=" + Password)
                    End If

                Case sURL.Contains("://localhost/business")
                    'CB LOCALHOST
                    'WE NEED TO LEAVE THE USER IN THIS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("~/CBAccount/CBMyAccount.aspx")
                    Else
                        Response.Redirect("http://localhost/Order/Login.aspx?un=" + UserName + "&pwd=" + Password)
                    End If

                    '###########################################################################
                    'The following section is for charter.com Residential
                    '###########################################################################

                Case sURL.Contains("://charter.com"), sURL.Contains("://www.charter.com")
                    'CHARTER.COM PROD
                    'WE NEED TO REDIRECT THE USER IN THE APPROPRIATE BUSINESS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("https://www.business.charter.com/order/CBlogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                Case sURL.Contains("://cc2uatx.chartercom.com"), sURL.Contains("://cc2uatw")
                    'CHARTER.COM TEST
                    'WE NEED TO REDIRECT THE USER IN THE APPROPRIATE BUSINESS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("https://business.cc2uatx.chartercom.com/order/CBlogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                Case sURL.Contains("://kstlmweb65/")
                    'CHARTER.COM DEV
                    'WE NEED TO REDIRECT THE USER IN THE APPROPRIATE BUSINESS DOMAIN
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("https://kstlmweb65:81/order/CBlogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                Case sURL.Contains("://localhost/ui")
                    'CHARTER.COM LOCALHOST
                    'WE NEED TO REDIRECT THE USER IN THE APPROPRIATE BUSINESS DOMAIN
                    'Response.Redirect("~/CBAccount/CBMyAccount.aspx")
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("http://localhost/business/Order/CBLogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                    '###########################################################################
                    '06-24-08   SDOLA   
                    'Conditions added to handle UAT & PROD BOXES individually
                    '###########################################################################

                    '###########################################################################
                    'The following section is for UAT BOXES
                    '###########################################################################

                Case sURL.Contains("://kstlmccws01/"), sURL.Contains("://kstlmccws02/"), _
                    sURL.Contains("://kstlmccws03/"), sURL.Contains("://kstlmccws04/"), _
                    sURL.Contains("://kstlmccws05/")
                    'CHARTER.COM UAT BOX
                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("https://business.cc2uatx.chartercom.com/order/CBlogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                    '###########################################################################
                    'The following section is for PROD BOXES
                    '###########################################################################

                Case sURL.Contains("://kstlmcc2p01"), sURL.Contains("://kstlmcc2p02"), _
                    sURL.Contains("://www.charter.com"), sURL.Contains("://kstlmccwp01"), _
                    sURL.Contains("://kstlmccwp02"), sURL.Contains("://kstlmccwp03"), _
                    sURL.Contains("://kstlmccwp04"), sURL.Contains("://kstlmccwp05")
                    'CHARTER.COM PROD BOX

                    If AcctType.ToLower = "bus" Or AcctType.ToLower = "commercial" Then
                        Response.Redirect("https://www.business.charter.com/order/CBlogin.aspx?un=" + UserName + "&pwd=" + Password)
                    Else
                        Response.Redirect(cMYACCOUNT_ASPX)
                    End If

                Case Else
                    'JUST SEND TO THE NORMAL CHARTER.COM RESIDENTIAL MYACCOUNT LANDING PAGE.
                    Response.Redirect(cMYACCOUNT_ASPX)
            End Select
        End Sub

        Public Shared Function EvaluateFailedAttemptLockout(ByRef PageContext As HttpContext, ByVal lTypeName As String) As Boolean
            '#################################################################
            '4/09/2010 SRIMAN KANURI
            'This procedure has been moved from Login.ascx so this can be a reusable function
            ' and can be called from different pages. 
            '#################################################################
            Dim Application As HttpApplicationState = PageContext.Application
            Dim Session As HttpSessionState = PageContext.Session

            Try
                '#################################################################
                '6/21/2007  ROD COPELAND
                'SHOW THE PLEASE CONTACT CUST SERVICE PANEL, THEY MAY HAVE EXCEEDED THE
                'MAX ERRORS FOR QUICK PAY ATTEMPTS AS DEFINED BY CUST CARE 
                'DEPARTMENT AND DIANA
                '#################################################################

                '#############################################################################
                'IF DATE IS STILL ACTIVE, SHOW CALL BACK PANEL IF MAX COUNT HAS BEEN EXCEEDED
                '#############################################################################
                If Not (Session(lTypeName & "_FAILED_TotalAttemptCount") Is Nothing) Then
                    If Session(lTypeName & "_FAILED_TotalAttemptCount") >= Application(lTypeName & "_FAILED_ATTEMPT_MAX_COUNT") Then

                        'we continue to lock them out until the time limit runs out then we give option to make payments again.
                        If (Session(lTypeName & "_FAILED_LockDownStartTime") Is Nothing) Then
                            Session(lTypeName & "_FAILED_LockDownStartTime") = New Date(Now.AddMinutes(CType(Application(lTypeName & "_FAILED_LOCKOUT_WAIT_MINUTES"), Integer)).Ticks())
                        End If
                        If Session(lTypeName & "_FAILED_LockDownStartTime") < Now Then
                            '################################
                            'ALLOW ACCESS TO MAKE A PAYMENT
                            '################################
                            Session.Remove(lTypeName & "_FAILED_LockDownStartTime")
                            Session.Remove(lTypeName & "_FAILED_TotalAttemptCount")
                            Return False
                        Else
                            '#########################################
                            'CONTINUE TO LOCK THEM OUT FROM PAYMENTS
                            '#########################################
                            Return True
                        End If
                    Else
                        Return False
                    End If
                End If

                Return False

            Catch ex As Exception
                Return True
            End Try
        End Function
    End Class
End Namespace