🔍 Code Extractor

function get_users

Maturity: 53

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

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
168 - 207
Complexity:
moderate

Purpose

This function queries a Neo4j database to fetch user records, excluding template users. It can retrieve either a specific user by their UID or all users in the system. The function transforms raw database nodes into structured dictionaries containing user profile information suitable for administrative interfaces. It includes error handling to return an empty list if the query fails.

Source Code

def get_users(user_id: Optional[str] = None) -> List[Dict[str, Any]]:
    """Get user information for admin panel."""
    try:
        if user_id:
            # Get specific user
            query = """
            MATCH (u:User {UID: $user_id})
            WHERE not ('Template' in labels(u))
            RETURN u
            """
            result = db.run_query(query, {'user_id': user_id})
        else:
            # Get all users
            query = """
            MATCH (u:User)
            WHERE not ('Template' in labels(u))
            RETURN u
            ORDER BY u.username
            """
            result = db.run_query(query)
        
        users = []
        for row in result:
            user_data = row.get('u', {})
            users.append({
                'id': user_data.get('UID', ''),
                'username': user_data.get('username', user_data.get('Name', '')),
                'email': user_data.get('Mail', ''),
                'first_name': user_data.get('firstName', ''),
                'last_name': user_data.get('lastName', ''),
                'Name': user_data.get('Name', ''),
                #'role': user_data.get('role', 'user'),
                'department': user_data.get('department', ''),
                'active': user_data.get('active', True)
            })
        
        return users
    except Exception as e:
        logger.error(f"Error getting users: {e}")
        return []

Parameters

Name Type Default Kind
user_id Optional[str] None positional_or_keyword

Parameter Details

user_id: Optional string parameter representing the unique identifier (UID) of a specific user. If provided, the function retrieves only that user's information. If None (default), the function retrieves all users in the system. The value should match the 'UID' property of User nodes in the Neo4j database.

Return Value

Type: List[Dict[str, Any]]

Returns a List of dictionaries, where each dictionary represents a user with the following keys: 'id' (user's UID), 'username' (username or Name fallback), 'email' (Mail property), 'first_name', 'last_name', 'Name', 'department', and 'active' (boolean status). Returns an empty list if an error occurs or no users are found. All string values default to empty strings if not present in the database, and 'active' defaults to True.

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 Optional, List, Dict, Any
import logging
from CDocs import db

Usage Example

# Initialize logger and database connection first
import logging
from typing import Optional, List, Dict, Any
from CDocs import db

logger = logging.getLogger(__name__)

# Get all users
all_users = get_users()
for user in all_users:
    print(f"User: {user['username']}, Email: {user['email']}")

# Get specific user by ID
user_id = "user-123-abc"
specific_user = get_users(user_id=user_id)
if specific_user:
    user_info = specific_user[0]
    print(f"Found user: {user_info['first_name']} {user_info['last_name']}")
else:
    print("User not found")

Best Practices

  • Always check if the returned list is empty before accessing user data to avoid index errors
  • The function returns an empty list on errors, so implement additional error checking if needed
  • Ensure the 'logger' object is properly initialized in the module scope before calling this function
  • The 'db.run_query()' method must be available and properly configured with Neo4j connection details
  • User nodes with 'Template' label are intentionally excluded from results
  • The function uses fallback values (username falls back to Name, empty strings for missing fields) to ensure consistent dictionary structure
  • Consider implementing pagination for large user bases as this function retrieves all users when user_id is None
  • The 'role' field is commented out in the code but may be needed for role-based access control implementations

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_user_by_id 74.4% 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
  • function get_system_stats 67.3% similar

    Retrieves comprehensive system statistics from a Neo4j graph database for display on an admin dashboard, including user counts, document counts, review cycles, and approval metrics.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_admin_user 66.3% similar

    Retrieves an admin user from a Neo4j database by querying for a specific email address and returns a DocUser object for document creation operations.

    From: /tf/active/vicechatdev/CDocs/FC_sync.py
  • function get_dbo_usergroup_by_uid 65.5% 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_all_dbo_usergroup 64.4% similar

    Queries a Neo4j graph database to retrieve all nodes labeled as 'dbo_UserGroup' with a configurable limit on the number of results returned.

    From: /tf/active/vicechatdev/neo4j_schema/neo4j_python_snippets.py
← Back to Browse