🔍 Code Extractor

function update_user_v1

Maturity: 55

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

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
728 - 780
Complexity:
moderate

Purpose

This function provides a centralized way to update user records in the database. It handles the construction of a full name from first and last name components, updates multiple user properties atomically, sets a lastModified timestamp, and automatically logs the update event to an audit trail for compliance and tracking purposes. It's designed for user management systems where user profile updates need to be tracked and persisted.

Source Code

def update_user(user_id: str, user_data: Dict[str, Any]) -> Dict[str, Any]:
    """Update user data."""
    try:
        # Construct full name from first and last name
        first_name = user_data.get('first_name', '').strip()
        last_name = user_data.get('last_name', '').strip()
        full_name = f"{first_name} {last_name}".strip() or user_data.get('username', '')
        
        query = """
        MATCH (u:User {UID: $user_id})
        SET u.username = $username,
            u.Name = $full_name,
            u.Mail = $email,
            u.department = $department,
            u.active = $active,
            u.lastModified = datetime()
        RETURN u
        """
        
        params = {
            'user_id': user_id,
            'username': user_data.get('username', ''),
            'full_name': full_name,
            'email': user_data.get('email', ''),
            'department': user_data.get('department', ''),
            'active': user_data.get('active', True)
        }
        
        result = db.run_query(query, params)
        
        if result:
            # Log the update
            from CDocs.utils import audit_trail
            audit_trail.log_event(
                event_type="USER_UPDATED",
                user=user_id,
                resource_uid=user_id,
                resource_type="User",
                details={
                    "username": user_data.get('username'),
                    "email": user_data.get('email'),
                    "department": user_data.get('department'),
                    "active": user_data.get('active')
                }
            )
            
            return {"success": True, "message": "User updated successfully"}
        else:
            return {"success": False, "message": "User not found"}
        
    except Exception as e:
        logger.error(f"Error updating user {user_id}: {e}")
        return {"success": False, "message": f"Failed to update user: {str(e)}"}

Parameters

Name Type Default Kind
user_id str - positional_or_keyword
user_data Dict[str, Any] - positional_or_keyword

Parameter Details

user_id: A unique string identifier (UID) for the user to be updated. This is used to locate the specific User node in the Neo4j database. Must match an existing user's UID.

user_data: A dictionary containing the user fields to update. Expected keys include: 'first_name' (str), 'last_name' (str), 'username' (str), 'email' (str), 'department' (str), and 'active' (bool). All fields are optional; missing fields will use empty strings or default values (True for 'active'). The function will strip whitespace from first_name and last_name.

Return Value

Type: Dict[str, Any]

Returns a dictionary with two keys: 'success' (bool) indicating whether the update succeeded, and 'message' (str) providing details. On success, message is 'User updated successfully'. On failure, message explains the error (either 'User not found' if the user_id doesn't exist, or 'Failed to update user: {error}' if an exception occurred).

Dependencies

  • CDocs.db
  • CDocs.utils.audit_trail
  • logging

Required Imports

from typing import Dict, Any
from CDocs import db
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.utils import audit_trail

Condition: imported lazily inside the function after successful database update to log the event

Required (conditional)

Usage Example

from typing import Dict, Any
from CDocs import db
import logging

# Ensure logger is configured
logger = logging.getLogger(__name__)

# Example usage
user_id = "user-12345"
user_data = {
    'first_name': 'John',
    'last_name': 'Doe',
    'username': 'jdoe',
    'email': 'john.doe@example.com',
    'department': 'Engineering',
    'active': True
}

result = update_user(user_id, user_data)

if result['success']:
    print(f"Success: {result['message']}")
else:
    print(f"Error: {result['message']}")

# Example with partial update
partial_update = {
    'email': 'newemail@example.com',
    'department': 'Sales'
}
result = update_user(user_id, partial_update)

Best Practices

  • Always provide a valid user_id that exists in the database to avoid 'User not found' errors
  • Include all relevant user fields in user_data dictionary even if only updating some fields, as missing fields will default to empty strings or True for 'active'
  • Handle the returned dictionary to check 'success' status before proceeding with dependent operations
  • Ensure the logger is properly configured before calling this function to capture error messages
  • The function automatically logs audit events, so no additional audit logging is needed after calling it
  • Be aware that the full_name is constructed from first_name and last_name; if both are empty, it falls back to username
  • The lastModified timestamp is automatically set to the current datetime, so no manual timestamp management is needed
  • Wrap calls to this function in appropriate error handling at the application level for production use

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_user 75.0% similar

    Updates an existing user's information in a Neo4j database, including profile fields, password, and role assignments.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function delete_user 60.6% similar

    Safely deactivates a user account by setting an 'active' flag to false rather than permanently deleting the user record from the database.

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

    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.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function get_users 60.0% similar

    Retrieves user information from a Neo4j graph database for display in an admin panel, with optional filtering by user ID.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_user_by_id 59.9% similar

    Retrieves user data from a Neo4j graph database by user ID, including associated roles and formatted name fields.

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