Imports System.Web.Security
'Imports System.Security.Cryptography
'Imports System.IO
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Web.Configuration
' Imports CharterDotCom.Common.Logging

Partial Class LogIn

    Inherits System.Web.UI.Page

    Private roleName As String
    Private _roles As String()
    Dim info As CMS.UserInfo
    Private templateIDs As String

   

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Dim dp As New DpapiProtectedConfigurationProvider()



        'Dim txtUserID As String = "rcopeland"




        'If Not (Profile.CMSUserID Is Nothing) Or (Profile.CMSUserID.Trim() <> "") Then
        '    Dim lMachineKey As MachineKeySection = CType(System.Web.Configuration.WebConfigurationManager.GetSection("system.web/machineKey"), MachineKeySection)

        '    Dim EncryptedString As String = EncryptString128Bit(txtUserID, lMachineKey.ValidationKey)
        '    Profile.CMSUserID = EncryptedString


        '    'Dim EncryptedString As String = EncryptString128Bit(Profile.CMSUserID, lMachineKey.ValidationKey)
        '    Dim decryptedProfileID As String = DecryptString128Bit(Profile.CMSUserID, lMachineKey.ValidationKey)

        '    If txtUserID = decryptedProfileID Then
        '        decryptedProfileID = decryptedProfileID
        '    Else
        '        Throw New Exception("keys dont match")
        '    End If
        'Else

        'End If


    End Sub


    'Public Function EncryptString128Bit(ByVal vstrTextToBeEncrypted As String, ByVal vstrEncryptionKey As String) As String

    '    Dim bytValue() As Byte
    '    Dim bytKey() As Byte
    '    Dim bytEncoded() As Byte
    '    Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}
    '    Dim intLength As Integer
    '    Dim intRemaining As Integer
    '    Dim objMemoryStream As New MemoryStream()
    '    Dim objCryptoStream As CryptoStream
    '    Dim objRijndaelManaged As RijndaelManaged


    '    '   **********************************************************************
    '    '   ******  Strip any null character from string to be encrypted    ******
    '    '   **********************************************************************

    '    vstrTextToBeEncrypted = StripNullCharacters(vstrTextToBeEncrypted)

    '    '   **********************************************************************
    '    '   ******  Value must be within ASCII range (i.e., no DBCS chars)  ******
    '    '   **********************************************************************

    '    bytValue = Encoding.ASCII.GetBytes(vstrTextToBeEncrypted.ToCharArray)

    '    intLength = Len(vstrEncryptionKey)

    '    '   ********************************************************************
    '    '   ******   Encryption Key must be 256 bits long (32 bytes)      ******
    '    '   ******   If it is longer than 32 bytes it will be truncated.  ******
    '    '   ******   If it is shorter than 32 bytes it will be padded     ******
    '    '   ******   with upper-case Xs.                                  ****** 
    '    '   ********************************************************************

    '    If intLength >= 32 Then
    '        vstrEncryptionKey = Strings.Left(vstrEncryptionKey, 32)
    '    Else
    '        intLength = Len(vstrEncryptionKey)
    '        intRemaining = 32 - intLength
    '        vstrEncryptionKey = vstrEncryptionKey & Strings.StrDup(intRemaining, "X")
    '    End If

    '    bytKey = Encoding.ASCII.GetBytes(vstrEncryptionKey.ToCharArray)

    '    objRijndaelManaged = New RijndaelManaged()

    '    '   ***********************************************************************
    '    '   ******  Create the encryptor and write value to it after it is   ******
    '    '   ******  converted into a byte array                              ******
    '    '   ***********************************************************************

    '    Try

    '        objCryptoStream = New CryptoStream(objMemoryStream, _
    '          objRijndaelManaged.CreateEncryptor(bytKey, bytIV), _
    '          CryptoStreamMode.Write)
    '        objCryptoStream.Write(bytValue, 0, bytValue.Length)

    '        objCryptoStream.FlushFinalBlock()

    '        bytEncoded = objMemoryStream.ToArray
    '        objMemoryStream.Close()
    '        objCryptoStream.Close()
    '    Catch



    '    End Try

    '    '   ***********************************************************************
    '    '   ******   Return encryptes value (converted from  byte Array to   ******
    '    '   ******   a base64 string).  Base64 is MIME encoding)             ******
    '    '   ***********************************************************************

    '    Return Convert.ToBase64String(bytEncoded)

    'End Function




    'Public Function DecryptString128Bit(ByVal vstrStringToBeDecrypted As String, ByVal vstrDecryptionKey As String) As String

    '    Dim bytDataToBeDecrypted() As Byte
    '    Dim bytTemp() As Byte
    '    Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}
    '    Dim objRijndaelManaged As New RijndaelManaged()
    '    Dim objMemoryStream As MemoryStream
    '    Dim objCryptoStream As CryptoStream
    '    Dim bytDecryptionKey() As Byte

    '    Dim intLength As Integer
    '    Dim intRemaining As Integer
    '    Dim intCtr As Integer
    '    Dim strReturnString As String = String.Empty
    '    Dim achrCharacterArray() As Char
    '    Dim intIndex As Integer

    '    '   *****************************************************************
    '    '   ******   Convert base64 encrypted value to byte array      ******
    '    '   *****************************************************************

    '    bytDataToBeDecrypted = Convert.FromBase64String(vstrStringToBeDecrypted)

    '    '   ********************************************************************
    '    '   ******   Encryption Key must be 256 bits long (32 bytes)      ******
    '    '   ******   If it is longer than 32 bytes it will be truncated.  ******
    '    '   ******   If it is shorter than 32 bytes it will be padded     ******
    '    '   ******   with upper-case Xs.                                  ****** 
    '    '   ********************************************************************

    '    intLength = Len(vstrDecryptionKey)

    '    If intLength >= 32 Then
    '        vstrDecryptionKey = Strings.Left(vstrDecryptionKey, 32)
    '    Else
    '        intLength = Len(vstrDecryptionKey)
    '        intRemaining = 32 - intLength
    '        vstrDecryptionKey = vstrDecryptionKey & Strings.StrDup(intRemaining, "X")
    '    End If

    '    bytDecryptionKey = Encoding.ASCII.GetBytes(vstrDecryptionKey.ToCharArray)

    '    ReDim bytTemp(bytDataToBeDecrypted.Length)

    '    objMemoryStream = New MemoryStream(bytDataToBeDecrypted)

    '    '   ***********************************************************************
    '    '   ******  Create the decryptor and write value to it after it is   ******
    '    '   ******  converted into a byte array                              ******
    '    '   ***********************************************************************

    '    Try

    '        objCryptoStream = New CryptoStream(objMemoryStream, _
    '           objRijndaelManaged.CreateDecryptor(bytDecryptionKey, bytIV), _
    '           CryptoStreamMode.Read)

    '        objCryptoStream.Read(bytTemp, 0, bytTemp.Length)

    '        objCryptoStream.FlushFinalBlock()
    '        objMemoryStream.Close()
    '        objCryptoStream.Close()

    '    Catch

    '    End Try

    '    '   *****************************************
    '    '   ******   Return decypted value     ******
    '    '   *****************************************

    '    Return StripNullCharacters(Encoding.ASCII.GetString(bytTemp))

    'End Function


    'Public Function StripNullCharacters(ByVal vstrStringWithNulls As String) As String

    '    Dim intPosition As Integer
    '    Dim strStringWithOutNulls As String

    '    intPosition = 1
    '    strStringWithOutNulls = vstrStringWithNulls

    '    Do While intPosition > 0
    '        intPosition = InStr(intPosition, vstrStringWithNulls, vbNullChar)

    '        If intPosition > 0 Then
    '            strStringWithOutNulls = Left$(strStringWithOutNulls, intPosition - 1) & _
    '                              Right$(strStringWithOutNulls, Len(strStringWithOutNulls) - intPosition)
    '        End If

    '        If intPosition > strStringWithOutNulls.Length Then
    '            Exit Do
    '        End If
    '    Loop

    '    Return strStringWithOutNulls

    'End Function















    '######################################################
    'This method simple converts the role list into a string array so it 
    'can be stored in the forms authentication cookie    '
    '######################################################
    Function TokenizeRoleList() As String
        Dim _retval As StringBuilder = New StringBuilder
        Dim _first As Boolean = True

        For Each role As String In _roles
            If _first Then
                _retval.Append(role)
                _first = False
            Else
                _retval.Append(";" & role)
            End If
        Next
        Return _retval.ToString()
    End Function

    Private Function ValidateUser() As Boolean

        Try
            'Logger.ServiceLog("\BL.RemotingHost\LogIn\ValidateUser")

            'roleName = "ContentAuthor"
            ' _roles = CMSContentManager.Instance.Authenticate(userNameTextBox.Text.Trim().ToLower(), passwordTextBox.Text)

            Dim s As CMSContentManager = New CMSContentManager
            info = s.Authenticate(ctxLogin.UserName, ctxLogin.Password)


            _roles = info.USerRoles 

            If _roles.Length = 0 Then

                ValidateUser = False

            Else

                ValidateUser = True

            End If

        Catch ex As Exception

            Throw ex

        End Try

    End Function

    Protected Sub ctxLogin_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles ctxLogin.Authenticate
       

        Try

            If ValidateUser() Then
                e.Authenticated = True

