Enterprise/AuditLog.psm1
|
# Audit Log Module for MiMo CLI # Provides audit trail and logging capabilities function Write-MiMoAuditLog { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$Action, [string]$User = "", [string]$Resource = "", [hashtable]$Details = @{}, [string]$Level = "Info" ) $logEntry = @{ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Action = $Action User = $User Resource = $Resource Details = $Details Level = $Level Id = [guid]::NewGuid().ToString() } # Save to log file $logDir = "$env:USERPROFILE\.mimocode\logs" if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } $logFile = "$logDir\audit-$(Get-Date -Format 'yyyyMMdd').log" $logEntry | ConvertTo-Json -Depth 10 | Out-File -FilePath $logFile -Append -Encoding UTF8 Write-Host "Audit log: $Action" -ForegroundColor Gray return $logEntry } function Get-MiMoAuditLogs { param( [string]$Date = "", [string]$User = "", [string]$Action = "" ) $logDir = "$env:USERPROFILE\.mimocode\logs" if (-not $Date) { $Date = Get-Date -Format "yyyyMMdd" } $logFile = "$logDir\audit-$Date.log" if (Test-Path $logFile) { $logs = Get-Content -Path $logFile | ConvertFrom-Json if ($User) { $logs = $logs | Where-Object { $_.User -eq $User } } if ($Action) { $logs = $logs | Where-Object { $_.Action -eq $Action } } return $logs } else { return @() } } function Search-MiMoAuditLogs { param( [string]$Query, [string]$StartDate = "", [string]$EndDate = "" ) $logDir = "$env:USERPROFILE\.mimocode\logs" $allLogs = @() # Get all log files $logFiles = Get-ChildItem -Path $logDir -Filter "audit-*.log" -ErrorAction SilentlyContinue foreach ($logFile in $logFiles) { $logs = Get-Content -Path $logFile.FullName | ConvertFrom-Json $allLogs += $logs } # Filter by date range if ($StartDate) { $allLogs = $allLogs | Where-Object { $_.Timestamp -ge $StartDate } } if ($EndDate) { $allLogs = $allLogs | Where-Object { $_.Timestamp -le $EndDate } } # Filter by query if ($Query) { $allLogs = $allLogs | Where-Object { $_.Action -like "*$Query*" -or $_.User -like "*$Query*" -or $_.Resource -like "*$Query*" } } return $allLogs } function New-MiMoAuditReport { param( [array]$Logs, [string]$OutputPath ) $report = @" # MiMo Audit Report ## Generated: $(Get-Date) ## Summary: - Total Entries: $($Logs.Count) - Actions: $(($Logs | Group-Object Action).Count) - Users: $(($Logs | Group-Object User).Count) ## Details: $($Logs | ForEach-Object { "- [$($_.Timestamp)] $($_.Action) by $($_.User)" } | Out-String) "@ if ($OutputPath) { $report | Out-File -FilePath $OutputPath -Encoding UTF8 Write-Host "Audit report saved to: $OutputPath" } return $report } # Export functions Export-ModuleMember -Function Write-MiMoAuditLog, Get-MiMoAuditLogs, Search-MiMoAuditLogs, New-MiMoAuditReport |