### Minimal Audit Log Setup with AdminForth Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md This example shows the basic configuration required to register the AuditLogPlugin with AdminForth. Ensure your AdminForth instance and data sources are correctly configured before building. ```typescript import AuditLogPlugin from '@adminforth/audit-log'; import AdminForth from 'adminforth'; const adminforth = new AdminForth({ baseUrl: 'http://localhost:3000', dataSource: { type: 'postgres', url: 'postgres://...' }, resources: [ { resourceId: 'users', dataSourceId: 'postgres', table: 'users', columns: [ { name: 'id', type: 'int', primaryKey: true }, { name: 'email', type: 'string' }, { name: 'name', type: 'string' } ] }, { resourceId: 'audit_logs', dataSourceId: 'postgres', table: 'audit_logs', columns: [ { name: 'id', type: 'int', primaryKey: true }, { name: 'resource_id', type: 'string' }, { name: 'action', type: 'string' }, { name: 'data', type: 'json' }, { name: 'user_id', type: 'int' }, { name: 'record_id', type: 'int' }, { name: 'created_at', type: 'string' } ] } ] }); const auditLogPlugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'data', resourceUserIdColumnName: 'user_id', resourceRecordIdColumnName: 'record_id', resourceCreatedColumnName: 'created_at' } }); adminforth.registerPlugin(auditLogPlugin, { resourceId: 'audit_logs' }); await adminforth.build(); ``` -------------------------------- ### Install and Register Audit Log Plugin Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Demonstrates how to install the AuditLogPlugin and register it with the AdminForth application, including configuration options for resource columns. ```typescript import AuditLogPlugin from '@adminforth/audit-log'; import AdminForth from 'adminforth'; const adminforth = new AdminForth(config); const auditLogPlugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'data', resourceUserIdColumnName: 'user_id', resourceRecordIdColumnName: 'record_id', resourceCreatedColumnName: 'created_at' } }); adminforth.registerPlugin(auditLogPlugin, { resourceId: 'audit_logs' }); ``` -------------------------------- ### AuditLogPlugin Initialization Example Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/types.md Demonstrates how to instantiate the AuditLogPlugin with specific configuration options, including resource exclusions and custom column mappings. ```typescript import AuditLogPlugin from '@adminforth/audit-log'; const plugin = new AuditLogPlugin({ excludeResourceIds: ['temp_data', 'internal_cache'], resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action_type', resourceDataColumnName: 'changes', resourceUserIdColumnName: 'admin_id', resourceRecordIdColumnName: 'record_pk', resourceCreatedColumnName: 'created_at', resourceCountryColumnName: 'country_code', resourceIpColumnName: 'client_ip' }, isoCountryCodeRequestHeader: 'CF-IPCountry' }); ``` -------------------------------- ### AuditLogPlugin Initialization Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Illustrates the initialization process for the AuditLogPlugin, starting with instantiation and followed by registration with Adminforth. ```plaintext new AuditLogPlugin(options) ↓ adminforth.registerPlugin(plugin, { resourceId: 'audit_logs' }) ↓ plugin.modifyResourceConfig(adminforth, auditLogResource) ``` -------------------------------- ### Basic Audit Log Plugin Setup Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Initializes the Audit Log plugin with essential resource column mappings. Use this for a straightforward configuration. ```typescript import AuditLogPlugin from '@adminforth/audit-log'; const auditLogPlugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'change_data', resourceUserIdColumnName: 'user_id', resourceRecordIdColumnName: 'record_id', resourceCreatedColumnName: 'created_at' } }); ``` -------------------------------- ### Generated Audit Log URL Example Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md An example of a generated URL for filtering the audit log list, demonstrating sorting and filtering parameters. ```url /admin/audit_logs? sort=created_at__desc& filter__record_id__eq=42& filter__resource_id__eq="users" ``` -------------------------------- ### Audit Log Dependencies Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Import necessary modules for displaying audit log diffs. Ensure these dependencies are installed and configured in your project. ```typescript import { useCoreStore } from '@/stores/core'; import { DiffModeEnum, DiffView } from '@git-diff-view/vue'; import { generateDiffFile } from '@git-diff-view/file'; ``` -------------------------------- ### Geolocation Resolution Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Shows example configurations for resolving the ISO country code from HTTP headers, including Cloudflare, AWS CloudFront, and custom headers. ```typescript // Cloudflare isoCountryCodeRequestHeader: 'CF-IPCountry' // AWS CloudFront isoCountryCodeRequestHeader: 'CloudFront-Viewer-Country' // Custom header isoCountryCodeRequestHeader: 'X-Country-Code' ``` -------------------------------- ### Filter Audit Logs by Resource and Action Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Retrieve audit logs using standard AdminForth filters. This example demonstrates filtering by resource ID ('users') and action ('delete'), sorted by creation timestamp in descending order. ```typescript const logs = await adminforth.resource('audit_logs').getList({ filters: Filters.AND( Filters.EQ('resource_id', 'users'), Filters.EQ('action', 'delete') ), sort: { column: 'created_at', direction: 'desc' } }); ``` -------------------------------- ### Audit Log Record Deletion Example Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Illustrates the visual representation of a deleted audit log record, showing removed fields in red and added fields in green. ```json Left side (oldRecord): Right side (newRecord): { "id": 42, "email": "user@example.com", "name": "John Doe" } { } ``` -------------------------------- ### Configure Audit Log Resource Permissions Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Set permissions for the audit log resource to control user access. This example prevents manual creation, editing, and deletion of audit log entries, enforcing read-only access. ```typescript { resourceId: 'audit_logs', columns: [ ... ], options: { permissions: { create: { admin: false }, // Prevent manual creation edit: { admin: false }, // Read-only delete: { admin: false } // Cannot delete logs } } } ``` -------------------------------- ### Getting Admin Panel Theme Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md A computed property that retrieves the current theme ('light' or 'dark') from the core store. This is used to apply appropriate styling to the diff view. ```typescript const theme = computed(() => coreStore.theme); ``` -------------------------------- ### PostgreSQL Audit Log Schema Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Example PostgreSQL schema for the audit_logs table. Ensure column types and constraints match your application's needs. ```sql CREATE TABLE audit_logs ( id SERIAL PRIMARY KEY, resource_id VARCHAR(255) NOT NULL, action VARCHAR(50) NOT NULL, change_data JSONB NOT NULL, admin_user_id UUID NOT NULL REFERENCES users(id), record_id UUID NOT NULL, created_at VARCHAR(50) NOT NULL, country VARCHAR(2), ip_address VARCHAR(45), created_at_db TIMESTAMP DEFAULT NOW() ); CREATE INDEX idx_audit_resource ON audit_logs(resource_id); CREATE INDEX idx_audit_record ON audit_logs(record_id); CREATE INDEX idx_audit_user ON audit_logs(admin_user_id); CREATE INDEX idx_audit_created ON audit_logs(created_at DESC); ``` -------------------------------- ### AuditLogPlugin Class Methods Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/MANIFEST.txt This section details the public methods available within the AuditLogPlugin class, including their signatures, parameters, return types, and usage examples. ```APIDOC ## AuditLogPlugin Class Methods This section provides documentation for the public methods of the `AuditLogPlugin` class. ### `createLogRecord` **Description**: Creates a new log record in the audit trail. **Method**: (Assumed to be a method call within the SDK/plugin context, not an HTTP method) **Parameters**: (Details on parameters like `level`, `message`, `metadata` would be here if explicitly provided in source) ### `logCustomAction` **Description**: Logs a custom action performed by a user or system. **Method**: (Assumed to be a method call within the SDK/plugin context, not an HTTP method) **Parameters**: (Details on parameters like `actionName`, `details` would be here if explicitly provided in source) ### `getIpAndCountry` **Description**: Retrieves the IP address and country information for a given request. **Method**: (Assumed to be a method call within the SDK/plugin context, not an HTTP method) **Parameters**: (Details on parameters like `request` would be here if explicitly provided in source) ### `getClientIpCountry` **Description**: Retrieves the client's IP address and country information. **Method**: (Assumed to be a method call within the SDK/plugin context, not an HTTP method) **Parameters**: (Details on parameters like `req` would be here if explicitly provided in source) ### `modifyResourceConfig` **Description**: Modifies the configuration of a resource within the audit log system. **Method**: (Assumed to be a method call within the SDK/plugin context, not an HTTP method) **Parameters**: (Details on parameters like `resourceId`, `newConfig` would be here if explicitly provided in source) ### `PluginOptions` Interface **Description**: Defines the structure for configuring the AuditLogPlugin. **Fields**: (Details on fields like `databaseUrl`, `logLevel`, `geolocationService` would be here if explicitly provided in source) ``` -------------------------------- ### Audit Log Entry for Password Change Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md An example of an audit log entry after a user changes their password. Sensitive fields marked as backendOnly in the configuration are hidden. ```typescript { resource_id: 'users', action: 'edit', data: { oldRecord: { email: 'user@example.com', password_hash: '' }, newRecord: { email: 'user@example.com', password_hash: '' } }, user_id: 5, record_id: 10, created_at: '2026-06-29T15:00:00Z' } ``` -------------------------------- ### Initialize Audit Log Plugin with Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Demonstrates the initialization of the AuditLogPlugin, including setting up resource column mappings and registering the plugin with Adminforth. Includes error handling for the initialization process. ```typescript async function initializeAuditLog() { try { const plugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'res_id', resourceActionColumnName: 'act', resourceDataColumnName: 'diff', // Must be JSON type! resourceUserIdColumnName: 'uid', resourceRecordIdColumnName: 'rid', resourceCreatedColumnName: 'ts' } }); adminforth.registerPlugin(plugin, { resourceId: 'audit_logs' }); await adminforth.build(); console.log('Audit log initialized successfully'); } catch (error) { console.error('Failed to initialize audit log:', error.message); process.exit(1); } } ``` -------------------------------- ### constructor Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Initializes the AuditLogPlugin with provided options. ```APIDOC ## constructor(options) ### Description Initializes the AuditLogPlugin instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - Configuration options for the plugin. ### Request Example ```json { "options": { ... } } ``` ### Response #### Success Response (200) - **AuditLogPlugin instance** (object) - The initialized plugin instance. ### Response Example ```json { "instance": "AuditLogPlugin" } ``` ``` -------------------------------- ### Get Client IP and Country Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/INDEX.md Extracts the client's IP address and attempts to resolve their country from the provided request headers. ```APIDOC ## getIpAndCountry ### Description Extracts the client's IP address and attempts to resolve their country from the provided request headers. This is useful for logging and geolocation purposes. ### Method Not applicable (internal SDK method) ### Parameters - **headers** (object) - Required - The request headers object. ### Response #### Success Response (200) - **country** (string) - The detected country code (e.g., 'US', 'GB'). - **clientIp** (string) - The detected client IP address. ``` -------------------------------- ### Component Lifecycle in AdminForth Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Illustrates the sequence of events from page load to component mounting, including when audit log and related logs components are injected. ```text Page Load ├─ Resource configuration loaded ├─ Component paths resolved │ ├─ AuditLogView.vue injected if audit log resource │ └─ RelatedLogsLink.vue injected if tracked resource └─ Components mounted with props ``` -------------------------------- ### Audit Log Plugin Initialization Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Demonstrates how to import and instantiate the AuditLogPlugin. This is the primary way to integrate the audit log functionality into an AdminForth application. Ensure the plugin is imported from '@adminforth/audit-log'. ```typescript import AuditLogPlugin from '@adminforth/audit-log'; const plugin = new AuditLogPlugin(options); // Available methods on instance plugin.createLogRecord(...) plugin.logCustomAction(...) plugin.getIpAndCountry(...) plugin.getClientIpCountry(...) plugin.modifyResourceConfig(...) ``` -------------------------------- ### MySQL Audit Log Schema Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Example MySQL schema for the audit_logs table. Adjust data types and constraints as necessary for your MySQL version and requirements. ```sql CREATE TABLE audit_logs ( id INT AUTO_INCREMENT PRIMARY KEY, resource_id VARCHAR(255) NOT NULL, action VARCHAR(50) NOT NULL, change_data JSON NOT NULL, admin_user_id CHAR(36) NOT NULL, record_id VARCHAR(255) NOT NULL, created_at VARCHAR(50) NOT NULL, country VARCHAR(2), ip_address VARCHAR(45), INDEX idx_resource (resource_id), INDEX idx_record (record_id), INDEX idx_user (admin_user_id), INDEX idx_created (created_at DESC) ); ``` -------------------------------- ### Package.json Exports Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Defines the entry points for the package, specifying how it should be imported in different module systems. This configuration is crucial for module resolution and compatibility. ```json { "main": "dist/index.js", "types": "dist/index.d.ts", "type": "module", "exports": { ".": { "import": "./dist/index.js", "types": "./dist/index.d.ts" } } } ``` -------------------------------- ### Initialize AuditLogPlugin Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Instantiate the AuditLogPlugin with your custom options. Ensure 'options' conforms to the PluginOptions interface. ```typescript const auditLogPlugin = new AuditLogPlugin(options: PluginOptions); ``` -------------------------------- ### Audit Log Plugin Instance Methods Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md This section details the methods available on an instantiated Audit Log plugin. These methods allow for the creation of log records, logging custom actions, and retrieving client IP and country information. ```APIDOC ## Audit Log Plugin Instance Methods ### Description Provides methods to interact with the audit log system, including creating log entries, logging custom actions, and retrieving geographical information based on IP addresses. ### Methods - **createLogRecord(record)** - **Description**: Creates a new log record. - **Parameters**: - `record` (object) - Required - The log record object to be created. - **logCustomAction(action, details)** - **Description**: Logs a custom action performed by a user. - **Parameters**: - `action` (string) - Required - The name of the custom action. - `details` (object) - Optional - Additional details about the custom action. - **getIpAndCountry()** - **Description**: Retrieves the current user's IP address and country. - **Returns**: (Promise) - An object containing the IP address and country. - **getClientIpAndCountry()** - **Description**: Retrieves the client's IP address and country. - **Returns**: (Promise) - An object containing the IP address and country. - **modifyResourceConfig(resourceName, config)** - **Description**: Modifies the configuration for a specific resource. - **Parameters**: - `resourceName` (string) - Required - The name of the resource to modify. - `config` (object) - Required - The new configuration for the resource. ``` -------------------------------- ### Initialize and Build Diff File Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md This function generates the diff file content from old and new records, initializes its theme, and then builds either a split or unified diff based on the current mode. It handles cases where both old and new records are empty. ```typescript function initDiffFile() { // If both old and new records are empty, don't generate diff if ( Object.keys(JSON.parse(oldContent)).length === 0 && Object.keys(JSON.parse(newContent)).length === 0 ) { return; // Shows "No changes to display" } // Generate diff file const file = generateDiffFile( 'diff.json', // Old filename oldContent, // Old content 'diff.json', // New filename newContent, // New content 'json', // Old language 'json' // New language ); // Initialize theme file.initTheme(theme.value === 'dark' ? 'dark' : 'light'); file.init(); // Build diff based on mode if (mode.value === DiffModeEnum.Split) { file.buildSplitDiffLines(); } else { file.buildUnifiedDiffLines(); } diffFile.value = file; } ``` -------------------------------- ### Batch Logging for Efficiency Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Improve efficiency by collecting multiple log entries and sending them in a single batch, rather than logging each item individually in a loop. This reduces the overhead of repeated network requests or database operations. ```typescript // Instead of logging each item in a loop: for (const id of itemIds) { await auditLogPlugin.logCustomAction(...); // SLOW } // Collect and log in batch: const batchLog = itemIds.map(id => ({ resource_id: 'items', record_id: id, action_id: 'bulk_update', changes: { updated: true } })); await auditLogPlugin.logCustomAction({ resourceId: null, recordId: null, actionId: 'bulk_item_update', oldData: null, data: { items_updated: itemIds.length, batch_size: batchLog.length }, user: currentUser }); ``` -------------------------------- ### AuditLogPlugin Constructor Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/api-reference.md Initializes the AuditLogPlugin with configuration options. It ensures the plugin is a single instance and sets up resource column mappings. ```APIDOC ## AuditLogPlugin Constructor ### Description Initializes the AuditLogPlugin. Configures the plugin to be a single instance across the entire application. The plugin extends AdminForthPlugin with entry point `import.meta.url`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`PluginOptions`) - Required - Configuration object for the plugin ### Request Example ```typescript import AuditLogPlugin from '@adminforth/audit-log'; const auditLogPlugin = new AuditLogPlugin({ excludeResourceIds: ['internal_logs'], resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'data', resourceUserIdColumnName: 'user_id', resourceRecordIdColumnName: 'record_id', resourceCreatedColumnName: 'created_at', resourceCountryColumnName: 'country', resourceIpColumnName: 'ip_address' } }); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Country from Specific IP Address Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/api-reference.md Resolves the country for a given IP address using multiple fallback methods. This function is useful when the IP address is already known. ```typescript async getClientIpCountry( headers: Record, clientIp: string | null ): Promise ``` ```typescript const country = await auditLogPlugin.getClientIpCountry(req.headers, '192.0.2.1'); console.log(country); // 'US' ``` -------------------------------- ### Log Non-Resource Action (Database Backup) Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Log a system-level action that is not tied to a specific resource, such as a database backup. This includes details about the backup process. ```typescript // Log system maintenance event (not tied to a specific resource) await auditLogPlugin.logCustomAction({ resourceId: null, recordId: null, actionId: 'database_backup', oldData: null, data: { backup_time: new Date().toISOString(), backup_size_mb: 1024, backup_location: 's3://backups/...' }, user: systemAdminUser, headers: req.headers }); ``` -------------------------------- ### Audit Log Entry with Masked Field Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md An example of an audit log entry where a backendOnly field ('password') is automatically masked. The masked value is represented as '' or ''. ```json { "oldRecord": { "password": "" }, "newRecord": { "password": "" } } ``` -------------------------------- ### Change Tracking Format - Create Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/types.md Shows the change tracking format for a 'create' action, where 'oldRecord' is empty and 'newRecord' contains the newly created data. ```typescript { oldRecord: {}, newRecord: { id: 1, email: 'user@example.com', ... } } ``` -------------------------------- ### Get IP and Country from Headers Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/api-reference.md Extracts the client's IP address and resolves their country from HTTP request headers. It prioritizes ISO country headers, then checks the audit log database, and finally falls back to the ipinfo.io API. ```typescript async getIpAndCountry(headers: Record): Promise<{ country: string | null, clientIp: string | null }> ``` ```typescript const { country, clientIp } = await auditLogPlugin.getIpAndCountry(req.headers); console.log(`Request from ${country} (${clientIp})`); ``` -------------------------------- ### Create Audit Log Database Table Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Provides the SQL statement to create the 'audit_logs' table, specifying columns for storing audit trail information. ```sql CREATE TABLE audit_logs ( id INT PRIMARY KEY AUTO_INCREMENT, resource_id VARCHAR(255), action VARCHAR(50), data JSON, user_id INT, record_id INT, created_at VARCHAR(50) ); ``` -------------------------------- ### Optional Plugin Options Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Illustrates the optional configuration settings for the AuditLogPlugin, such as excluding specific resource IDs or defining custom headers for geolocation. ```typescript const options: PluginOptions = { excludeResourceIds?: string[], resourceColumns: { ... }, resourceCountryColumnName?: string, resourceIpColumnName?: string, isoCountryCodeRequestHeader?: string }; ``` -------------------------------- ### createLogRecord Success Response Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md Indicates a successful creation of a log record. No further data is returned. ```typescript { ok: true } ``` -------------------------------- ### Copy Assets with rsync Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Copies custom assets (Vue components) to the distribution directory, excluding the node_modules folder. This ensures that necessary frontend assets are included in the build output. ```bash rsync -av --exclude 'node_modules' custom dist/ ``` -------------------------------- ### createLogRecord Success Response Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md Indicates that a log record was created successfully. ```APIDOC ## createLogRecord Success ### Response #### Success Response (200) - **ok** (boolean) - Indicates success. ``` -------------------------------- ### AuditLogView Component Dependencies Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Lists the necessary imports for the AuditLogView component, including Vue's reactivity functions, asynchronous component loading, and specific libraries for diff viewing. ```vue ``` -------------------------------- ### Audit Log Configuration Flow Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Outlines the configuration flow when registering the audit log plugin. This involves modifying resource configurations, registering hooks, injecting UI components, and populating resource enums. ```text adminforth.registerPlugin() ↓ modifyResourceConfig() [index.ts:225] ├─ Store adminforth reference ├─ Validate audit log resource ├─ Register CRUD hooks ├─ Inject UI components └─ Populate resource enum ``` -------------------------------- ### Import AdminForth Types and Enums Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Imports necessary types and enums from the 'adminforth' package for use within the plugin. ```typescript // AdminForth types and enums import type { AdminForthResource, IAdminForth, AdminUser, } from "adminforth"; import { AdminForthPlugin, AllowedActionsEnum, AdminForthSortDirections, AdminForthDataTypes, HttpExtra, ActionCheckSource, Filters } from "adminforth"; ``` -------------------------------- ### Audit Log with IP and Country Tracking Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Configure the AuditLogPlugin to track IP addresses and country codes. Ensure the specified request headers are present and the database schema includes columns for this information. ```typescript const auditLogPlugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'changes', resourceUserIdColumnName: 'admin_id', resourceRecordIdColumnName: 'affected_record_id', resourceCreatedColumnName: 'happened_at', resourceCountryColumnName: 'country', resourceIpColumnName: 'ip_address' }, isoCountryCodeRequestHeader: 'CF-IPCountry' }); // Database schema: // CREATE TABLE audit_logs ( // id INT PRIMARY KEY, // resource_id VARCHAR(255), // action VARCHAR(50), // changes JSONB, // admin_id UUID, // affected_record_id UUID, // happened_at VARCHAR(50), // country VARCHAR(2), // ip_address VARCHAR(45) // ); ``` -------------------------------- ### Build TypeScript Project Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Compiles the TypeScript project into JavaScript and generates type declarations. This command is typically run as part of the build process. ```bash npm run build # Output: tsc ``` -------------------------------- ### Handle Missing Column Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Detect if a specified column is not found within a resource during configuration. Throws an error to alert developers to the missing column. ```typescript // 2. Column not found if (!diffColumn) { throw new Error(`Column not found in ${resource.label}`); } ``` -------------------------------- ### Import Internal Plugin Dependencies Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Imports local types and the dayjs library with its UTC plugin for date/time handling. ```typescript // Plugin options type import { PluginOptions } from "./types.js"; // Date/time library import dayjs from 'dayjs'; import utc from 'dayjs/plugin/utc.js'; ``` -------------------------------- ### Audit Log Plugin Options Type Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/module-graph.md Shows how to import and use the PluginOptions type for configuring the AuditLogPlugin. This is useful for ensuring type safety when defining plugin configurations. ```typescript import type { PluginOptions } from '@adminforth/audit-log'; const config: PluginOptions = { resourceColumns: { ... } }; ``` -------------------------------- ### Exposed Navigation Method Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Exposes a 'click' method to allow parent components to programmatically trigger navigation to the audit log history using the router. ```typescript defineExpose({ click: goToAuditLog, }); function goToAuditLog() { if (!to.value) return; router.push(to.value); } ``` -------------------------------- ### Import Dependencies for Audit Log UI Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Imports necessary modules from Vue, Vue Router, and Flowbite for creating audit log related UI components. ```typescript import { computed } from 'vue'; import { useRoute } from 'vue-router'; import { IconClockSolid } from '@iconify-prerendered/vue-flowbite'; import { useRouter } from 'vue-router'; ``` -------------------------------- ### Log Custom Application Actions Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Log application-specific actions using the `logCustomAction` method. Provide resource ID, record ID, action ID, relevant data, user information, and request headers. ```typescript await auditLogPlugin.logCustomAction({ resourceId: 'users', recordId: userId, actionId: 'login_success', data: { ip: clientIp, timestamp: new Date() }, user: adminUser, headers: req.headers }); ``` -------------------------------- ### Pass Request Headers for IP Detection Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md Ensure IP address detection works by passing the request headers to the createLogRecord function. This is required for the plugin to access header information. ```typescript // Must pass headers await auditLogPlugin.createLogRecord( resource, 'edit', newData, adminUser, oldData, { headers: req.headers } // Required for IP detection ); ``` -------------------------------- ### Configure Audit Log Resource Columns Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Customize the visibility and components for columns in the audit log resource. Use this to define how data is displayed and edited. ```typescript const diffColumn = resource.columns.find(c => c.name === options.resourceColumns.resourceDataColumnName ); diffColumn.showIn = { show: true, // Visible on detail view list: false, // Hidden from list view edit: false, // Not editable create: false, // Not creatable filter: false // Not filterable }; diffColumn.components = { show: { file: './AuditLogView.vue', // Custom diff viewer meta: { ... } } }; ``` -------------------------------- ### AuditLogView Meta Object Structure Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Illustrates the expected structure of the 'meta' object, specifically highlighting the 'resourceColumns' property which maps to the audit log record's data field. ```typescript meta: { resourceColumns: { resourceDataColumnName: 'change_data', // Field name in audit log record // ... other column names }, pluginInstanceId: 'unique-id' } ``` -------------------------------- ### Audit Log Context for Show Page Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Defines how to extract `recordId` and `resourceId` from route parameters when the current route name is 'resource-show'. ```plaintext route.name === 'resource-show' ├─ recordId from route.params.primaryKey || route.params.id └─ resourceId from route.params.resourceId ``` -------------------------------- ### modifyResourceConfig Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Initializes or modifies resource configurations. This is a void method. ```APIDOC ## modifyResourceConfig(...) ### Description Initializes or modifies the configuration for resources tracked by the audit log system. This method does not return a value. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **...** (arguments) - Required - Arguments specifying the resource and its configuration details. ### Request Example ```json { "resource_name": "users", "config": { "log_changes": true, "fields_to_track": ["email", "name"] } } ``` ### Response #### Success Response (200) - **void** - This method does not return any value. ### Response Example ```json null ``` ``` -------------------------------- ### Props Flow in AdminForth Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Details the data flow from the AdminForth Resource Configuration to the Vue Component's props and computed properties. ```text AdminForth Resource Config ↓ Component Meta Object ├─ resourceColumns ├─ pluginInstanceId └─ auditLogResourceId ↓ Vue Component ├─ Props binding └─ Computed properties ``` -------------------------------- ### Log Audit Log Creation Errors Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Implement a try-catch block to handle errors during the creation of audit log entries. Errors are logged, but the main application operation continues uninterrupted. ```typescript try { await this.adminforth.createResourceRecord({ resource: auditLogResource, record, adminUser: user }); } catch (error) { // Plugin logs error but allows original operation to continue console.error('Audit log creation failed:', error); } ``` -------------------------------- ### createLogRecord Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Logs a CRUD operation to the audit trail. Returns a promise indicating success. ```APIDOC ## createLogRecord(...) ### Description Logs a CRUD operation. This method is used to record changes made to resources. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **...** (arguments) - Required - Arguments detailing the CRUD operation, resource, user, and data. ### Request Example ```json { "resource_id": "user_123", "action": "UPDATE", "data": { ... }, "user_id": 1, "record_id": 456 } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the log record was created successfully. ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Basic Error Handling for Custom Actions Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md Use a try-catch block to handle potential errors during the logging of custom actions. Differentiate between 'not found' errors and other general errors. ```typescript try { await auditLogPlugin.logCustomAction({ resourceId: 'users', recordId: recordId, actionId: 'password_reset', oldData: null, data: { reset_token: token }, user: adminUser }); } catch (error) { if (error.message.includes('not found')) { // Handle missing resource console.error('Resource not found:', error.message); } else { // Handle other errors console.error('Audit log failed:', error); } } ``` -------------------------------- ### List All Changes for a User Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Retrieve all audit log entries associated with a specific user ID. Results are sorted by creation date in descending order. ```typescript const userChanges = await adminforth.resource('audit_logs').getList({ filters: Filters.EQ('user_id', adminUserId), sort: { column: 'created_at', direction: 'desc' } }); userChanges.forEach(log => { console.log(`${log.action} on ${log.resource_id}/${log.record_id}`); }); ``` -------------------------------- ### Change Tracking Format - Edit Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/types.md Illustrates the format for tracking changes during an 'edit' action, showing the state of fields before and after the modification. ```typescript { oldRecord: { email: 'old@example.com', status: 'active' }, newRecord: { email: 'new@example.com', status: 'inactive' } } ``` -------------------------------- ### Complete Audit Log Configuration with Optional Fields Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Configures the Audit Log plugin with all optional fields, including excluded resource IDs and custom request headers for IP country detection. This provides comprehensive logging capabilities. ```typescript const auditLogPlugin = new AuditLogPlugin({ excludeResourceIds: ['temp_data', 'cache_table', 'internal_logs'], resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action_type', resourceDataColumnName: 'changes', resourceUserIdColumnName: 'admin_user_id', resourceRecordIdColumnName: 'affected_record_id', resourceCreatedColumnName: 'timestamp', resourceCountryColumnName: 'country', resourceIpColumnName: 'ip_address' }, isoCountryCodeRequestHeader: 'CF-IPCountry' }); ``` -------------------------------- ### Selective Logging for Performance Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Optimize performance by excluding high-volume, low-importance resource IDs from automatic logging. Important events can still be logged manually using `logCustomAction`. ```typescript const auditLogPlugin = new AuditLogPlugin({ // Exclude analytics and events to reduce load excludeResourceIds: [ 'page_views', 'api_calls', 'user_sessions', 'metric_points' ], resourceColumns: { ... } }); // But manually log important events: adminforth.hooks.resource('page_views').create.afterSave.push( async ({ record, adminUser, extra }) => { // Only log if critical if (record.event_type === 'security_event') { await auditLogPlugin.logCustomAction({ resourceId: 'page_views', recordId: record.id, actionId: 'security_event_logged', data: record, user: adminUser, headers: extra.headers }); } } ); ``` -------------------------------- ### Required Plugin Options Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Defines the essential configuration for the AuditLogPlugin, specifying the database column mappings required for logging. ```typescript const options: PluginOptions = { resourceColumns: { resourceIdColumnName: string, resourceActionColumnName: string, resourceDataColumnName: string, resourceUserIdColumnName: string, resourceRecordIdColumnName: string, resourceCreatedColumnName: string } }; ``` -------------------------------- ### Log Custom Action with Audit Log Plugin Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Shows how to manually log a custom action using the `logCustomAction` method of the AuditLogPlugin, useful for actions not covered by standard CRUD operations. ```typescript await auditLogPlugin.logCustomAction({ resourceId: 'users', recordId: userId, actionId: 'password_reset', oldData: null, data: { reset_token: token }, user: currentAdminUser, headers: req.headers }); ``` -------------------------------- ### Automatic Logging for Create Operation Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md When a user creates a new record via the admin panel, the audit log captures the resource, action, new record data, user information, and contextual details. ```typescript // User creates a product via UI // Admin panel sends: POST /adminforth-api/products/create { name: 'New Product', price: 99.99, stock: 50 } // Audit log automatically records: { resource_id: 'products', action: 'create', data: { oldRecord: {}, newRecord: { id: 123, name: 'New Product', price: 99.99, stock: 50 } }, user_id: 5, record_id: 123, created_at: '2026-06-29T14:30:45Z', country: 'US', ip_address: '192.0.2.1' } ``` -------------------------------- ### Audit Log Context for List Page (Three-Dot Menu) Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Defines how to extract `recordId` and `resourceId` when the current route name is 'resource-list', typically for actions within the three-dot menu. ```plaintext route.name === 'resource-list' ├─ recordId from props.record[pkName] └─ resourceId from props.resource.resourceId ``` -------------------------------- ### Navigating Audit Log Views Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Illustrates the user flow for accessing and viewing edit history for a specific record, from the detail page to the filtered audit log list and diff view. ```plaintext User Detail Page (users/42) ↓ User clicks "Edit History" ↓ Audit Log List (filtered to user 42) ↓ User clicks on edit log entry ↓ Shows diff: - Name: "John" → "Jane" - Email: "john@..." → "jane@..." ↓ User clicks back ↓ Returns to Audit Log List ``` -------------------------------- ### Log Bulk Price Update Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/examples.md Log a bulk operation, such as updating prices for multiple products. This snippet iterates through selected product IDs and logs each update individually. ```typescript for (const productId of selectedProductIds) { await auditLogPlugin.logCustomAction({ resourceId: 'products', recordId: productId, actionId: 'bulk_price_update', oldData: { price: originalPrice }, data: { price: newPrice }, user: currentAdminUser, headers: req.headers }); } ``` -------------------------------- ### createLogRecord Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/api-reference.md Creates an audit log entry for CRUD operations. It automatically detects changes, hides backend fields, captures IP and geolocation, and skips logging for external users. ```APIDOC ## createLogRecord ### Description Creates an audit log entry for CRUD operations. Automatically: - Detects changes between old and new records - Hides backend-only fields - Captures client IP address if configured - Detects geolocation from IP header or via ipinfo.io API - Skips logging for external (non-AdminForth) users - Stores ISO UTC timestamp ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **resource** (`AdminForthResource`) - Yes - The resource being modified - **action** (`AllowedActionsEnum | string`) - Yes - The action performed: 'create', 'edit', or 'delete' - **data** (`Object`) - Yes - The new record data - **user** (`AdminUser`) - Yes - The user performing the action - **oldRecord** (`Object`) - No - The previous record state (required for edit actions) - **extra** (`HttpExtra`) - No - HTTP request metadata including headers ### Request Example ```typescript const result = await auditLogPlugin.createLogRecord( userResource, 'edit', { id: 123, email: 'new@example.com' }, currentAdminUser, { id: 123, email: 'old@example.com' }, { headers: req.headers } ); ``` ### Response #### Success Response (200) - **ok** (`boolean`) - Success indication #### Response Example ```json { "ok": true } ``` ### Throws - Does not throw; returns `{ ok: true }` for external users without logging ``` -------------------------------- ### Fetch Record State Using Database Connector Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Retrieve the current state of a record using the database connector before an edit operation. This ensures accuracy by fetching the record post-update. ```typescript const connector = this.adminforth.connectors[resource.dataSource]; const newRecord = await connector.getRecordByPrimaryKey(resource, recordId); ``` -------------------------------- ### Audit Log Plugin Configuration Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/INDEX.md Configure the AuditLogPlugin by specifying resource column names, optionally excluding certain resource IDs, and setting a request header for ISO country codes. ```typescript const plugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: string, resourceActionColumnName: string, resourceDataColumnName: string, resourceUserIdColumnName: string, resourceRecordIdColumnName: string, resourceCreatedColumnName: string, resourceCountryColumnName?: string, resourceIpColumnName?: string }, excludeResourceIds?: string[], isoCountryCodeRequestHeader?: string }); ``` -------------------------------- ### getIpAndCountry Success Response Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md Returns the detected country and client IP address. ```APIDOC ## getIpAndCountry Success ### Response #### Success Response (200) - **country** (string | null) - The ISO 2-letter country code, or null if not detected. - **clientIp** (string | null) - The client's IP address, or null if not configured. ``` -------------------------------- ### Skipping Audit Log for External Users Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/errors.md When an external user attempts to create a log record, the operation silently returns { ok: true } without generating an audit log entry. Use logCustomAction() if external user actions need separate tracking. ```typescript const result = await auditLogPlugin.createLogRecord( resource, 'edit', newData, externalAdminUser, // { isExternalUser: true } oldData ); // result === { ok: true }, no log created ``` -------------------------------- ### Error Handling for Custom Actions Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/INDEX.md Implement a try-catch block to handle potential errors when logging custom actions. Check the error message to differentiate between specific issues like 'not found' and other general errors. ```typescript try { await plugin.logCustomAction({...}); } catch (error) { if (error.message.includes('not found')) { // Resource not found } else { // Other error } } ``` -------------------------------- ### Route Parameters for Audit Log Context Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/ui-components.md Lists the route parameters commonly used to determine the context for audit log related actions, including route name, resource ID, and primary key. ```plaintext | Parameter | Source | |-----------|--------| | `route.name` | Vue Router | | `route.params.resourceId` | Vue Router | | `route.params.primaryKey` | Vue Router | | `route.params.id` | Vue Router | ``` -------------------------------- ### Index Audit Log Table Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/plugin-integration.md Improve query performance by creating indexes on frequently filtered columns in the `audit_logs` table. ```sql CREATE INDEX idx_resource ON audit_logs(resource_id); CREATE INDEX idx_record ON audit_logs(record_id); CREATE INDEX idx_user ON audit_logs(user_id); ``` -------------------------------- ### Audit Log Configuration with UUID and Custom Types Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/configuration.md Sets up the Audit Log plugin using UUIDs for user and record identifiers, along with custom column names for geographical and IP data. This is useful when your database schema uses UUIDs. ```typescript const auditLogPlugin = new AuditLogPlugin({ resourceColumns: { resourceIdColumnName: 'resource_id', resourceActionColumnName: 'action', resourceDataColumnName: 'diff', resourceUserIdColumnName: 'admin_uuid', // Matches user table UUID column resourceRecordIdColumnName: 'record_uuid', // Matches resource primary key resourceCreatedColumnName: 'happened_at', resourceCountryColumnName: 'geo_country', resourceIpColumnName: 'source_ip' } }); ``` -------------------------------- ### AuditLogPlugin Runtime Phase Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/README.md Describes the runtime flow when a user performs a CRUD action, triggering audit log record creation, IP/country detection, and entry insertion. ```plaintext User Action (Create/Edit/Delete) ↓ CRUD Hook Fires ├─ Call createLogRecord() ├─ Detect IP/country └─ Insert audit log entry ``` -------------------------------- ### Log Custom Application Action Source: https://github.com/devforth/adminforth-audit-log/blob/main/_autodocs/INDEX.md Logs custom actions performed within the application that are not standard CRUD operations. This allows for tracking specific business logic events. ```APIDOC ## logCustomAction ### Description Logs custom actions performed within the application that are not standard CRUD operations. This allows for tracking specific business logic events. ### Method Not applicable (internal SDK method) ### Parameters - **resourceId** (string | number) - Required - The ID of the resource related to the custom action. - **recordId** (string | number) - Required - The ID of the specific record involved. - **actionId** (string) - Required - A unique identifier for the custom action. - **oldData** (object) - Optional - The state of the data before the custom action. - **data** (object) - Required - The data associated with the custom action. - **user** (any) - Required - The user performing the action. - **headers** (object) - Optional - Request headers, used for IP and country detection. ```