function get_user_by_id
Retrieves user data from a Neo4j graph database by user ID, including associated roles and formatted name fields.
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
690 - 726
moderate
Purpose
This function queries a Neo4j database to fetch comprehensive user information for editing purposes. It retrieves the User node by UID, optionally matches associated CDocs_Role nodes, and transforms the raw data into a structured dictionary with parsed name fields (first_name, last_name) and role information. The function handles missing data gracefully and returns None if the user is not found or an error occurs.
Source Code
def get_user_by_id(user_id: str) -> Optional[Dict[str, Any]]:
"""Get user data by ID for editing."""
try:
query = """
MATCH (u:User {UID: $user_id})
OPTIONAL MATCH (u)-[:HAS_ROLE]->(r:CDocs_Role)
RETURN u, collect(r.name) as roles
"""
result = db.run_query(query, {'user_id': user_id})
if not result:
return None
record = result[0]
user_data = record['u']
roles = record['roles']
# Extract first and last name from Name field
name_parts = user_data.get('Name', '').split(' ', 1)
first_name = name_parts[0] if len(name_parts) > 0 else ''
last_name = name_parts[1] if len(name_parts) > 1 else ''
return {
'uid': user_data.get('UID'),
'id': user_data.get('UID'), # Alias for compatibility
'username': user_data.get('username') or user_data.get('Name'),
'first_name': first_name,
'last_name': last_name,
'email': user_data.get('Mail'),
'department': user_data.get('department'),
'active': user_data.get('active', True),
'roles': roles
}
except Exception as e:
logger.error(f"Error getting user by ID {user_id}: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user_id |
str | - | positional_or_keyword |
Parameter Details
user_id: A string representing the unique identifier (UID) of the user to retrieve from the database. This should match the UID property of a User node in the Neo4j graph database.
Return Value
Type: Optional[Dict[str, Any]]
Returns an Optional[Dict[str, Any]] - either a dictionary containing user data or None. The dictionary includes keys: 'uid' (user ID), 'id' (alias for uid), 'username' (username or Name field), 'first_name' (parsed from Name), 'last_name' (parsed from Name), 'email' (from Mail property), 'department', 'active' (boolean, defaults to True), and 'roles' (list of role names). Returns None if the user is not found or if an exception occurs during the query.
Dependencies
loggingtypingCDocs.dbCDocs.models.documentCDocs.models.user_extensionsCDocs.db.schema_managerCDocs.configCDocs.utils.audit_trail
Required Imports
from typing import Dict, Any, Optional
import logging
from CDocs import db
Usage Example
from typing import Dict, Any, Optional
import logging
from CDocs import db
logger = logging.getLogger(__name__)
def get_user_by_id(user_id: str) -> Optional[Dict[str, Any]]:
# ... function code ...
pass
# Usage
user_data = get_user_by_id('user123')
if user_data:
print(f"User: {user_data['username']}")
print(f"Email: {user_data['email']}")
print(f"Roles: {user_data['roles']}")
print(f"Full name: {user_data['first_name']} {user_data['last_name']}")
else:
print("User not found or error occurred")
Best Practices
- Always check if the returned value is None before accessing dictionary keys
- The function logs errors but does not raise exceptions, making it safe for use in web handlers
- The 'id' field is provided as an alias for 'uid' for backward compatibility
- Name parsing assumes Western name format (first name followed by last name); may not work correctly for all cultural naming conventions
- The 'active' field defaults to True if not present in the database
- Username falls back to the Name field if the username property is not set
- Ensure the logger is properly configured before calling this function to capture error messages
- The function uses parameterized queries to prevent Cypher injection attacks
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_users 74.4% similar
-
function get_dbo_usergroup_by_uid 73.1% similar
-
function get_dbo_usergroup_by_id 71.4% similar
-
function get_node_by_uid 67.8% similar
-
function update_user 65.1% similar