🔍 Code Extractor

function log_user_action

Maturity: 59

Creates an audit event node in a graph database to log user actions, connecting it to both an audit trail and the user who performed the action.

File:
/tf/active/vicechatdev/CDocs/utils/audit_trail.py
Lines:
924 - 963
Complexity:
moderate

Purpose

This function provides comprehensive audit logging functionality for tracking user actions within a document management system. It creates a structured audit trail by generating unique event nodes with timestamps, user information, and action details, then establishes relationships between the event, the audit trail, and the user. This enables tracking of all user activities for compliance, security monitoring, and debugging purposes.

Source Code

def log_user_action(user: DocUser, action_type: str, category: str = "USER_ACTION", details: Optional[Dict[str, Any]] = None) -> bool:
    """Log a user action in the audit trail."""
    try:
        # Create an audit event node
        event_uid = str(uuid.uuid4())
        timestamp = datetime.now()
        
        event_properties = {
            "UID": event_uid,
            "eventType": action_type,
            "eventCategory": category,
            "timestamp": timestamp,
            "userUID": user.uid if user else None,
            "userName": user.name if user else None,
            "details": json.dumps(details) if details else None
        }
        
        # Create the audit event node
        db.create_node(NodeLabels.AUDIT_EVENT, event_properties)
        
        # Connect to the audit trail
        db.create_relationship(
            from_uid=get_or_create_audit_trail_uid(),
            to_uid=event_uid,
            relationship_type=RelTypes.HAS_EVENT,
            properties={"created": timestamp}
        )
        
        # Connect to user if available
        if user:
            db.create_relationship(
                from_uid=event_uid,
                to_uid=user.uid,
                relationship_type="PERFORMED_BY"
            )
            
        return True
    except Exception as e:
        logger.error(f"Error logging user action: {e}")
        return False

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
action_type str - positional_or_keyword
category str 'USER_ACTION' positional_or_keyword
details Optional[Dict[str, Any]] None positional_or_keyword

Parameter Details

user: A DocUser object representing the user performing the action. Contains user identification (uid) and name. Can be None if the action is system-generated or user context is unavailable.

action_type: A string describing the type of action being logged (e.g., 'LOGIN', 'DOCUMENT_CREATED', 'PERMISSION_CHANGED'). This categorizes the specific operation performed.

category: Optional string to group related action types together. Defaults to 'USER_ACTION'. Can be used for higher-level categorization like 'SECURITY', 'DOCUMENT_MANAGEMENT', etc.

details: Optional dictionary containing additional contextual information about the action. Will be JSON-serialized and stored with the event. Can include any relevant metadata like document IDs, IP addresses, or operation-specific data.

Return Value

Type: bool

Returns a boolean value: True if the audit event was successfully created and all relationships were established in the database; False if any exception occurred during the logging process. The function catches all exceptions and logs errors, ensuring it never raises exceptions to calling code.

Dependencies

  • uuid
  • datetime
  • json
  • logging
  • typing
  • CDocs

Required Imports

import logging
import uuid
from typing import Dict, Any, Optional
from datetime import datetime
import json
from CDocs import db
from CDocs.config import settings
from CDocs.db.schema_manager import NodeLabels, RelTypes
from CDocs.models.user_extensions import DocUser

Usage Example

from CDocs.models.user_extensions import DocUser
from your_module import log_user_action

# Create or retrieve a user object
user = DocUser(uid='user-123', name='John Doe')

# Log a simple action
success = log_user_action(
    user=user,
    action_type='LOGIN',
    category='SECURITY'
)

# Log an action with detailed information
details = {
    'document_id': 'doc-456',
    'ip_address': '192.168.1.1',
    'operation': 'update',
    'fields_changed': ['title', 'content']
}

success = log_user_action(
    user=user,
    action_type='DOCUMENT_MODIFIED',
    category='DOCUMENT_MANAGEMENT',
    details=details
)

if success:
    print('Action logged successfully')
else:
    print('Failed to log action')

Best Practices

  • Always check the return value to ensure the action was logged successfully, especially for critical security events
  • Use consistent action_type strings across your application to enable effective querying and reporting
  • Include relevant contextual information in the details dictionary to make audit logs more useful for investigation
  • Consider the performance impact when logging high-frequency actions, as each call creates multiple database operations
  • The function silently catches all exceptions and returns False - monitor logs for error messages to detect logging failures
  • Ensure the audit trail exists before calling this function (via get_or_create_audit_trail_uid())
  • Be mindful of sensitive data in the details dictionary as it will be stored in plain text JSON format
  • Use appropriate category values to organize audit events for easier filtering and analysis

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_audit_entry 68.4% similar

    Creates an audit trail entry for document actions, logging user activity, document changes, and lifecycle events with fallback mechanisms.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_audit_trail 68.1% similar

    Retrieves audit trail events from a Neo4j database with optional filtering by date range, action type, and user, returning a list of audit event dictionaries.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function log_event 66.4% similar

    Creates and persists an audit trail event in a Neo4j graph database, linking it to users, resources, and an audit trail node with comprehensive event metadata.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function get_user_activity 63.5% similar

    Retrieves user activity logs from a Neo4j graph database by querying AuditEvent nodes with flexible filtering options for date ranges, users, and action types.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function update_user_v1 60.2% similar

    Updates user information in a Neo4j graph database, including username, full name, email, department, and active status, with automatic audit logging.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
← Back to Browse