function init_admin_role
Initializes an ADMIN role for a specific administrator user (wim@vicebio.com) in a Neo4j graph database by creating role relationships if they don't already exist.
/tf/active/vicechatdev/CDocs single class/db/schema_manager.py
564 - 636
moderate
Purpose
This function is part of a CDocs system initialization process that ensures the administrator user has proper ADMIN role privileges. It queries the Neo4j database to find the admin user, checks if they already have the ADMIN role, and if not, creates the role relationship between the user, role, and CDocs system node. The function includes comprehensive error handling and logging, and is protected by a cooldown decorator to prevent excessive execution.
Source Code
def init_admin_role():
"""
Initialize admin role for the administrator user (wim@vicebio.com)
"""
logger.info("Setting up admin role")
from CDocs import db
import uuid
try:
# Find admin user
result = db.run_query(
"""
MATCH (u:User)
WHERE u.Mail = 'wim@vicebio.com'
RETURN u.UID AS UID
"""
)
# Check if result exists and has at least one record
if not result or len(result) == 0:
logger.warning("Admin user (wim@vicebio.com) not found")
return False
admin_uid = result[0]['UID']
# Check if user already has ADMIN role
result = db.run_query(
"""
MATCH (u:User {UID: $uid})-[:HAS_ROLE]->(r:CDocs_Role {name: 'ADMIN'})
RETURN count(r) > 0 AS has_admin
""",
{"uid": admin_uid}
)
# Check if result exists and has at least one record
if result and len(result) > 0 and result[0].get('has_admin', False):
logger.info("Admin user already has ADMIN role")
return True
# Find CDocs node
result = db.run_query("MATCH (c:CDocs) RETURN c.UID AS uid LIMIT 1")
# Check if result exists and has at least one record
if not result or len(result) == 0:
logger.error("CDocs node not found")
return False
cdocs_uid = result[0]['uid']
# Add ADMIN role
db.run_query(
"""
MATCH (u:User {UID: $user_uid}), (c:CDocs {UID: $cdocs_uid})
MERGE (u)-[:HAS_ROLE]->(r:CDocs_Role {
UID: $role_uid,
name: 'ADMIN',
createdDate: datetime()
})<-[:ROLE_DEFINITION]-(c)
""",
{
"user_uid": admin_uid,
"cdocs_uid": cdocs_uid,
"role_uid": str(uuid.uuid4())
}
)
logger.info(f"Added ADMIN role to user wim@vicebio.com")
return True
except Exception as e:
logger.error(f"Error setting up admin role: {e}")
logger.error(traceback.format_exc())
return False
Return Value
Returns a boolean value: True if the admin role was successfully initialized or already exists, False if there was an error (such as admin user not found, CDocs node not found, or database query failure). The function logs detailed information about the outcome.
Dependencies
logginguuidtracebacktypingneo4jdatetimeCDocs
Required Imports
import logging
import uuid
import traceback
from typing import Dict, List, Any, Optional, Tuple
from neo4j import Driver, Session, Transaction
from datetime import datetime
from CDocs import guard_execution
from CDocs import db
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs import db
Condition: imported lazily inside the function body for database operations
Required (conditional)import uuid
Condition: imported lazily inside the function body for generating role UIDs
Required (conditional)Usage Example
# Ensure CDocs database connection is configured
# from CDocs import db, guard_execution
# import logging
# logger = logging.getLogger(__name__)
# Call the function to initialize admin role
result = init_admin_role()
if result:
print("Admin role successfully initialized")
else:
print("Failed to initialize admin role - check logs for details")
# Note: This function is typically called during system initialization
# and is protected by a 5-second cooldown to prevent rapid re-execution
Best Practices
- This function is idempotent - it can be safely called multiple times as it checks for existing roles before creating new ones
- The function is protected by a guard_execution decorator with a 5-second cooldown to prevent excessive database queries
- Always check the return value to ensure the admin role was successfully initialized
- Review logs for detailed information about the initialization process and any errors
- Ensure the admin user (wim@vicebio.com) exists in the database before calling this function
- The function creates a unique UID for each role using uuid.uuid4(), ensuring no conflicts
- The MERGE clause in Cypher ensures the role relationship is created only if it doesn't exist
- This function should typically be called during system initialization or setup phases
- The function requires proper Neo4j database connectivity through the CDocs.db module
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function init_admin_role_v1 99.7% similar
-
function get_admin_user 63.3% similar
-
function init_database 57.1% similar
-
function initialize_schema_v1 56.0% similar
-
function initialize_approval_workflow_types 54.2% similar