🔍 Code Extractor

function set_document_permissions_in_filecloud

Maturity: 70

Sets user and group permissions for a document in FileCloud by updating access controls on the document's folder path and logging the permission changes to an audit trail.

File:
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
Lines:
651 - 722
Complexity:
moderate

Purpose

This function manages document-level access control in a FileCloud integration. It retrieves a controlled document by UID, determines its FileCloud folder path, applies user and group permissions through the FileCloud API, and creates an audit log entry. It's used in document management systems where fine-grained access control needs to be synchronized with FileCloud storage, typically called when administrators or document owners need to grant or revoke access to specific users or groups.

Source Code

def set_document_permissions_in_filecloud(
    user: DocUser,
    document_uid: str,
    user_permissions: Optional[Dict[str, List[str]]] = None,
    group_permissions: Optional[Dict[str, List[str]]] = None
) -> Dict[str, Any]:
    """
    Set permissions for a document in FileCloud.
    
    Args:
        user: User setting the permissions
        document_uid: UID of the document
        user_permissions: Dictionary mapping usernames to permission lists
        group_permissions: Dictionary mapping groups to permission lists
        
    Returns:
        Dictionary with permission update status
        
    Raises:
        ResourceNotFoundError: If document not found
        PermissionError: If user doesn't have permission
        FileCloudError: If permission update fails
    """
    # Get document instance
    doc = ControlledDocument(uid=document_uid)
    if not doc:
        raise ResourceNotFoundError(f"Document not found: {document_uid}")
    
    # Get document folder path
    _, folder_path = os.path.split(get_filecloud_document_path(doc))
    
    # Default empty dictionaries if not provided
    user_permissions = user_permissions or {}
    group_permissions = group_permissions or {}
    
    try:
        client = get_filecloud_client()
        
        # Set document permissions
        result = client.set_document_permissions(
            file_path=folder_path,
            users=user_permissions,
            groups=group_permissions
        )
        
        if not result.get('success', False):
            logger.error(f"Failed to set permissions in FileCloud: {result.get('message', 'Unknown error')}")
            raise FileCloudError(f"Failed to set permissions: {result.get('message', 'Unknown error')}")
        
        # Log audit event
        audit_trail.log_document_lifecycle_event(
            event_type="DOCUMENT_PERMISSIONS_UPDATED",
            user=user,
            document_uid=document_uid,
            details={
                "folder_path": folder_path,
                "user_permissions": user_permissions,
                "group_permissions": group_permissions
            }
        )
        
        return {
            "success": True,
            "document_uid": document_uid,
            "folder_path": folder_path,
            "user_permissions": user_permissions,
            "group_permissions": group_permissions
        }
        
    except Exception as e:
        logger.error(f"Error setting document permissions in FileCloud: {e}")
        raise FileCloudError(f"Error setting document permissions: {e}")

Parameters

Name Type Default Kind
user DocUser - positional_or_keyword
document_uid str - positional_or_keyword
user_permissions Optional[Dict[str, List[str]]] None positional_or_keyword
group_permissions Optional[Dict[str, List[str]]] None positional_or_keyword

Parameter Details

user: DocUser object representing the authenticated user performing the permission update. Must have MANAGE_DOCUMENT_PERMISSIONS permission (enforced by decorator). Used for audit logging.

document_uid: String containing the unique identifier of the document whose permissions are being modified. Must correspond to an existing ControlledDocument in the database.

user_permissions: Optional dictionary mapping FileCloud usernames (strings) to lists of permission strings (e.g., {'john.doe': ['read', 'write'], 'jane.smith': ['read']}). If None or not provided, defaults to empty dictionary, effectively removing all user-specific permissions.

group_permissions: Optional dictionary mapping FileCloud group names (strings) to lists of permission strings (e.g., {'engineering': ['read', 'write'], 'viewers': ['read']}). If None or not provided, defaults to empty dictionary, effectively removing all group-specific permissions.

Return Value

Type: Dict[str, Any]

Returns a dictionary with keys: 'success' (boolean, always True if no exception raised), 'document_uid' (string, echoes input document_uid), 'folder_path' (string, the FileCloud folder path where permissions were applied), 'user_permissions' (dict, the user permissions that were set), 'group_permissions' (dict, the group permissions that were set). This provides confirmation of what was applied.

Dependencies

  • logging
  • os
  • json
  • uuid
  • tempfile
  • typing
  • time
  • CDocs
  • CDocs.config
  • CDocs.models
  • CDocs.utils
  • CDocs.controllers

Required Imports

import logging
import os
from typing import Dict, List, Any, Optional
from CDocs.models.document import ControlledDocument
from CDocs.models.user_extensions import DocUser
from CDocs.utils import audit_trail
from CDocs.controllers import require_permission, log_controller_action, ResourceNotFoundError
from CDocs.utils.FC_api import FileCloudAPI

Usage Example

from CDocs.models.user_extensions import DocUser
from CDocs.controllers.document_controller import set_document_permissions_in_filecloud

# Assume user is authenticated and has MANAGE_DOCUMENT_PERMISSIONS
admin_user = DocUser.query.filter_by(username='admin').first()

# Set permissions for a document
user_perms = {
    'john.doe': ['read', 'write'],
    'jane.smith': ['read']
}
group_perms = {
    'engineering_team': ['read', 'write', 'delete'],
    'viewers': ['read']
}

try:
    result = set_document_permissions_in_filecloud(
        user=admin_user,
        document_uid='doc-12345-abcde',
        user_permissions=user_perms,
        group_permissions=group_perms
    )
    print(f"Permissions updated successfully: {result['success']}")
    print(f"Applied to folder: {result['folder_path']}")
except ResourceNotFoundError as e:
    print(f"Document not found: {e}")
except FileCloudError as e:
    print(f"FileCloud error: {e}")

Best Practices

  • Always handle ResourceNotFoundError when the document_uid doesn't exist in the database
  • Handle FileCloudError exceptions which can occur if FileCloud API is unavailable or returns errors
  • Ensure the calling user has MANAGE_DOCUMENT_PERMISSIONS permission (enforced by decorator but good to verify in calling code)
  • Pass empty dictionaries explicitly if you want to clear all permissions rather than relying on None defaults
  • Permission strings in the lists should match FileCloud's expected permission values (e.g., 'read', 'write', 'delete')
  • The function modifies permissions at the folder level in FileCloud, not individual files
  • All permission changes are logged to audit trail automatically for compliance tracking
  • Consider wrapping calls in try-except blocks to handle integration failures gracefully
  • The function returns the applied permissions for verification purposes - use this for confirmation UI

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_document_metadata_in_filecloud 74.2% similar

    Updates metadata for a document stored in FileCloud, merging new metadata with existing values and logging the update in an audit trail.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function delete_document_from_filecloud 73.8% similar

    Deletes a document and its associated folder from FileCloud storage, with permission checks, audit logging, and error handling.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function manage_user_share_access_v2 70.7% similar

    Manages user access permissions to a FileCloud document share, creating shares if needed and setting read-only or write access for specified users.

    From: /tf/active/vicechatdev/CDocs/controllers/permission_startup_check.py
  • function manage_user_share_access_v1 70.0% similar

    Manages user access permissions to a FileCloud document share, creating the share if needed and setting read-only or write access for a specified user.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function upload_document_to_filecloud 68.9% similar

    Uploads a document version to FileCloud storage system with metadata, handling file creation, folder structure, and audit logging.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
← Back to Browse