🔍 Code Extractor

function get_user_by_id

Maturity: 53

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

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
690 - 726
Complexity:
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

  • logging
  • typing
  • CDocs.db
  • CDocs.models.document
  • CDocs.models.user_extensions
  • CDocs.db.schema_manager
  • CDocs.config
  • CDocs.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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_users 74.4% 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_dbo_usergroup_by_uid 73.1% similar

    Retrieves a single dbo_UserGroup node from a Neo4j graph database by matching its unique identifier (UID).

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function get_dbo_usergroup_by_id 71.4% similar

    Retrieves a single dbo_UserGroup node from a Neo4j graph database by its unique ID.

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
  • function get_node_by_uid 67.8% similar

    Retrieves a node from a Neo4j graph database by its unique identifier (UID) and returns it as a dictionary.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function update_user 65.1% 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
← Back to Browse