'               add a user and userinfo key to the seesion state.  These are used throughout the site to ensure the 
'               user is logged in and also to pull information about the user performing actions.  The code below first
'               converts ths return from the webservice call to a CMSUserToken object.  It then saves that token to a cookie
'               userToken whick is typically used to ensure authentication in a farm environment (since we wont have cookies)
                Dim userinfo As New CMSUserToken
                userinfo._userid = info.UserID
                userinfo._roles = info.USerRoles

'               xmlserialize the userinfo token and place in cookie
                Dim ticket As String = CMSUserToken.SerializeToTicket(userinfo)
                Dim cookie As HttpCookie = New HttpCookie("userToken", ticket)
                cookie.Expires = DateTime.Now.AddMinutes(Session.Timeout)
                Response.Cookies.Add(cookie)

'               also add userinfo and userrow from dal to session state for the current server.  These values will
'               of course not be there on any other server in the farm, but the cookie will allow us to validate authentication
'               and we will use the information in the deserialized userinfo object to load the userrow into any servers that
'               do not have it
                Session("userinfo") = userinfo
                Dim usersTA As DALTableAdapters.UsersTableAdapter = New DALTableAdapters.UsersTableAdapter
                Dim users As DAL.UsersDataTable = usersTA.GetData()
                Dim user As DAL.UsersRow = users.FindByUserID(userinfo._userid)
                Session("user") = user

               

                Dim redirecturl As String = Request.QueryString("redirecturl")
                If redirecturl Is Nothing Then
                    redirecturl = ""
                End If

                Dim s As CMSContentManager = New CMSContentManager
                


                If redirecturl.Length = 0 Then
                    Response.Redirect("Default.aspx")
                Else
                    Response.Redirect(redirecturl)
                End If

            Else
                If info.UserID = -1 Then
                    e.Authenticated = False
                    Me.ctxLogin.FailureText = "Although you are a valid user, no roles have been assigned to you yet so you may not log on at this time"
                End If
            End If

        Catch ex As Exception

            Throw

        End Try
    End Sub
End Class

