function update_user_v1
Updates user information in a Neo4j graph database, including username, full name, email, department, and active status, with automatic audit logging.
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
728 - 780
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.dbCDocs.utils.audit_traillogging
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function update_user 75.0% similar
-
function delete_user 60.6% similar
-
function log_user_action 60.2% similar
-
function get_users 60.0% similar
-
function get_user_by_id 59.9% similar