Imports System.Web
Imports System.Web.UI
Imports BaseClasses
Imports BaseClasses.Configuration
Imports BaseClasses.Utils

Namespace Security
    Partial Public Class SamlCallback
        Inherits System.Web.UI.Page

        Protected Sub Page_Load(sender As Object, e As EventArgs)
            Dim samlResponse = Request.Form("SAMLResponse")
            If String.IsNullOrEmpty(samlResponse) Then
                RedirectToSignInWithError("No SAML Response received")
                Return
            End If

            ' Certificate for validating SAML response
            Dim cert As String = _
            "-----BEGIN CERTIFICATE-----" & vbCrLf & _
            "MIIE6DCCAtCgAwIBAgIQOQaY6KUdPItB52hpOsIBvjANBgkqhkiG9w0BAQsFADAw" & vbCrLf & _
            "MS4wLAYDVQQDEyVBREZTIFNpZ25pbmcgLSBzc28uc2F0aXRtLmNodWxhLmFjLnRo" & vbCrLf & _
            "MB4XDTI1MDQwNjEyNTQxNFoXDTI2MDQwNjEyNTQxNFowMDEuMCwGA1UEAxMlQURG" & vbCrLf & _
            "UyBTaWduaW5nIC0gc3NvLnNhdGl0bS5jaHVsYS5hYy50aDCCAiIwDQYJKoZIhvcN" & vbCrLf & _
            "AQEBBQADggIPADCCAgoCggIBAMlu6kjF9Ghsr9Z6+AIYRjHTx4OL6fROrCzq26/h" & vbCrLf & _
            "YBfsrsL5QeJlWtYhRsbrW3wAFaQukNYal5LRJx8BXXlngIDIfoIEixT62BqFC2XO" & vbCrLf & _
            "Ju7Rq+p1ei2WZb06V0It8ohmZVPqsDPzygjBblta27DBGQ8qQ4upGVTwOIBRisMj" & vbCrLf & _
            "Ixxx90p6DeB2ZCiGOYCYMYPdFWwz8QCZv64WbWRw3WhRKla05nyiV352aaC53XL0" & vbCrLf & _
            "ZZlRFV8jj6YiKsbKEzkxKpDVxEaH28NGVptBJyfkU5VOpqkmZZtqhSCrrIprfa+j" & vbCrLf & _
            "Dl6De9Siq8/CUDoZhkhRoNUqmhaiu0ZbV3AF0iN+XLtmeP/GJREz5m3gOoAGH8Rl" & vbCrLf & _
            "g5pyca6vmSnJHKnTsu8Elc4pVvO6jH1hqdBLVFa4uftqqBY2B/ZuUXj7764eHsMZ" & vbCrLf & _
            "kHZC6SXOxAP2BPbRbslbd4CRErnuE5rgMRQAYQVWcrDvagUdvm2T1+wJN7GmwBg9" & vbCrLf & _
            "GGhTA3r9howvIj2RFLxCZbpy2QlWKMb1zjyvtCHrM7g8/aGuvJfY5cmfww5aib4a" & vbCrLf & _
            "QpJq+ZyCPZpW8iXZTnxVuyV57WFTOmCvy/9dfK/IQXEqG5FIikwaB2nyL/D5FXIP" & vbCrLf & _
            "xH+OzLeLdLlKe2zpOJgx2p1M6rJ29AJRASKs+ikqlSV/i5t+1sw2qinFKJ8ZegsN" & vbCrLf & _
            "HDgBAgMBAAEwDQYJKoZIhvcNAQELBQADggIBABzrTEbbzMHbq0mIV1w3TL6IVOv8" & vbCrLf & _
            "BeXoYznSI7P/MhJwBXMbrYNNbpSkv5jWhtSAWQWrDrN0IUqvKwIYYRlRtgvma6Mk" & vbCrLf & _
            "PFXRvzkVhpuqm/bp1HAH2yoJUXNuWInzdJeMnPaQymU/hSvSJ8f66pwlPrAYTSBk" & vbCrLf & _
            "YIbcEdLJ3OmcnjOjj4W+s70J0s0HTnNQboAzjue3SmpsPVVetP+cwaoIASz2M6Fr" & vbCrLf & _
            "wfqFaUUiSAxcUzfELOyN8d1dnRFQVkrNyayz0fHH2Kje5GnGLMNaZTKZ88nVbmoq" & vbCrLf & _
            "Cbow7ofjEb74jNwWhmRhntuEE0I1W55LnU3Srjptjnfkd604W60DbqiWBKM6rTTb" & vbCrLf & _
            "ilCJsW3umI26/eFZAfZIA2n7/FKDcDXFCJOM1UV+09pZ12p0TAaA3nyA2TbdI+PM" & vbCrLf & _
            "GtvvEK2PU+tdU64uAlOOaldk52dIuR7kOVBk53Gf3K2wY2U/oovLrlXLHb8NJD49" & vbCrLf & _
            "Po6XT3w6WL+okyr7FgdmAHTNpTnthXG0pyN4KUFEAK9HWXdGRWUgFX4yBOjmPN1N" & vbCrLf & _
            "Vx7G3klMd+ccQUU80lxDKQUbjhcWLloWNlg6w2SKk4Ku7/f8HmPkqppvFow+ytWm" & vbCrLf & _
            "0abcCjptoUrFR1BCM86CIDCo9bEWIyWv+SHr2AvlQ8D0Z8aQRr6M73NN1PNWruPf" & vbCrLf & _
            "bpD2ekhB2vZ9R2ij" & vbCrLf & _
            "-----END CERTIFICATE-----"

            Try
                Dim resp = New SamlHelper.Response(cert, samlResponse)
                If resp.IsValid() Then
                    ' Extract user information from SAML response
                    Dim email = resp.GetEmail()
                    Dim firstName = resp.GetFirstName()
                    Dim lastName = resp.GetLastName()
                    
                    ' Authenticate user in the application
                    If AuthenticateSamlUser(email, firstName, lastName) Then
                        ' Redirect to success page or back to original requested page
                        RedirectOnSuccess()
                    Else
                        RedirectToSignInWithError("User authentication failed")
                    End If
                Else
                    RedirectToSignInWithError("Invalid SAML Response")
                End If
            Catch ex As Exception
                RedirectToSignInWithError("Error processing SAML response: " & ex.Message)
            End Try
        End Sub

        Private Function AuthenticateSamlUser(email As String, firstName As String, lastName As String) As Boolean
            Try
                ' Create a base application page to access security methods
                Dim basePage As BaseApplicationPage = DirectCast(Me.Page, BaseApplicationPage)
                Dim errMessage As String = ""
                
                ' Use email as username for authentication
                ' This assumes your user table uses email as the primary identifier
                Dim success As Boolean = basePage.CurrentSecurity.SetLoginInfo(email, "", errMessage)
                
                If success Then
                    ' User authenticated successfully
                    Return True
                Else
                    ' Log the authentication failure
                    System.Diagnostics.Debug.WriteLine("SAML Authentication failed: " & errMessage)
                    Return False
                End If
            Catch ex As Exception
                System.Diagnostics.Debug.WriteLine("SAML Authentication error: " & ex.Message)
                Return False
            End Try
        End Function

        Private Sub RedirectOnSuccess()
            ' Check if there's a return URL in session or query string
            Dim returnUrl As String = Request.QueryString("ReturnUrl")
            If String.IsNullOrEmpty(returnUrl) Then
                returnUrl = ApplicationSettings.Current.DefaultPageUrl()
            End If
            
            If String.IsNullOrEmpty(returnUrl) Then
                returnUrl = "~/Default.aspx"
            End If
            
            Response.Redirect(returnUrl)
        End Sub

        Private Sub RedirectToSignInWithError(message As String)
            Dim signInUrl As String = ApplicationSettings.Current.SignInPageUrl()
            If String.IsNullOrEmpty(signInUrl) Then
                signInUrl = "~/Security/SignIn.aspx"
            End If
            
            signInUrl &= "?message=" & Server.UrlEncode(message)
            Response.Redirect(signInUrl)
        End Sub
    End Class
End Namespace