' SummaryPage2_PCIDSSComplianceReportV4
Option Explicit On
Option Strict On

' #################################################################
' PCI DSS Report
'
' Version: 2.03 (05/09/2024)
'
' Usage: Run from User Security
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  09/06/2021  ISS                Created (PCI DSS v3.2.1)
'    2.00  20/04/2023  ISS      J030805   Updated to support PCI DSS v4.0
'    2.01  31/05/2023  ISS      J030829   Allow for non-Administrators
'    2.02  17/06/2024  ISS      J033480   Improve password reset checking (8.3.5)
'          17/06/2024  ISS      J033481   Fixed error with audit checks (10.2.1)
'    2.03  15/07/2024  ISS      J033857   Added Pool settings to Audit (10.2.1)
'          22/07/2024  ISS      J033914   Corrected days-since calculations (8.2.6,8.3.9)
'          23/07/2024  ISS      J033954   Updated to PCI/DSS spec v4.0.1
'          23/07/2024  ISS      J033952   Added "Reset By' column (8.3.5)
'          05/09/2024  ISS      J034121   Section now works with multiple password resets which occur on the same day (8.3.5)
'                      ISS      J033478   Add Cloud Config Session Timeout checks (8.2.8)
' #################################################################

' Objects

' Other
Private FormKey As String
Private FormPageKey As String
Private FormTabKey As String

' Constants
Private Const R3_2_1_CLOSED_DAYS As Integer = 120
Private Const R3_2_1_ACCOUNT_LIMIT As Integer = 100
Private Const R8_2_6_INACTIVE_DAYS As Integer = 90
Private Const R8_2_8_AUTOLOCK_IDLE_MINUTES As Integer = 15
Private Const R8_3_4_LOGIN_ATTEMPTS As Integer = 10
Private Const R8_3_4_LOCKOUT_MINUTES As Integer = 30
Private Const R8_3_6_PASSWORD_MINIMUM_LENGTH As Integer = 12
Private Const R8_3_7_PASSWORD_HISTORY As Integer = 4
Private Const R8_3_9_PASSWORD_CHANGE_DAYS As Integer = 90

