Imports Microsoft.AspNet.Identity
Imports System.IO
Imports System.Threading

Public Class SiteMaster
    Inherits MasterPage
    Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
    Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
    Private _antiXsrfTokenValue As String
    Property CurrentDriver As Logic.DriverAccount
    Property CurrentPage As String

    Protected Sub Page_Init(sender As Object, e As EventArgs)
        ' The code below helps to protect against XSRF attacks
        Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
        Dim requestCookieGuidValue As Guid
        If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
            ' Use the Anti-XSRF token from the cookie
            _antiXsrfTokenValue = requestCookie.Value
            Page.ViewStateUserKey = _antiXsrfTokenValue
        Else
            ' Generate a new Anti-XSRF token and save to the cookie
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N")
            Page.ViewStateUserKey = _antiXsrfTokenValue

            Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
                 .HttpOnly = True,
                 .Value = _antiXsrfTokenValue
            }
            If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
                responseCookie.Secure = True
            End If
            Response.Cookies.[Set](responseCookie)
        End If

        Try
            If My.Settings.httpsOnly Then
                _SecurePage()
            End If

            Dim uri As New Uri(Request.Url.AbsoluteUri)
            CurrentPage = Path.GetFileName(uri.LocalPath).ToLower()

            If Not (CurrentPage = "login" Or CurrentPage = "default" Or CurrentPage = "default.aspx" Or CurrentPage = "createaccount" Or CurrentPage = "forgotpassword" Or CurrentPage = "forgotpassword_success" Or CurrentPage = "error") Then
                Dim driverId = SessionVars.DriverId(Session)
                If driverId > 0 Then
                    CurrentDriver = New Logic.DriverAccount(driverId)
                Else
                    If String.IsNullOrEmpty(SessionVars.PostLoginUrl(Session)) Then
                        SessionVars.PostLoginUrl(Session) = Request.Url.ToString()
                    End If
                    Response.Redirect("/Login.aspx")
                End If
            End If
        Catch ex As ThreadAbortException
            Throw
        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try

        AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
    End Sub

    Protected Sub master_Page_PreLoad(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            ' Set Anti-XSRF token
            ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
            ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, [String].Empty)
        Else
            ' Validate the Anti-XSRF token
            If DirectCast(ViewState(AntiXsrfTokenKey), String) <> _antiXsrfTokenValue OrElse DirectCast(ViewState(AntiXsrfUserNameKey), String) <> (If(Context.User.Identity.Name, [String].Empty)) Then
                Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
            End If
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Unnamed_LoggingOut(sender As Object, e As LoginCancelEventArgs)
        Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie)
    End Sub


    ' Make us use https
    Private Sub _SecurePage()
        Dim ServerName As String = Server.UrlEncode(Request.ServerVariables.Item("SERVER_NAME"))
        Dim FilePath As String = Request.Url.PathAndQuery
        If Not Request.IsSecureConnection Then
            Response.Redirect("https://" & ServerName & FilePath)
        End If
    End Sub
End Class