🔍 Code Extractor

function create_user

Maturity: 59

Creates a new user in the system with validation, password hashing, and role assignment, including CDocs user extension setup.

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
209 - 273
Complexity:
moderate

Purpose

This function handles the complete user creation workflow including input validation, user node creation in the database, password hashing, CDocs user extension setup with default VIEWER role, and optional role assignment. It ensures all required fields are present, generates a unique UID, stores user properties in the database, and integrates with the CDocs document management system's user extension model.

Source Code

def create_user(user_data: Dict[str, Any]) -> str:
    """
    Create a new user.
    
    Args:
        user_data: Dictionary with user information
        
    Returns:
        UID of the created user
    """
    try:
        # Validate input
        required_fields = ['username', 'password', 'email']
        for field in required_fields:
            if field not in user_data or not user_data[field]:
                raise ValidationError(f"Missing required field: {field}")
        
        # Create user node with basic properties
        user_properties = {
            "UID": str(uuid.uuid4()),
            "username": user_data['username'],
            "Name": f"{user_data.get('first_name', '')} {user_data.get('last_name', '')}".strip(),
            "Mail": user_data['email'],  # Changed from 'email' to 'Mail'
            "first_name": user_data.get('first_name', ''),
            "last_name": user_data.get('last_name', ''),
            "department": user_data.get('department_id', ''),  # Changed from 'Department' to 'department'
            "active": user_data.get('active', True),
            "created_date": datetime.datetime.now().isoformat()
        }
        
        # Hash password if provided
        if 'password' in user_data and user_data['password']:
            # In a real system, use a proper password hashing library
            import hashlib
            user_properties["password_hash"] = hashlib.sha256(
                user_data['password'].encode()
            ).hexdigest()
        
        # Create user node
        db.create_node(NodeLabels.USER, properties=user_properties)
        
        # Set up CDocs user extension (adds CDocs_User label and default VIEWER role)
        from CDocs.models.user_extensions import DocUser
        DocUser._setup_user_extension(user_properties["UID"])
        
        # Add roles if specified (removing any existing roles first)
        if 'roles' in user_data and user_data['roles']:
            # Create DocUser instance to manage roles
            doc_user = DocUser(uid=user_properties["UID"])
            
            # Get current roles to remove any that aren't in the new set
            current_roles = doc_user.roles
            for role in current_roles:
                if role != 'VIEWER' and role not in user_data['roles']:
                    doc_user.remove_role(role)
            
            # Add new roles
            for role in user_data['roles']:
                if role in settings.USER_ROLES:
                    doc_user.add_role(role)
        
        return user_properties["UID"]
    except Exception as e:
        logger.error(f"Error creating user: {e}")
        raise

Parameters

Name Type Default Kind
user_data Dict[str, Any] - positional_or_keyword

Parameter Details

user_data: Dictionary containing user information. Required keys: 'username' (str), 'password' (str), 'email' (str). Optional keys: 'first_name' (str), 'last_name' (str), 'department_id' (str), 'active' (bool, defaults to True), 'roles' (list of str, must be valid roles from settings.USER_ROLES). The password will be hashed using SHA256 before storage.

Return Value

Type: str

Returns a string representing the unique identifier (UID) of the newly created user. This UID is a UUID4 string that can be used to reference the user in subsequent operations.

Dependencies

  • uuid
  • datetime
  • hashlib
  • logging
  • typing
  • pathlib
  • CDocs

Required Imports

import uuid
import datetime
import logging
from typing import Dict, Any
from CDocs import db
from CDocs.models.user_extensions import DocUser
from CDocs.db.schema_manager import NodeLabels
from CDocs.config import settings

Conditional/Optional Imports

These imports are only needed under specific conditions:

import hashlib

Condition: only when password is provided in user_data and needs to be hashed

Required (conditional)

Usage Example

# Example 1: Create user with minimal required fields
user_data = {
    'username': 'jdoe',
    'password': 'SecurePass123!',
    'email': 'jdoe@example.com'
}
uid = create_user(user_data)
print(f"Created user with UID: {uid}")

# Example 2: Create user with full details and roles
user_data = {
    'username': 'asmith',
    'password': 'AnotherSecurePass456!',
    'email': 'asmith@example.com',
    'first_name': 'Alice',
    'last_name': 'Smith',
    'department_id': 'DEPT-001',
    'active': True,
    'roles': ['EDITOR', 'REVIEWER']
}
uid = create_user(user_data)
print(f"Created user with UID: {uid}")

Best Practices

  • Always provide all required fields (username, password, email) in user_data dictionary
  • Ensure passwords are strong before passing to this function as it only hashes, does not validate password strength
  • Note that SHA256 is used for password hashing in this implementation - in production, use bcrypt or argon2 for better security
  • The function automatically assigns a VIEWER role by default through _setup_user_extension
  • When specifying roles, ensure they exist in settings.USER_ROLES to avoid silent failures
  • Handle ValidationError exceptions when calling this function to catch missing required fields
  • The function logs errors but re-raises exceptions, so implement proper error handling in calling code
  • The created_date is automatically set to the current timestamp in ISO format
  • User properties use mixed naming conventions (Mail vs email, department vs Department) - be aware when querying
  • The function creates both a base user node and a CDocs user extension, making it specific to CDocs systems

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_user 66.7% 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
  • function create_document_v1 56.5% similar

    Creates a new version of an existing document in a document management system, storing the file in FileCloud and tracking version metadata in Neo4j graph database.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function delete_user_v1 56.5% similar

    Deletes a user from the database by removing their user node using the provided user_id.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_user_by_id 56.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 create_dbo_usergroup 55.8% similar

    Creates a new dbo_UserGroup node in a Neo4j graph database with specified properties and returns the created node.

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