Imports AppAuth
Imports AppCommon
Imports AppVariable
Imports System.Net
Imports System.IO


Partial Public Class login
    Inherits System.Web.UI.Page

#Region "******************** ページイベント ********************"

    Private DBServerAuthUserId As String = ConfigurationManager.AppSettings("WebDavAuthUserId").ToString()
    Private DBServerAuthUserPass As String = ConfigurationManager.AppSettings("WebDavAuthUserPass").ToString()

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'ヘッダの左領域を設定
        SetHeaderLeft(lb_user, lb_title)

        '---------------------------------------------------------------
        'HTMLタグを追加
        '---------------------------------------------------------------
        Dim ctl As Control = Page.FindControl("login_header")
        '2024/02/23 M.Okabe DEL Start
        ''JS
        'SetTagJs(ctl, "common.js")
        'SetTagJs(ctl, "jquery-1.8.3.min.js")
        'SetTagJs(ctl, "login.js")
        ''CSS
        'SetTagCss(ctl, "login.css")
        '2024/02/23 M.Okabe DEL End
        'ファビコン
        SetTagFavicon(ctl)

        '2020/6/22 ADD START モバイル版のログインページへ遷移 /Liu
        'HL_ChangeSite.NavigateUrl = HttpContext.Current.Request.ApplicationPath & "/" & "mobile/LoginSP.aspx"
        '2020/6/22 ADD END

        '操作説明マニュアルのダウンロードリンクの取得
        'SetManualDownloadLink()
    End Sub

#End Region

