function delete_user
Safely deactivates a user account by setting an 'active' flag to false rather than permanently deleting the user record from the database.
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
782 - 813
moderate
Purpose
This function provides a safe user deletion mechanism by deactivating user accounts instead of permanently removing them. It updates the user's status in a Neo4j graph database, sets deactivation and modification timestamps, and logs the action to an audit trail. This approach preserves data integrity and allows for potential account recovery while preventing active use of the account.
Source Code
def delete_user(user_id: str) -> Dict[str, Any]:
"""Delete user (actually deactivate for safety)."""
try:
# Instead of deleting, we'll deactivate the user for safety
query = """
MATCH (u:User {UID: $user_id})
SET u.active = false,
u.deactivatedDate = datetime(),
u.lastModified = datetime()
RETURN u
"""
result = db.run_query(query, {'user_id': user_id})
if result:
# Log the deactivation
from CDocs.utils import audit_trail
audit_trail.log_event(
event_type="USER_DEACTIVATED",
user=user_id,
resource_uid=user_id,
resource_type="User",
details={"action": "deactivated_via_admin"}
)
return {"success": True, "message": "User deactivated successfully"}
else:
return {"success": False, "message": "User not found"}
except Exception as e:
logger.error(f"Error deleting user {user_id}: {e}")
return {"success": False, "message": f"Failed to deactivate user: {str(e)}"}
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 be deactivated. This should match the UID property of a User node in the Neo4j database.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys 'success' (boolean) and 'message' (string). On success, returns {'success': True, 'message': 'User deactivated successfully'}. On failure, returns {'success': False, 'message': <error description>} where the message explains why the operation failed (e.g., 'User not found' or an exception message).
Dependencies
CDocs.dbCDocs.utils.audit_traillogging
Required Imports
from typing import Dict, Any
from CDocs import db
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.utils import audit_trail
Condition: only when the user is successfully found and deactivated (lazy import inside the function)
Required (conditional)Usage Example
import logging
from typing import Dict, Any
from CDocs import db
# Ensure logger is configured
logger = logging.getLogger(__name__)
# Example usage
user_id_to_deactivate = "user-12345-abcde"
result = delete_user(user_id_to_deactivate)
if result['success']:
print(f"Success: {result['message']}")
else:
print(f"Error: {result['message']}")
# Example with error handling
try:
result = delete_user("invalid-user-id")
if not result['success']:
print(f"Deactivation failed: {result['message']}")
except Exception as e:
print(f"Unexpected error: {e}")
Best Practices
- This function implements soft-delete pattern - users are deactivated rather than deleted to preserve data integrity and audit history
- Always check the 'success' field in the returned dictionary before assuming the operation completed successfully
- The function logs all deactivation events to an audit trail for compliance and security tracking
- Ensure proper database connection is established before calling this function
- The function sets three properties on deactivation: active=false, deactivatedDate, and lastModified timestamps
- Consider implementing additional authorization checks before calling this function to ensure only authorized administrators can deactivate users
- The audit trail logs include event_type='USER_DEACTIVATED' which can be used for reporting and compliance purposes
- If you need to permanently delete users, create a separate function with appropriate safeguards and authorization requirements
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function delete_user_v1 61.3% similar
-
function update_user_v1 60.6% similar
-
function delete_node 55.9% similar
-
function delete_all_notifications 55.3% similar
-
function remove_user_document 54.2% similar