Public Function Main(source As Object, eventId As String, eventArgs As ISKeyValueList, ByRef handled As Boolean, ByRef returnValues As ISKeyValueList, ByRef text As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Form Information
  FormKey = ScriptInfo.FormKey
  FormPageKey = ScriptInfo.FormPageKey
  FormTabKey = ScriptInfo.FormTabKey

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main Event, i.e., Return main page content
      Main = GetPage(text)
  End Select

End Function

Public Function GetPage(ByRef html As String) As Boolean

  Dim ApplicationShortcut As ISApplicationShortcut
  Dim HeadingStyle As isefinSummaryPageBlockHeadingStyle
  Dim Ok As Boolean
  Dim PortalRO As finPortalRO
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Ok = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Build Application Shortcut to PCI DSS Website
  ApplicationShortcut = finBL.CreateApplicationShortcutExternal("https://www.pcisecuritystandards.org/")

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("PCIReport", isefinSummaryPageStyle.Document)
    .HtmlHeaderEnd()
  End With

  ' Heading
  sb.AppendH1(finBL.AppTitle & " PCI DSS Compliance Report")
  sb.AppendLine(String.Format("<p>Printed on {0}</p>", finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
  sb.AppendLine("<p>Generated in accordance with version 4.0.1 of the standards and only includes sections relevant to " & finBL.AppTitle & " and its configuration which can be determined automatically.</p>")
  sb.AppendLine("<p>For more information on the Payment Card Industry (PCI) Data Security Standard (DSS) see the PCI Security Standards website <a href='" & ApplicationShortcut.ToUrlString(True) & "'>www.pcisecuritystandards.org</a>.</p>")
  sb.AppendLine("<div style='background-color:#E7F3FD;border-radius:8px;padding:8px;margin-bottom:16px;'><h3 style='margin:0;'>Disclaimer</h3><p style='margin-bottom:0px; margin:0'>This report is provided without warranty of any kind, and Intersoft accepts no liability for any decisions made on the basis of this Report. You should seek your own advice on PCI DSS compliance.</p></div>")

  ' Columns
  sb.SectionColumnsBegin("100%")
  sb.ColumnBegin("100%")

  ' 3.2.1
  ' NOTE: Temporarily removed until J030898 has been completed
'    SummaryTables = GetSection_3_2_1(HeadingStyle)
'    sb.BlockBegin("Section 3.2.1", String.Format("Accounts should have Banking Information removed within {0} days of being Closed or being left Unopened.", R3_2_1_CLOSED_DAYS), HeadingStyle, True)
'    sb.SummaryTablesAppend(SummaryTables)
'    sb.BlockEnd()
  
  ' 3.4.1
  SummaryTables = GetSection_3_4_1(HeadingStyle)
  sb.BlockBegin("Section 3.4.1", "Unmasked viewing of Banking Information.", HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 7.2.6
  SummaryTables = GetSection_7_2_6(HeadingStyle)
  sb.BlockBegin("Section 7.2.6", "Only database Administrators should have access to directly query the Database.", HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.1.2
  SummaryTables = GetSection_8_1_2(HeadingStyle)
  sb.BlockBegin("Section 8.1.2", "Users have been assigned at least one Role.", HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()

  ' 8.2.6
  SummaryTables = GetSection_8_2_6(HeadingStyle)
  sb.BlockBegin("Section 8.2.6", String.Format("Remove / Disable inactive User accounts within {0} days.", R8_2_6_INACTIVE_DAYS), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.2.7
  If finBL.Settings.AddOns.ExternalParty Then
    SummaryTables = GetSection_8_2_7(HeadingStyle)
    sb.BlockBegin("Section 8.2.7", String.Format("External User access to {0}.", finBL.AppTitle), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If
  
  ' 8.2.8
  SummaryTables = GetSection_8_2_8(HeadingStyle)
  sb.BlockBegin("Section 8.2.8", String.Format("Automatically lock {0} if left idle for {1} minutes.", finBL.AppTitle, R8_2_8_AUTOLOCK_IDLE_MINUTES), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.4.a
  SummaryTables = GetSection_8_3_4_a(HeadingStyle)
  sb.BlockBegin("Section 8.3.4.a", String.Format("Lock Users out after {0} failed login attempts.", R8_3_4_LOGIN_ATTEMPTS), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.4.b
  SummaryTables = GetSection_8_3_4_b(HeadingStyle)
  sb.BlockBegin("Section 8.3.4.b", String.Format("Lock Users out for a minimum of {0} minutes after {1} failed login attempts.", R8_3_4_LOCKOUT_MINUTES, R8_3_4_LOGIN_ATTEMPTS), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()

  ' 8.3.5
  SummaryTables = GetSection_8_3_5(HeadingStyle)
  sb.BlockBegin("Section 8.3.5", "First-time use and reset passwords must be changed after first login.", HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.6
  SummaryTables = GetSection_8_3_6(HeadingStyle)
  sb.BlockBegin("Section 8.3.6", String.Format("Minimum Password length must be at least {0} characters and must contain both numeric and alphabetic characters.", R8_3_6_PASSWORD_MINIMUM_LENGTH), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.7
  SummaryTables = GetSection_8_3_7(HeadingStyle)
  sb.BlockBegin("Section 8.3.7", String.Format("The last {0} Passwords cannot be reused.", R8_3_7_PASSWORD_HISTORY), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.9 (Users)
  SummaryTables = GetSection_8_3_9(HeadingStyle)
  sb.BlockBegin("Section 8.3.9 (Users)", String.Format("Passwords should be changed at least once every {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.9 (User Policies)
  SummaryTables = GetSection_8_3_9_UserPolicy(HeadingStyle)
  sb.BlockBegin("Section 8.3.9 (User Policy)", String.Format("Passwords should expire at least once every {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS), HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' 8.3.10
  If finBL.Settings.AddOns.Portal AndAlso finBL.Portals.CountClient(True) <> 0 Then
    SummaryTables = GetSection_8_3_10(HeadingStyle)
    sb.BlockBegin("Section 8.3.10", "Clients should receive guidance on when to change their Password (via Client-based Portals)", HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If    
  
  ' 8.4.1 and 8.4.2 - finPOWER Connect Cloud
  If finBL.Settings.AddOns.WebAutomation AndAlso finBL.Settings.AddOns.WebInterface Then
    SummaryTables = GetSection_8_4_1_8_4_2(Nothing, HeadingStyle)
    sb.BlockBegin("Section 8.4.1 and 8.4.2 - finPOWER Connect Cloud", "Enforce Multi-Factor Authentication for finPOWER Connect Cloud.", HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If
  
  ' 8.4.1 and 8.4.2 - User Portals
  If finBL.Settings.AddOns.Portal AndAlso (finBL.Portals.CountUser() <> 0 OrElse finBL.Portals.CountClient() <> 0) Then
    For Each PortalRO In finBL.Portals
      If PortalRO.Active Then
        SummaryTables = GetSection_8_4_1_8_4_2(PortalRO, HeadingStyle)
        sb.BlockBegin("Section 8.4.1 and 8.4.2 - Portal", String.Format("Enforce Multi-Factor Authentication for Portal {0}, '{1}'.", PortalRO.PortalId, PortalRO.Description), HeadingStyle, True)
        sb.SummaryTablesAppend(SummaryTables)
        sb.BlockEnd()
      End If
    Next 
  End If
  
  ' 10.2.1
  SummaryTables = GetSection_10_2_1(HeadingStyle)
  sb.BlockBegin("Section 10.2.1", "System Auditing", HeadingStyle, True)
  sb.SummaryTablesAppend(SummaryTables)
  sb.BlockEnd()
  
  ' Columns
  sb.ColumnEnd()
  sb.SectionColumnsEnd()

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Ok

End Function

''' <summary>
'''  Section 3.2.1.
''' </summary>
Private Function GetSection_3_2_1(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables
  
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim AccountId As String
  Dim AccountsDt As DataTable
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal
  
  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  
  ' Get Accounts
  If GetSection_3_2_1_GetAccounts(R3_2_1_ACCOUNT_LIMIT, AccountsDt) Then
    If AccountsDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("3.2.1", "{{icon|ok}} No Bank Account information found on old, Closed / Quote Accounts", String.Format("All Accounts closed or Unopened for {0} days (or longer) have had banking information removed.", R3_2_1_CLOSED_DAYS))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Banking Information found on old, Closed / Quote Accounts", String.Format("The following Closed / Quote Accounts (Closed or Unopened longer than {0} days ago) still have Banking information stored.", R3_2_1_CLOSED_DAYS))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("Account")
          .Add("Name")
          .Add("Closed")
          .Add("Quoted Opening")
          .Add("Status")
          .Add("BankingDetailsType")
        End With
      End With

      ' Users
      For Each row In AccountsDt.Rows
        AccountId = finBL.Database.GetFieldString(row!AccountId)

        With SummaryTable.Rows.Add()
          With .Cells
            .AddWiki("[[app://FormShow?form=Accounts&id=" & AccountId & "|" & AccountId & "]]")
            .AddText(finBL.Database.GetFieldString(row!Name))
            
            If finBL.Database.GetFieldString(row!Status) = isefinAccountStatus.Quote.ToString() Then
              .AddText("")
              .AddDate(finBL.Database.GetFieldDate(row!DateOpened))
            Else 
              .AddDate(finBL.Database.GetFieldDate(row!DateClosed))
              .AddText("")
            End If
                        
            .AddWiki("{{icon|AccountStatus_" & finBL.Database.GetFieldString(row!Status) & "|" & finBL.Database.GetFieldString(row!StatusText) & "}}").TextAlign = iseSummaryTableCellTextAlign.Center
            .AddText(finBL.Database.GetFieldString(row!BankingDetailsType))
          End With
        End With
      Next
      
      If AccountsDt.Rows.Count = R3_2_1_ACCOUNT_LIMIT Then
        SummaryTable.TextAfter = "{{info|This list is limited to the oldest " & R3_2_1_ACCOUNT_LIMIT & " Accounts. After removing details for the Accounts listed above, please rerun this report to get the next batch.}}"
      End If      
      
      SummaryTables.Add("321_Accounts", SummaryTable)
    End If
  Else
    ' Ignore error
  End If
  
  Return SummaryTables
  
End Function

''' <summary>
'''  Retrieve Accounts which have been closed (or unopened) for XX days but still have Banking information attached.
''' </summary>
Private Function GetSection_3_2_1_GetAccounts(loadFullDetailRowCount As Integer,
                                              ByRef accounts As DataTable) As Boolean
  
  Dim Account As finAccount                                               
  Dim CountRowsAdded As Integer
  Dim dt As DataTable
  Dim row As DataRow
  Dim sqb As ISSelectQueryBuilder
  Dim strTemp As String
  Dim strTemp2 As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accounts = New DataTable()
  
  ' Initialise
  Account = finBL.CreateAccount()  
  sqb = finBL.Database.CreateSelectQueryBuilder()
  
  ' DataTable Columns
  With accounts.Columns
    .Add("AccountId")
    .Add("Name", GetType(String))
    .Add("DateClosed", GetType(Date))
    .Add("DateOpened", GetType(Date))
    .Add("Status", GetType(String))
    .Add("StatusText", GetType(String))
    .Add("BankingDetailsType", GetType(String))
  End With
  
  ' Build Query
  With sqb
    .Table = "Account"
    .Fields.Add("Account.AccountId")
    
    ' SQL Where
    With .SqlWhere
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
          .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Closed))
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Declined))
            .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Unwanted))
          .BlockEnd()      
          .AppendComparisonDate("Account.DateClosed", "<=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-R3_2_1_CLOSED_DAYS), False)
        .BlockEnd()
        
        .BlockBegin(iseSqlWhereBuilderNestedBlockType.AndBlock)
          .AppendComparisonInteger("Account.Status", "=", CInt(isefinAccountStatus.Quote))
          .AppendComparisonDate("Account.DateOpened", "<=", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-R3_2_1_CLOSED_DAYS), False)
        .BlockEnd()
      .BlockEnd()
      
      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonNotNull("Account.BankingDetails1")
      .AppendComparisonNotNull("Account.BankingDetails2")
      .AppendComparisonNotNull("Account.BankingDetails3")
      .AppendComparisonNotNull("Account.BankingDetails4")      
      .BlockEnd()
    End With
    
    ' Order By
    With .OrderByFields
      .Add("Account.DateClosed")
      .Add("Account.DateOpened")
      .Add("Account.AccountId")
    End With
  End With
  
  ' Get Results
  If sqb.ExecuteDataTable(dt) Then
    CountRowsAdded = 0
    
    ' Get Banking Details
    For Each row In dt.Rows
      strTemp = ""
      
      If Account.Load(finBL.Database.GetFieldString(row!AccountId)) Then
        ' Determine which Banking Details are used
        If GetSection_3_2_1_GetAccounts_HasStoredBankingDetails(Account, isefinAccountBankingDetailsType.Incoming) Then
          strTemp = finBL.Runtime.TextUtilities.ListSeparate(vbNewLine, strTemp, "Incoming: " & Account.BankingDetails(isefinAccountBankingDetailsType.Incoming).BankingDetails.PaymentTypeCategoryDescription)
        End If
        If GetSection_3_2_1_GetAccounts_HasStoredBankingDetails(Account, isefinAccountBankingDetailsType.Outgoing) Then
          If Account.AccountClass = isefinAccountClass.Deposit Then
            strTemp2 = "Interest Payment: "
          Else 
            strTemp2 = "Outgoing: "
          End If        
          strTemp = finBL.Runtime.TextUtilities.ListSeparate(vbNewLine, strTemp, strTemp2 & Account.BankingDetails(isefinAccountBankingDetailsType.Outgoing).BankingDetails.PaymentTypeCategoryDescription)
        End If
        If GetSection_3_2_1_GetAccounts_HasStoredBankingDetails(Account, isefinAccountBankingDetailsType.Maturity) Then
          strTemp = finBL.Runtime.TextUtilities.ListSeparate(vbNewLine, strTemp, "Maturity: " & Account.BankingDetails(isefinAccountBankingDetailsType.Maturity).BankingDetails.PaymentTypeCategoryDescription)
        End If   
      Else 
        Success = False
      End If

      ' Include?
      If Success AndAlso Len(strTemp) <> 0 Then
        ' Add Account to return collection
        CountRowsAdded += 1
        accounts.Rows.Add(Account.AccountId, Account.Name, Account.DateClosed, Account.DateOpened, Account.Status.ToString(), Account.StatusText, strTemp)
        
        ' Limit reached?
        If loadFullDetailRowCount > 0 AndAlso CountRowsAdded >= loadFullDetailRowCount Then
          Exit For
        End If
      End If       
      
      ' Exit if error
      If Not Success Then Exit For
    Next 
  Else 
    Success = False
  End If

  Return Success
  
End Function

''' <summary>
'''  Indicates if an Account has stored Banking Details for a particular type.
''' </summary>
Private Function GetSection_3_2_1_GetAccounts_HasStoredBankingDetails(account As finAccount,
                                                                      bankingDetailsType As isefinAccountBankingDetailsType) As Boolean
  
  ' Check Banking Details
  If account.BankingDetails.ExistsBankingDetailsType(bankingDetailsType) Then
    With account.BankingDetails(bankingDetailsType).BankingDetails
      If .PaymentMethodPk <> 0 Then
        Select Case .PaymentMethod.PaymentTypeCategory
          Case isefinPaymentTypeCategory.Cash, isefinPaymentTypeCategory.Cheque
            ' No Banking details stored for these types

          Case Else
            ' Assume Banking Details stored
            Return True
        End Select
      End If
    End With
  End If
                                                                      
  Return False                                                                      
                                                                      
End Function

''' <summary>
'''  Section 3.4.1.
''' </summary>
Private Function GetSection_3_4_1(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim Allowed As Boolean
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UserRO As finUserRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
  End With

  ' Find Users
  For Each UserRO In finBL.Users
    With UserRO
      If .Active AndAlso .Level <> iseUserLevel.Administrator Then
        If .PermissionAllow("Banking.ShowUnmaskedAccountDetails", Allowed) Then
          If Allowed Then
            dt.Rows.Add(.UserId, .Name)
          End If
        End If
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("3.4.1", "{{icon|ok}} No Unmasked viewing of Banking Information", "Only Administrators have access to unmasked Banking Information.")
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.WarningLow
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|Outcome_Invalid}} Unmasked viewing of Banking Information allowed", "The following 'Active' non-Administrator Users have Permission to view Banking Information unmasked.")
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Id")
        .Add("Name")
      End With
    End With

    ' Users
    For Each row In dt.Rows
      UserId = finBL.Database.GetFieldString(row!UserId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=Users&page=Effective Permissions&id=" & UserId & "|" & UserId & "]]")
        .Add(finBL.Database.GetFieldString(row!Name))
      End With
    Next

    SummaryTables.Add("341_Users", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 7.2.6.
''' </summary>
Private Function GetSection_7_2_6(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim Allowed As Boolean
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UserRO As finUserRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
  End With

  ' Find Users
  If Not finBL.IsRunningFromWeb Then
    For Each UserRO In finBL.Users
      With UserRO
        If .Active AndAlso .Level <> iseUserLevel.Administrator Then
          If .PermissionAllow("Menu.Report.QueryExecute", Allowed) Then
            If Allowed Then
              dt.Rows.Add(.UserId, .Name)
            End If
          End If
        End If
      End With
    Next
  End If  

  ' Summary
  If finBL.IsRunningFromWeb Then
    headingStyle = isefinSummaryPageBlockHeadingStyle.WarningLow
    SummaryTables.AddSummaryTableBlank("7.2.6", "{{icon|Outcome_Invalid}} Invalid Database access may be present (from finPOWER Connect Desktop)", "Could not determine if only Administrators have access to directly query the database using the 'Run Query' wizard. Please re-run this report in finPOWER Connect Desktop to determine this.")
  ElseIf dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("7.2.6", "{{icon|ok}} No Invalid Database access", "Only Administrators have access to directly query the database using the 'Run Query' wizard.")
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid Database access found", "The following 'Active' non-Administrator Users have Permission to directly query the database using the 'Run Query' wizard.")
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Id")
        .Add("Name")
      End With
    End With

    ' Users
    For Each row In dt.Rows
      UserId = finBL.Database.GetFieldString(row!UserId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=Users&page=Effective Permissions&id=" & UserId & "|" & UserId & "]]")
        .Add(finBL.Database.GetFieldString(row!Name))
      End With
    Next

    SummaryTables.Add("726_Users", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.1.2.
''' </summary>
Private Function GetSection_8_1_2(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables
  
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UsersDt As DataTable
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal
  
  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  
  ' Get Users
  If GetSection_8_1_2_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.1.2", "{{icon|ok}} No Users without a Role", "All 'Active' Users have been assigned to at least one Role")
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Users without a Role found", "The following 'Active' Users have not been assigned to a Role.")
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        UserId = finBL.Database.GetFieldString(row!UserId)

        With SummaryTable.Rows.Add()
          With .Cells
            .AddWiki("[[app://FormShow?form=Users&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))            
          End With
        End With
      Next

      SummaryTables.Add("812_Users", SummaryTable)
    End If
  Else
    ' Ignore error
  End If
  
  Return SummaryTables
  
End Function

''' <summary>
'''  Retrieve Users which are not assigned to a User Role
''' </summary>
''' <returns></returns>
Private Function GetSection_8_1_2_GetUsers(ByRef users As DataTable) As Boolean
  
  Dim Success As Boolean
  Dim sqb As ISSelectQueryBuilder
  Dim sqbSub As ISSelectQueryBuilder

  ' Assume Success
  Success = True

  ' Initialise
  sqb = finBL.Database.CreateSelectQueryBuilder()
  sqbSub = finBL.Database.CreateSelectQueryBuilder()
  
  ' Build Sub Query
  With sqbSub
    .Table = "RoleUser"
    .Fields.Add("RoleUser.Pk")
    
    ' SQL Where
    With .SqlWhere
      .AppendComparisonField("User.Pk", "=", "RoleUser.UserPk")
    End With
  End With
  
  ' Build Query
  With sqb
    .Table = "User"
    .Fields.AddList("User.UserId,User.Name")
    
    ' SQL Where
    With .SqlWhere
      .AppendNotExists(sqbSub)
      .AppendComparisonIntegerBoolean("User.Active", "=", True)
      .AppendComparisonIntegerBoolean("User.Deleted", "=", False)
    End With
    
    ' Order By
    With .OrderByFields
      .Add("User.UserId")
    End With
  End With
  
  ' Get Results
  Success = sqb.ExecuteDataTable(users)

  Return Success
  
End Function

''' <summary>
'''  Section 8.2.6.
''' </summary>
Private Function GetSection_8_2_6(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim LastLogin As String
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UsersDt As DataTable

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Users
  If GetSection_8_2_6_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.2.6", "{{icon|ok}} No Inactive Users", String.Format("All 'Active' Users have logged in at least once within the last {0} days.", R8_2_6_INACTIVE_DAYS))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Inactive Users found", String.Format("The following 'Active' Users have not logged in during the last {0} days.", R8_2_6_INACTIVE_DAYS))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Last Login")
          .Add("Days ago")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        LastLogin = finBL.Database.GetFieldString(row!LastLogin)
        UserId = finBL.Database.GetFieldString(row!UserId)

        With SummaryTable.Rows.Add()
          If LastLogin = "Never" Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))
            .AddText(LastLogin).TextAlign = iseSummaryTableCellTextAlign.Right
            .AddInteger(finBL.Database.GetFieldInteger(row!DaysSince), True).TextAlign = iseSummaryTableCellTextAlign.Right
          End With
        End With
      Next

      SummaryTables.Add("826_Users", SummaryTable)
    End If
  Else
    ' Ignore error
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Retrieve List of Active Users without any login for the last 90 days
''' </summary>
Private Function GetSection_8_2_6_GetUsers(ByRef users As DataTable) As Boolean

  Dim DateToday As Date
  Dim LastLoginDate As Date
  Dim Success As Boolean
  Dim UserRO As finUserRO

  ' Assume Success
  Success = True

  ' Initialise
  users = New DataTable()

  ' Setup DataTable
  With users.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
    .Add("LastLogin", GetType(String))
    .Add("DaysSince", GetType(Integer))
  End With

  ' Today
  DateToday = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()

  ' Get Users
  For Each UserRO In finBL.Users
    With UserRO
      If .Active AndAlso Not .Deleted Then
        If .GetLastLoginDate(LastLoginDate) Then
          If LastLoginDate = Nothing Then
            users.Rows.Add(.UserId, .Name, "Never", 0)
          ElseIf DateDiff(DateInterval.Day, LastLoginDate, DateToday) >= R8_2_6_INACTIVE_DAYS Then
            users.Rows.Add(.UserId, .Name, finBL.FormatDateLong(LastLoginDate), CInt(DateDiff(DateInterval.Day, LastLoginDate, DateToday)))
          End If
        Else
          Success = False
        End If
      End If
    End With

    ' Exit if error
    If Not Success Then Exit For
  Next

  ' Sort
  If Success Then
    users.DefaultView.Sort = "LastLogin ASC"
    users = users.DefaultView.ToTable()
  End If

  Return Success

End Function

''' <summary>
'''  Section 8.2.7.
''' </summary>
Private Function GetSection_8_2_7(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim LastLogin As String
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UsersDt As DataTable
  Dim ExternalPartyId As String
  Dim Description As String

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Users
  If GetSection_8_2_7_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.2.7", "{{icon|ok}} No External Users", "There are no Active External Users configured in this database.")
    Else            
      headingStyle = isefinSummaryPageBlockHeadingStyle.WarningLow
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|Outcome_Invalid}} External Users found", "Active External Users are configured in this database.")
      SummaryTable.TableClass = iseSummaryTableClass.TabularData
      
      Description = "These Users should be reviewed regularly to ensure they are:" & vbNewLine
      Description &= " - Enabled only during the time period needed and disabled when not in use." & vbNewLine
      Description &= " - Use is monitored for unexpected activity."
      SummaryTable.TextAfter = "{{info|" & Description & "}}"
      
      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Last Login")
          .Add("Days ago")
          .Add("External Party")
          .Add("External Party Description")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        LastLogin = finBL.Database.GetFieldString(row!LastLogin)
        UserId = finBL.Database.GetFieldString(row!UserId)
        ExternalPartyId = finBL.Database.GetFieldString(row!ExternalPartyId)

        With SummaryTable.Rows.Add()
          If LastLogin = "Never" Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))
            .AddText(LastLogin).TextAlign = iseSummaryTableCellTextAlign.Right
            .AddInteger(finBL.Database.GetFieldInteger(row!DaysSince), True).TextAlign = iseSummaryTableCellTextAlign.Right
            .AddWiki("[[app://FormShow?form=ExternalParties&id=" & ExternalPartyId & "|" & ExternalPartyId & "]]")
            .AddText(finBL.ExternalParties(ExternalPartyId).Description)
          End With
        End With
      Next

      SummaryTables.Add("827_Users", SummaryTable)
    End If
  Else
    ' Ignore error
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Retrieve List of Active External Users.
''' </summary>
Private Function GetSection_8_2_7_GetUsers(ByRef users As DataTable) As Boolean

  Dim DateToday As Date
  Dim LastLoginDate As Date
  Dim Success As Boolean
  Dim UserRO As finUserRO

  ' Assume Success
  Success = True

  ' Initialise
  users = New DataTable()

  ' Setup DataTable
  With users.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
    .Add("LastLogin", GetType(String))
    .Add("DaysSince", GetType(Integer))
    .Add("ExternalPartyId", GetType(String))
  End With

  ' Today
  DateToday = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  ' Get Users
  For Each UserRO In finBL.Users
    With UserRO
      If .Active AndAlso Not .Deleted AndAlso .ExternalPartyEmployeePk <> 0 Then
        If .GetLastLoginDate(LastLoginDate) Then
          If LastLoginDate = Nothing Then
            users.Rows.Add(.UserId, .Name, "Never", 0, .ExternalPartyId)
          ElseIf LastLoginDate.AddDays(R8_2_6_INACTIVE_DAYS) < DateToday Then
            users.Rows.Add(.UserId, .Name, finBL.FormatDateLong(LastLoginDate), CInt(DateDiff(DateInterval.Day, LastLoginDate, DateToday)), .ExternalPartyId)
          End If
        Else
          Success = False
        End If
      End If
    End With

    ' Exit if error
    If Not Success Then Exit For
  Next

  ' Sort
  If Success Then
    users.DefaultView.Sort = "LastLogin ASC"
    users = users.DefaultView.ToTable()
  End If

  Return Success

End Function

''' <summary>
'''  Section 8.2.8.
''' </summary>
Private Function GetSection_8_2_8(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AutolockMinutes As Integer
  Dim CloudConfigMessages As ISList
  Dim dt As DataTable
  Dim row As DataRow
  Dim s As String
  Dim strTemp As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  CloudConfigMessages = finBL.Runtime.CreateList()
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("AutolockMinutes", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso (.AutoLockMinutes = 0 OrElse .AutoLockMinutes > R8_2_8_AUTOLOCK_IDLE_MINUTES) Then
        dt.Rows.Add(.UserPolicyId, .Description, .AutoLockMinutes)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.2.8", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies are using automatic application lock, and have it set to {0} minutes or less.", R8_2_8_AUTOLOCK_IDLE_MINUTES))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies are either not using automatic application lock, or have it set to longer than {0} minutes.", R8_2_8_AUTOLOCK_IDLE_MINUTES))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Auto-Lock Minutes")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      AutolockMinutes = finBL.Database.GetFieldInteger(row!AutolockMinutes)
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add()
        If AutolockMinutes = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If AutolockMinutes = 0 Then
            .AddText("Not Used").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(AutolockMinutes)
          End If
        End With
      End With
    Next

    SummaryTables.Add("828_UserPolicies", SummaryTable)
  End If

  ' Cloud Configuration
  If finBL.CloudConnectFunctions.CloudConnectSettings.SessionTimeoutMinutes > R8_2_8_AUTOLOCK_IDLE_MINUTES Then
    CloudConfigMessages.Add(String.Format("Session Timeout is set to longer than {0} minutes.", R8_2_8_AUTOLOCK_IDLE_MINUTES))
  End If
  If finBL.CloudConnectFunctions.CloudConnectSettings.MobileDeviceKeepAliveMinutes > R8_2_8_AUTOLOCK_IDLE_MINUTES Then
    CloudConfigMessages.Add(String.Format("Mobile Device keep-alive is set to longer than {0} minutes.", R8_2_8_AUTOLOCK_IDLE_MINUTES))
  End If
  
  If CloudConfigMessages.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("828_UserPolicies_CloudConfiguration", "{{icon|ok}} finPOWER Connect Cloud Configuration is valid", String.Format("Cloud Configuration Session Timeout and Mobile Device keep-alive is set to {0} minutes or less.", R8_2_8_AUTOLOCK_IDLE_MINUTES))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    
    strTemp = ""
    For Each s In CloudConfigMessages
      strTemp &= "{{warning|" & s & "}}"
    Next 
    
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid finPOWER Connect Cloud Configuration found", strTemp)
    SummaryTables.Add("828_UserPolicies_CloudConfiguration", SummaryTable)
  End If
  
  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.4.a
''' </summary>
Private Function GetSection_8_3_4_a(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AllowedLoginAttempts As Integer
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("AllowedLoginAttempts", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .LoginLockoutAttempts > R8_3_4_LOGIN_ATTEMPTS OrElse .LoginLockoutAttempts = 0 Then
        dt.Rows.Add(.UserPolicyId, .Description, .LoginLockoutAttempts)
      End If
    End With
  Next

  ' Sort
  dt.DefaultView.Sort = "AllowedLoginAttempts"
  dt = dt.DefaultView.ToTable()

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.3.4.a", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies will lockout the User after {0} (or fewer) failed login attempts.", R8_3_4_LOGIN_ATTEMPTS))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow more than {0} login attempts before locking the User out.", R8_3_4_LOGIN_ATTEMPTS))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Allowed Login Attempts")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      AllowedLoginAttempts = finBL.Database.GetFieldInteger(row!AllowedLoginAttempts)
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add()
        If AllowedLoginAttempts = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If AllowedLoginAttempts = 0 Then
            .AddText("Not Restricted").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(AllowedLoginAttempts)
          End If
        End With
      End With
    Next

    SummaryTables.Add("834a_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.4.b
''' </summary>
Private Function GetSection_8_3_4_b(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim LockoutMinutes As Integer
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("LockoutMinutes", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .LoginLockoutMinutes < R8_3_4_LOCKOUT_MINUTES Then
        dt.Rows.Add(.UserPolicyId, .Description, .LoginLockoutMinutes)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.3.4.b", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies have a minimum lockout period of at least {0} minutes.", R8_3_4_LOCKOUT_MINUTES))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow a lockout period of less than {0} minutes.", R8_3_4_LOCKOUT_MINUTES))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Lockout Minutes")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)
      LockoutMinutes = finBL.Database.GetFieldInteger(row!LockoutMinutes)

      With SummaryTable.Rows.Add()
        If LockoutMinutes = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If LockoutMinutes = 0 Then
            .AddText("Not Used").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(LockoutMinutes)
          End If
        End With
      End With
    Next

    SummaryTables.Add("834b_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.5.
''' </summary>
Private Function GetSection_8_3_5(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UsersDt As DataTable
  Dim LastPasswordReset As Date
  Dim LastPasswordResetUserId As String
  Dim UserId As String
  Dim row As DataRow

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Get Users
  If GetSection_8_3_5_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.3.5", "{{icon|ok}} No Password changes required", "All 'Active' Users have valid Passwords which have been changed since an Administrator reset them.")
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Password changes required", "The following 'Active' Users have Passwords which have not been updated since an Administrator has reset them.")
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Last Login")
          .Add("Last Password Reset")
          .Add("Reset by")
          .Add("Force Change")
          .Add("Details")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        UserId = finBL.Database.GetFieldString(row!UserId)
        LastPasswordReset = finBL.Database.GetFieldDate(row!LastPasswordReset)
        LastPasswordResetUserId = finBL.Database.GetFieldString(row!LastPasswordResetUserId)

        With SummaryTable.Rows.Add()
          If LastPasswordReset = Nothing Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))
            .AddDate(finBL.Database.GetFieldDate(row!LastLogin))
            .AddDate(LastPasswordReset)
            If String.IsNullOrEmpty(LastPasswordResetUserId) Then
              .AddText("")
            Else
              .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & LastPasswordResetUserId & "|" & LastPasswordResetUserId & "]]")
            End If
            .AddTick(finBL.Database.GetFieldIntegerBoolean(row!ForcePasswordChange), True, True)
            .AddText(finBL.Database.GetFieldString(row!Details))
          End With
        End With
      Next

      SummaryTables.Add("835_Users", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

Private Function GetSection_8_3_5_GetUsers(ByRef users As DataTable) As Boolean

  Dim AdminPasswordChangeDate As Date
  Dim AdminPasswordChangeUser As String
  Dim AuditLogs As DataTable
  Dim AuditLogType As iseAuditLogType
  Dim LastLoginDate As Date
  Dim LastPasswordResetDate As Date
  Dim PasswordChangedByAdmin As Boolean
  Dim PasswordChangedByUser As Boolean
  Dim Row As DataRow
  Dim Success As Boolean
  Dim User As finUser
  Dim UserMatch As Boolean
  Dim UserRO As finUserRO
  Dim Warning As String
  
  ' Assume Success
  Success = True

  ' Initialise
  users = New DataTable()
  User = finBL.CreateUser()

  ' Setup DataTable
  With users.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
    .Add("LastLogin", GetType(Date))
    .Add("LastPasswordReset", GetType(Date))
    .Add("LastPasswordResetUserId", GetType(String))
    .Add("ForcePasswordChange", GetType(Boolean))
    .Add("Details", GetType(String))
  End With

  ' Find all Users with Admin password changes not flagged for immediate change
  For Each UserRO In finBL.Users
    ' Reset
    AdminPasswordChangeDate = Nothing
    AdminPasswordChangeUser = ""
    LastLoginDate = Nothing
    PasswordChangedByAdmin = False
    PasswordChangedByUser = False
    'UserLoggedIn = False
    Warning = ""
    
    If UserRO.Active AndAlso Not UserRO.Deleted Then
      ' Get Audit
      Success = GetSection_8_3_5_GetAuditForUser(UserRO.Pk, AuditLogs)

      If Success Then
        ' Load User object
        Success = User.Load(UserRo.UserId)
        
        If Success Then
          ' The last time the User logged in
          LastLoginDate = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(User.LastLoginUtcDate)
          If LastLoginDate = Nothing Then
            Warning = "User has never logged in."
          End If
              
          ' The last time the password was changed by the User or by an admin
          LastPasswordResetDate = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(User.PasswordUtcDate)
          
          For Each Row In AuditLogs.Rows
            AuditLogType = DirectCast(finBL.Database.GetFieldEnum(Row!AuditLogType, GetType(iseAuditLogType)), iseAuditLogType)

            ' Does the Audit Log User match the Source User? This determines if the Password was changed by the User themselves, or someone else
            UserMatch = StrComp(finBL.Users.ItemByPkSafe(finBL.Database.GetFieldInteger(Row!UserPk)).UserId, finBL.Database.GetFieldString(Row!SourceId), CompareMethod.Text) = 0
            
            ' Password was changed by another user, i.e. An Administrator has updated the password
            If AuditLogType = iseAuditLogType.UserPasswordChanged AndAlso Not UserMatch Then
              PasswordChangedByAdmin = True
              PasswordChangedByUser = False
              AdminPasswordChangeDate = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(finBL.Database.GetFieldUtcDate(Row!UtcDate))
              AdminPasswordChangeUser = finBL.Users.ItemByPkSafe(finBL.Database.GetFieldInteger(Row!UserPk)).UserId                          
            End If

            ' Check that the User has updated their password since an Admin changed it
            If AuditLogType = iseAuditLogType.UserPasswordChanged AndAlso UserMatch Then
              PasswordChangedByUser = True
              PasswordChangedByAdmin = False
            End If
          Next
          
          If PasswordChangedByAdmin AndAlso Not PasswordChangedByUser Then
            If LastLoginDate > AdminPasswordChangeDate Then
              Warning = "User has not changed their password, but has logged in since an Administrator had reset their password."
            Else
              Warning = "User has not changed their password, nor logged in since an Administrator had reset their password."
            End If
          End If
        End If
  
        ' Add to collection
        If Success AndAlso Not String.IsNullOrEmpty(Warning) Then
          users.Rows.Add(UserRO.UserId, UserRO.Name, LastLoginDate, AdminPasswordChangeDate, AdminPasswordChangeUser, UserRO.PasswordForceChange, Warning)
        End If
      End If
    End If

    ' Exit if error
    If Not Success Then Exit For
  Next

  Return Success

End Function

Private Function GetSection_8_3_5_GetAuditForUser(sourcePk As Integer,
                                                  ByRef dt As DataTable) As Boolean

  Dim Success As Boolean
  Dim sqb As ISSelectQueryBuilder

  ' Assume Success
  Success = True

  ' Initialise
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Initialise ByRef Parameters
  dt = Nothing

  ' Build Query
  With sqb
    .Table = "ISAuditLog"
    .Fields.AddList("AuditLogType,UtcDate,UserPk,SourceId")

    ' SQL Where
    With .SqlWhere
      .AppendComparisonInteger("SourcePk", "=", sourcePk)
      .AppendComparisonInteger("AuditLogClass", "=", iseAuditLogClass.Security)

      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonInteger("AuditLogType", "=", iseAuditLogType.UserLogin)
      .AppendComparisonInteger("AuditLogType", "=", iseAuditLogType.UserPasswordChanged)
      .BlockEnd()
    End With

    ' Order By
    .OrderByFields.Add("Pk", False)
  End With

  ' Execute
  Success = sqb.ExecuteDataTable(dt)

  Return Success

End Function

''' <summary>
'''  Section 8.3.6.
''' </summary>
Private Function GetSection_8_3_6(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("MinimumPasswordLength", GetType(Integer))
    .Add("ForceStrongPasswords", GetType(Boolean))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso (.PasswordMinLength < R8_3_6_PASSWORD_MINIMUM_LENGTH OrElse Not .PasswordStrong) Then
        dt.Rows.Add(.UserPolicyId, .Description, .PasswordMinLength, .PasswordStrong)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.3.6", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies have a minimum Password length of {0} (or more) and are enforcing strong passwords.", R8_3_6_PASSWORD_MINIMUM_LENGTH))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies have a minimum Password length less than {0} characters, or do not enforce strong passwords.", R8_3_6_PASSWORD_MINIMUM_LENGTH))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Minimum Length")
        .Add("Enforcing Strong?")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
        .Add(finBL.Database.GetFieldString(row!Description))
        .AddInteger(finBL.Database.GetFieldInteger(row!MinimumPasswordLength))
        .AddTick(finBL.Database.GetFieldIntegerBoolean(row!ForceStrongPasswords), True, True)
      End With
    Next

    SummaryTables.Add("836_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.7.
''' </summary>
Private Function GetSection_8_3_7(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("PasswordReuse", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .PasswordHistoryLength < R8_3_7_PASSWORD_HISTORY Then
        dt.Rows.Add(.UserPolicyId, .Description, .PasswordHistoryLength)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.3.7", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies do not allow the last {0} Passwords to be reused.", R8_3_7_PASSWORD_HISTORY))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow less than the last {0} Passwords to be reused.", R8_3_7_PASSWORD_HISTORY))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Password History")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
        .Add(finBL.Database.GetFieldString(row!Description))
        .AddInteger(finBL.Database.GetFieldInteger(row!PasswordReuse))
      End With
    Next

    SummaryTables.Add("837_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.9.
''' </summary>
Private Function GetSection_8_3_9(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim DateToday As Date
  Dim DaysSinceChange As Integer
  Dim dt As DataTable
  Dim PasswordUtcDate As Date
  Dim row As DataRow
  Dim sqb As ISSelectQueryBuilder
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UserLevel As String

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Build Query
  With sqb
    .Table = "User"
    .Fields.AddList("UserId,PasswordUtcDate")

    ' SQL Where
    With .SqlWhere
      .AppendComparisonIntegerBoolean("Active", "=", True)
      .AppendComparisonIntegerBoolean("Deleted", "=", False)
      .AppendComparisonDate("PasswordUtcDate", "<", finBL.TimeZoneFunctions.GetCurrentUtcDateTime().AddDays(-R8_3_9_PASSWORD_CHANGE_DAYS), False)
    End With

    ' Order By
    With .OrderByFields
      .Add("PasswordUtcDate")
    End With
  End With

  ' Execute
  If sqb.ExecuteDataTable(dt) Then
    If dt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.3.9", "{{icon|ok}} No old Passwords", String.Format("All 'Active' Users have had their Passwords changed within the last {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Old Passwords found", String.Format("The following 'Active' Users have not changed their Password in over {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Level")
          .Add("Days since Password change")
        End With
      End With

      ' Current date+time
      DateToday = finBL.TimeZoneFunctions.GetCurrentDatabaseDateTime()
      
      ' Users
      For Each row In dt.Rows
        UserId = finBL.Database.GetFieldString(row!UserId)

        ' User Level
        Select Case finBL.Users(UserId).Level
          Case iseUserLevel.Administrator: UserLevel = "Administrator"
          Case iseUserLevel.UserAdministrator: UserLevel = "User Administrator"
          Case Else: UserLevel = ""
        End Select

        ' Get Days since Password change
        PasswordUtcDate = finBL.Database.GetFieldUtcDate(row!PasswordUtcDate)
        DaysSinceChange = CInt(DateDiff(DateInterval.Day, finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(PasswordUtcDate), DateToday))

        With SummaryTable.Rows.Add()
          If Len(UserLevel) <> 0 Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .AddText(finBL.Users(UserId).Name)
            .AddText(UserLevel)
            .AddInteger(DaysSinceChange)
          End With
        End With
      Next

      SummaryTables.Add("839_Users", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.3.9 User Policy.
''' </summary>
Private Function GetSection_8_3_9_UserPolicy(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO
  Dim PasswordMaxAge As Integer
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("PasswordMaxAge", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso (.PasswordMaxAgeDays > R8_3_9_PASSWORD_CHANGE_DAYS OrElse .PasswordMaxAgeDays = 0) Then
        dt.Rows.Add(.UserPolicyId, .Description, .PasswordMaxAgeDays)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.3.9", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies expire passwords within {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies do not expire Passwords within {0} days.", R8_3_9_PASSWORD_CHANGE_DAYS))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Password Expiry Days")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)
      PasswordMaxAge = finBL.Database.GetFieldInteger(row!PasswordMaxAge)

      With SummaryTable.Rows.Add()
        If PasswordMaxAge = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If
        
        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))
          
          If PasswordMaxAge = 0 Then
            .AddText("Not Used").TextAlign = iseSummaryTableCellTextAlign.Right
          Else 
            .AddInteger(PasswordMaxAge)
          End If    
        End With
      End With
    Next

    SummaryTables.Add("839_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function


''' <summary>
'''  Section 8.3.10.
''' </summary>
Private Function GetSection_8_3_10(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim PortalId As String
  Dim PortalRO As finPortalRO
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("PortalId", GetType(String))
    .Add("Description", GetType(String))
  End With

  ' Determine Portals which do not meet the critieria
  For Each PortalRO In finBL.Portals
    With PortalRO
      If .Active AndAlso Not .EnforcePasswordChange Then
        dt.Rows.Add(.PortalId, .Description)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTable = SummaryTables.AddSummaryTableBlank("8.3.10", "{{icon|ok}} No Invalid Client Portals", "All 'Active' Client Portals will enforce Password changes if configured on the Client.")
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid Client Portals found", "The following 'Active' Client Portals do not enforce Password changes, even if configured on the Client.")
    SummaryTable.TableClass = iseSummaryTableClass.TabularData    
    
    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("Portal Id")
        .Add("Description")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      PortalId = finBL.Database.GetFieldString(row!PortalId)      

      With SummaryTable.Rows.Add()
        With .Cells
          .AddWiki("[[app://FormShow?form=Portals&page=security&id=" & PortalId & "|" & PortalId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))   
        End With
      End With
    Next
        
    SummaryTables.Add("8310_Portals", SummaryTable)
  End If

  SummaryTable.TextAfter = "{{info|NOTE: Client Portals do not automatically set Password expiry periods. Ensuring that a suitable passport validity period is set must be either handled manually or specifically coded into the Portal.}}"
  
  Return SummaryTables

End Function

''' <summary>
'''  Section 8.4.1 and 8.4.2.
''' </summary>
Private Function GetSection_8_4_1_8_4_2(portalRO As finPortalRO,
                                        ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AuthMethod As isefinMultiFactorAuthenticationMethod
  Dim AuthMethodText As String
  Dim Count As Integer
  Dim DeferDays As Integer
  Dim ExcludedRoles As String
  Dim Found As Boolean
  Dim Level As String
  Dim List As ISList
  Dim Role As ISRole
  Dim RoleId As String
  Dim RoleUser As ISRoleUser
  Dim strTemp As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTableId As String
  Dim SummaryTables As ISSummaryTables
  Dim SummaryTableUsers As ISSummaryTable
  Dim Title As String
  Dim UserList As ISCodeDescriptionList
  Dim UserListItem As ISCodeDescriptionListItem
  Dim DeferDaysText As String

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  Role = finBL.CreateRole()
  SummaryTables = finBL.CreateSummaryTables()
  UserList = finBL.Runtime.CreateCodeDescriptionList()

  ' Determine Rules
  If portalRO Is Nothing Then
    With finBL.CloudConnectFunctions.CloudConnectSettings
      Title = "finPOWER Connect Cloud"
      SummaryTableId = "841_842_finCC"
      AuthMethod = .TwoFactorAuthenticationMethod
      AuthMethodText = .TwoFactorAuthenticationMethodText
      ExcludedRoles = .TwoFactorAuthenticationRolesExclude
      DeferDays = .TwoFactorAuthenticationDeferDays
    End With
  Else 
    With portalRO
      Title = String.Format("Portal {0}, '{1}'", portalRO.PortalId, portalRO.Description)
      SummaryTableId = "841_842_" & portalRO.PortalId
      AuthMethod = .MultiFactorAuthenticationMethod
      AuthMethodText = .MultiFactorAuthenticationMethodText
      ExcludedRoles = .MultiFactorAuthenticationRolesExclude
      DeferDays = .MultiFactorAuthenticationDeferDays
    End With
  End If

  ' Defer Days?
  If DeferDays <> 0 Then
    If DeferDays = 1 Then
      strTemp = ""
    Else 
      strTemp = "s"
    End If
    DeferDaysText = String.Format("NOTE: Multi-Factor Authentication is allowing deferring up to {0} day{1}. This reduces the effectiveness of Multi-Factor Authentication.", DeferDays, strTemp)
  End If
  
  ' Summary
  If AuthMethod = isefinMultiFactorAuthenticationMethod.None Then
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTables.AddSummaryTableBlank("8.4.1 and 8.4.2", "{{icon|cross}} Invalid " & Title & " Settings found", String.Format("This database is configured for {0} access, but does not enforce Multi-Factor Authentication.", Title))
  Else
    If Len(ExcludedRoles) = 0 Then
      If DeferDays = 0 Then
        SummaryTables.AddSummaryTableBlank("8.4.1 and 8.4.2", "{{icon|ok}} " & Title & " Settings valid", String.Format("{0} is using the '{1}' method of Multi-Factor Authentication.", Title, AuthMethodText))
      Else 
        headingStyle = isefinSummaryPageBlockHeadingStyle.WarningLow
        SummaryTable = SummaryTables.AddSummaryTableBlank("8.4.1 and 8.4.2", "{{icon|Outcome_Invalid}} " & Title & " Settings may require attention", String.Format("{0} is using the '{1}' method of Multi-Factor Authentication.", Title, AuthMethodText))
        SummaryTable.TextAfter = "{{warning|" & DeferDaysText & "}}"
      End If      
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid " & Title & " Settings found", String.Format("{0} is using the '{1}' method of Multi-Factor Authentication, however the following User Roles have been excluded.", Title, AuthMethodText))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Defer days warning?
      If DeferDays <> 0 Then
        SummaryTable.TextAfter = "{{warning|" & DeferDaysText & "}}"
      End If
      
      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("Role")
          .Add("Description")
          .Add("Active User Count")
        End With
      End With

      ' Get Roles
      List = finBL.Runtime.CreateList()
      List.FromRangeString(ExcludedRoles)

      ' Populate Summary Table
      For Each RoleId In List
        Count = 0
        
        If Role.Load(RoleId) Then
          ' Get Count of Active Users in the Role
          For Each RoleUser In Role.Users
            If RoleUser.UserActive AndAlso RoleUser.InRole AndAlso finBL.Users(RoleUser.UserId).WebAccess Then
              Count += 1
              
              ' Also add to a Users collection to be displayed
              Found = False
              For Each UserListItem In UserList
                If StrComp(UserListItem.Code, RoleUser.UserId, CompareMethod.Text) = 0 Then
                  Found = True
                  UserListItem.Description = finBL.Runtime.TextUtilities.ListSeparate(", ", UserListItem.Description, Role.RoleId)
                  Exit For
                End If
              Next
              
              If Not Found Then
                UserList.Add(RoleUser.UserId, Role.RoleId)
              End If
            End If
          Next 
          
          With SummaryTable.Rows.Add().Cells
            .AddWiki("[[app://FormShow?form=Roles&id=" & Role.RoleId & "|" & Role.RoleId & "]]")
            .AddText(Role.Description)
            .AddInteger(Count)
          End With
        End If
      Next
      
      ' Role Summary Tables
      SummaryTables.Add(SummaryTableId & "_UserRoles", SummaryTable)
      
      ' Add Users?
      If UserList.Count <> 0 Then
        ' Order by User Id
        UserList.Sort()
        
        ' Initialise
        If portalRO Is Nothing Then
          strTemp = "The below Active Users (and are configured for finPOWER Connect Cloud access) belong to the Roles listed above, and therefore are excluded from using Multi-Factor Authentication."
        Else 
          strTemp = "The below Active Users belong to the Roles listed above, and therefore are excluded from using Multi-Factor Authentication."
        End If
        SummaryTableUsers = SummaryTables.CreateSummaryTableBlank("Users", strTemp)
        SummaryTableUsers.TableClass = iseSummaryTableClass.TabularData
        
        ' Heading
        With SummaryTableUsers.Rows.Add()
          .RowClass = iseSummaryTableRowClass.Header
          With .Cells
            .Add("User")
            .Add("Name")
            .Add("Level")
            .Add("Role(s)")
          End With
        End With
        
        ' Add Users
        For Each UserListItem In UserList          
          ' Determine Level
          Select Case finBL.Users(UserListItem.Code).Level
            Case iseUserLevel.Administrator : Level = "Administrator"
            Case iseUserLevel.UserAdministrator : Level = "User Administrator"
            Case Else : Level = ""
          End Select
          
          With SummaryTableUsers.Rows.Add()
            If Len(Level) <> 0 Then
              .RowClass = iseSummaryTableRowClass.Negative
            End If
            
            With .Cells
              .AddWiki("[[app://FormShow?form=Users&id=" & UserListItem.Code & "|" & UserListItem.Code & "]]")
              .AddText(finBL.Users(UserListItem.Code).Name)
              .AddText(Level)
              .AddText(UserListItem.Description)
            End With
          End With
        Next 
        
        ' Users Summary Tables
        SummaryTables.Add(SummaryTableId & "Users", SummaryTableUsers)
      End If
    End If
  End If
  
  Return SummaryTables

End Function


''' <summary>
'''  Section 10.2.1.
''' </summary>
Private Function GetSection_10_2_1(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  
  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("AuditGroup", GetType(String))
    .Add("AuditOption", GetType(String))
    .Add("Description", GetType(String))
  End With

  ' Find any un-audited items
  GetSection_10_2_1_AuditOptionCheck("Admin", finBL.Settings.Audit.AdminAuditOptions, dt)
  If finBL.Settings.AddOns.AccountApplication Then
    GetSection_10_2_1_AuditOptionCheck("Account Applications", finBL.Settings.Audit.AccountAppAuditOptions, dt)
  End If  
  GetSection_10_2_1_AuditOptionCheck("Account", finBL.Settings.Audit.AccountAuditOptions, dt)  
  GetSection_10_2_1_AuditOptionCheck("Client", finBL.Settings.Audit.ClientAuditOptions, dt)
  If finBL.Settings.AddOns.ExternalParty Then
    GetSection_10_2_1_AuditOptionCheck("External Party", finBL.Settings.Audit.ExternalPartyAuditOptions, dt)
  End If  
  If finBL.Settings.AddOns.Pool Then
    GetSection_10_2_1_AuditOptionCheck("Pool", finBL.Settings.Audit.PoolAuditOptions, dt)
  End If  
  If finBL.Settings.AddOns.SecurityRegister Then
    GetSection_10_2_1_AuditOptionCheck("Security Statement", finBL.Settings.Audit.SecurityStmtAuditOptions, dt)
  End If  
  If finBL.Settings.AddOns.Workflow Then
    GetSection_10_2_1_AuditOptionCheck("Workflow", finBL.Settings.Audit.WorkflowAuditOptions, dt)
  End If  

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("10.2.1", "{{icon|ok}} Auditing is fully enabled", "Auditing is enabled on all system components.")
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.WarningLow
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|Outcome_Invalid}} Some items not audited", "The following system components are not currently Audited.")
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("Group")
        .Add("Option")
        .Add("Description")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      With SummaryTable.Rows.Add()        
        With .Cells
          .AddText(finBL.Database.GetFieldString(row!AuditGroup))
          .AddText(finBL.Database.GetFieldString(row!AuditOption))
          .AddText(finBL.Database.GetFieldString(row!Description))  
        End With
      End With
    Next

    SummaryTables.Add("1021_Audit", SummaryTable)
  End If

  Return SummaryTables

End Function

Private Sub GetSection_10_2_1_AuditOptionCheck(auditGroup As String,
                                               auditOptions As finAuditOptions,
                                               ByRef dt As DataTable)
  Dim AuditOption As finAuditOption                                               
                   
  ' Scan Audit Options
  For Each AuditOption In auditOptions
    With auditOption
      If .AlwaysAudit Then
        ' Always Audited
      ElseIf Not .SaveAudit Then 
        dt.Rows.Add(auditGroup, .AuditOptionId, .Description)
      End If
    End With
  Next 
  
End Sub