#Region "***************** コントロールイベント *****************"

    Protected Sub Login_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login.Authenticate
        Dim auth As Boolean = False

        Session.Clear()

        Dim LDAP_Auth_Use As String = String.Empty
        LDAP_Auth_Use = System.Configuration.ConfigurationManager.AppSettings("LDAP_Auth_Use")

        If LDAP_Auth_Use = "-1" Then
            'LDAP認証しない場合は固定のパスワードチェック
            Dim skipPassword As String = String.Empty
            skipPassword = System.Configuration.ConfigurationManager.AppSettings("SkipLDAPPassword")

            If Login.Password <> skipPassword Then
                Login.FailureText = "【管理者認証に失敗しました。】"
                Exit Sub
            Else
                auth = True
            End If
        Else

            'LDAPサーバへのアカウント認証
            'auth = Auth_LDAP(LDAP_ServerName, _
            '                    LDAP_Port, _
            '                    LDAP_Search_Scope, _
            '                    LDAP_DomainName, _
            '                    Login.UserName, _
            '                    Login.Password)

            auth = True
        End If

        If auth Then
            'ポータルへのアカウント認証
            auth = Auth_Portal(Login.UserName, Login.Password, "0")     '2014.4.28 引数追加/牧

            If auth Then

                '未リリース時はCommingSoon画面に飛ばす
                Dim releasedFlg = Com_Get_変数("PT_RELEASED_FLG")

                If releasedFlg Then
                    'トップページ呼び出し
                    Session(S_MSP_Selected_MenuCD) = Com_Get_変数("PT_TOP_NAVI")
                    Login.DestinationPageUrl = Com_Get_Content(Com_Get_変数("PT_TOP_MENU"))
                Else
                    Response.Redirect("~/ComingSoon.aspx")
                End If

            Else
                Login.FailureText = "アカウントが無効です。管理者に問い合わせてください。</br>【ポータル認証に失敗しました。】"
            End If
        Else
            Login.FailureText = "ユーザーID、パスワードを確認してください。</br>【LDAP認証に失敗しました。】"
        End If

        e.Authenticated = auth
    End Sub


    '操作説明マニュアルダウンロード
    Private Sub LinkManual_Click(sender As Object, e As EventArgs) Handles lnk_Manual.Click
        Dim filePath As String = Com_Get_変数("PT_MANUAL_PATH")
        DownloadFile(filePath)
    End Sub

    'FAQダウンロード
    Private Sub LinkFAQ_Click(sender As Object, e As EventArgs) Handles lnk_FAQ.Click
        Dim filePath As String = Com_Get_変数("PT_FAQ_PATH")
        DownloadFile(filePath)
    End Sub

    Private Sub DownloadFile(filePath As String)
        '基幹のWebDavの絶対パス
        Dim coreWebDavPath As String = Com_Get_変数("COMMON_DIRECTORY")

        '基幹の絶対パスの場合、直接参照できないので、URLパスに変換
        If filePath.StartsWith(coreWebDavPath) Then
            Dim urlWebDavPath As String = Com_Get_変数("PT_COMMON_DIRECTORY")
            filePath = filePath.Replace(coreWebDavPath, urlWebDavPath)
        End If
        ' URLの場合
        If filePath.StartsWith("http://") OrElse filePath.StartsWith("https://") Then
            DownloadFromUrl(filePath)
        Else
            DownloadLocalFile(filePath)
        End If
    End Sub

    Private Sub DownloadLocalFile(filePath As String)
        Dim fileName As String = Path.GetFileName(filePath)
        If File.Exists(filePath) Then
            Response.ContentType = "application/octet-stream"
            Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=""{0}""", fileName))
            Response.TransmitFile(filePath)
            Response.End()
        Else
            Response.Write("<script>alert('指定されたファイルが存在しません。');</script>")
        End If
    End Sub

    Private Sub DownloadFromUrl(url As String)
        Try
            ' ファイルをダウンロード
            Dim fileName As String = Path.GetFileName(url)
            ' レスポンスヘッダーを設定
            Response.Clear()
            Response.Buffer = False
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; filename=""" & fileName & """")

            Using client As New WebClient()
                ' 認証情報を設定
                Dim username As String = DBServerAuthUserId
                Dim password As String = DBServerAuthUserPass
                Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username & ":" & password))
                client.Headers("Authorization") = "Basic " & credentials
                Dim fileData As Byte() = client.DownloadData(url)

                Response.AddHeader("Content-Length", fileData.Length.ToString())
                Response.OutputStream.Write(fileData, 0, fileData.Length)

                Response.Flush()
                Response.Close()
            End Using
        Catch ex As WebException

            Dim errorResponse As HttpWebResponse = TryCast(ex.Response, HttpWebResponse)
            If errorResponse IsNot Nothing Then
                Select Case errorResponse.StatusCode
                    Case HttpStatusCode.Unauthorized
                        Response.Write("<script>alert('認証に失敗しました。ユーザーIDとパスワードを確認してください。');</script>")
                    Case HttpStatusCode.NotFound
                        Response.Write("<script>alert('指定されたファイルが見つかりません。');</script>")
                    Case Else
                        Response.Write(String.Format("<script>alert('ファイルのダウンロードに失敗しました: {0}');</script>", ex.Message))
                End Select
            Else
                Response.Write(String.Format("<script>alert('ネットワークエラーが発生しました: {0}');</script>", ex.Message))
            End If
        Catch ex As Exception
            ' その他の例外処理
            Response.Write(String.Format("<script>alert('エラーが発生しました: {0}');</script>", ex.Message))
        End Try
    End Sub

    Private Function UrlExists(url As String) As Boolean
        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
            request.Method = "HEAD"
            request.Timeout = 5000 ' 5秒のタイムアウト

            Dim username As String = DBServerAuthUserId
            Dim password As String = DBServerAuthUserPass
            Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username & ":" & password))
            request.Headers("Authorization") = "Basic " & credentials

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                Return (response.StatusCode = HttpStatusCode.OK)
            End Using

        Catch ex As WebException
            ' 404 Not Found や他のエラーの場合
            Dim errorResponse As HttpWebResponse = TryCast(ex.Response, HttpWebResponse)
            If errorResponse IsNot Nothing AndAlso errorResponse.StatusCode = HttpStatusCode.Unauthorized Then

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

#End Region

End Class