Imports System
Imports System.Web.Security
Imports System.Web.SessionState
Imports System.Threading
Imports System.Globalization
Imports System.Configuration
Imports ASPNET.StarterKit.TimeTracker.BusinessLogicLayer
Imports Microsoft.Win32

Namespace ASPNET.StarterKit.TimeTracker.Mobile
    _
    ' Global Application
    Public Class Global
        Inherits System.Web.HttpApplication
        ' Configuation constants used for retrieving application setting values from the
        ' web.config file.
        Public Const CfgKeyConnString As String = "ConnectionString"
        Public Const CfgKeyUserAcctSource As String = "UserAccountSource"
        Public Const CfgKeyDefaultRole As String = "DefaultRoleForNewUser"
        Public Const CfgKeyFirstDayOfWeek As String = "FirstDayOfWeek"

        ' Constants used to reference data stored in cookies
        Public UserRoles As String = "userroles"
        Public UserRolesMobile As String = "userrolesmobile"

        '*********************************************************************
        '
        ' Application_BeginRequest Event
        '
        ' The Application_BeginRequest method is an ASP.NET event that executes 
        ' on each web request into the mobile application.  
        '
        ' The thread culture is set for each request using the language
        ' settings specified in the browser.
        ' 
        '*********************************************************************
        Protected Sub Application_BeginRequest(ByVal sender As [Object], ByVal e As EventArgs)
            Try
                If Not (Request.UserLanguages Is Nothing) Then
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages(0))
                    ' Default to English if there are no user languages
                Else
                    Thread.CurrentThread.CurrentCulture = New CultureInfo("en-us")
                End If
                Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture
            Catch ex As Exception
                Thread.CurrentThread.CurrentCulture = New CultureInfo("en-us")
            End Try
        End Sub 'Application_BeginRequest


        '*********************************************************************
        '
        ' Application_AuthenticateRequest Event
        '
        ' If the client is authenticated with the application, then determine
        ' which security roles he/she belongs to and replace the "User" intrinsic
        ' with a custom IPrincipal security object that permits "User.IsInRole"
        ' role checks within the application
        '
        ' Roles are cached in the browser in an in-memory encrypted cookie.  If the
        ' cookie doesn't exist yet for this session, create it.
        '
        '*********************************************************************
        Protected Sub Application_AuthenticateRequest(ByVal sender As [Object], ByVal e As EventArgs)
            Dim userInformation As String = [String].Empty

            If Request.IsAuthenticated = True Then
                Dim strCookieValue As String

                If Request.Cookies(UserRolesMobile) Is Nothing Then
                    strCookieValue = ""
                Else
                    strCookieValue = Request.Cookies(UserRolesMobile).Value
                End If

                ' Create the roles cookie if it doesn't exist yet for this session.
                If strCookieValue = "" Then
                    ' Retrieve the user's role and ID information and add it to
                    ' the cookie
                    Dim usr As New TTUser(User.Identity.Name)
                    If Not usr.Load() Then
                        ' The user was not found in the Time Tracker database so add them using
                        ' the default role.  Specifying a UserID of 0 will result in the user being 
                        ' inserted into the database.
                        Dim newUser As New TTUser(0, Context.User.Identity.Name, [String].Empty, ConfigurationSettings.AppSettings(CfgKeyDefaultRole))
                        newUser.Save()
                        usr = newUser
                    End If

                    ' Create a string to persist the role and user id
                    userInformation = Convert.ToString(usr.UserID()) + ";" + usr.Role + ";" + usr.Name

                    ' Create a cookie authentication ticket.
                    Dim ticket As New FormsAuthenticationTicket(1, User.Identity.Name, DateTime.Now, DateTime.Now.AddHours(1), False, userInformation)
                    ' version
                    ' user name
                    ' issue time
                    ' expires every hour
                    ' don't persist cookie

                    ' Encrypt the ticket
                    Dim cookieStr As [String] = FormsAuthentication.Encrypt(ticket)

                    ' Send the cookie to the client
                    Response.Cookies(UserRolesMobile).Value = cookieStr
                    Response.Cookies(UserRolesMobile).Path = "/"
                    Response.Cookies(UserRolesMobile).Expires = DateTime.Now.AddMinutes(1)

                    ' Add our own custom principal to the request containing the user's identity, the user id, and
                    ' the user's role 
                    Context.User = New CustomPrincipal(User.Identity, usr.UserID, usr.Role, usr.Name)
                Else
                    ' Get roles from roles cookie
                    Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(Context.Request.Cookies(UserRolesMobile).Value)
                    userInformation = ticket.UserData

                    ' Add our own custom principal to the request containing the user's identity, the user id, and
                    ' the user's role from the auth ticket
                    Dim info As String() = userInformation.Split(New Char() {";"c})
                    Context.User = New CustomPrincipal(User.Identity, Convert.ToInt32(info(0).ToString()), info(1).ToString(), info(2).ToString())
                End If
            End If
        End Sub 'Application_AuthenticateRequest
    End Class 'Global
End Namespace 'ASPNET.StarterKit.TimeTracker.Web