🔍 Code Extractor

function manage_user_share_access

Maturity: 71

Manages user access permissions (read-only or edit) to a specific document version share in FileCloud, creating the share if it doesn't exist.

File:
/tf/active/vicechatdev/CDocs/controllers/filecloud_helper.py
Lines:
16 - 152
Complexity:
complex

Purpose

This function provides a comprehensive solution for managing user access to document shares in FileCloud. It handles the entire lifecycle: checking if a share exists for a document version, creating one if needed, and then granting or updating the specified user's access permissions (view or edit). It's designed to be used in document collaboration workflows where different users need different levels of access to specific document versions.

Source Code

def manage_user_share_access(
    document_version: DocumentVersion,
    user_id: str,
    grant_write_access: bool = False
) -> Dict[str, Any]:
    """
    Manage a user's access to a document share in FileCloud.
    
    This function ensures the user has appropriate access (read-only or edit)
    to a document share in FileCloud based on their role and document status.
    
    Args:
        document_version: The document version to share
        user_id: User's email address (used as FileCloud identifier)
        grant_write_access: Whether to grant write access (True) or read-only (False)
        
    Returns:
        Dict with result information:
            - success: Boolean indicating success
            - message: Additional information message
            - share_url: URL to access the document (if successful)
    """
    try:
        # Get FileCloud client
        fc_client = get_filecloud_client()
        if not fc_client:
            logger.error("Could not get FileCloud client")
            return {
                'success': False,
                'message': 'FileCloud connection not available'
            }
        
        # Check if share_id attribute exists, if not, initialize it
        if not hasattr(document_version, 'share_id') or not document_version.share_id:
            # Either attribute missing or it's None/empty - create a new share
            from CDocs.controllers.filecloud_controller import create_document_share_link
            

            # Get document
            doc = document_version.document
            if not doc:
                logger.error("Could not get document from version")
                return {
                    'success': False,
                    'message': 'Document not found for version'
                }
            
            # Create share as a system operation (no user required)
            share_result = create_document_share_link(
                document=doc,  # Pass document object directly
                user=None,  # System operation
                version=document_version.version_number
            )
            
            if not share_result.get('success', False):
                logger.error(f"Failed to create share: {share_result.get('message')}")
                return {
                    'success': False,
                    'message': f"Failed to create share: {share_result.get('message')}"
                }
            
            # Update document version with share information
            # Add share_id and share_url attributes if they don't exist yet
            if not hasattr(document_version, 'share_id'):
                setattr(document_version, 'share_id', share_result.get('share_id'))
            else:
                document_version.share_id = share_result.get('share_id')
                
            if not hasattr(document_version, 'share_url'):
                setattr(document_version, 'share_url', share_result.get('share_url'))
            else:
                document_version.share_url = share_result.get('share_url')
                
            document_version.save()
        
        # Get the share ID safely
        share_id = getattr(document_version, 'share_id', None)
        
        
        if not share_id:
            logger.error("No share ID available for document version")
            return {
                'success': False,
                'message': 'No share ID available for document'
            }
        
        # Add or update user's access to the share
        try:
            if grant_write_access:
                # Add with edit access
                result = fc_client.add_user_to_share(
                    user_email=user_id,  # Use email as identifier
                    share_id=share_id,
                    permission="edit"
                )
            else:
                # Add with view-only access
                result = fc_client.add_user_to_share(
                    user_email=user_id,  # Use email as identifier
                    share_id=share_id,
                    permission="view"
                )
        except Exception as e:
            logger.error(f"Error adding user to share: {str(e)}")
            # Try alternative parameter names
            if grant_write_access:
                result = fc_client.add_user_to_share(
                    user_id=user_id,
                    share_id=share_id,
                    permissions="write"
                )
            else:
                result = fc_client.add_user_to_share(
                    user_id=user_id,
                    share_id=share_id,
                    permissions="read"
                )
        
        if not result.get('success', False):
            logger.error(f"Failed to manage user access: {result.get('message')}")
            return {
                'success': False,
                'message': f"Failed to set user access: {result.get('message')}"
            }
        
        return {
            'success': True,
            'message': f"User access {'with edit rights' if grant_write_access else 'read-only'} set successfully",
            'share_url': getattr(document_version, 'share_url', None)
        }
        
    except Exception as e:
        logger.error(f"Error managing user share access: {str(e)}")
        return {
            'success': False,
            'message': f"Error: {str(e)}"
        }

Parameters

Name Type Default Kind
document_version DocumentVersion - positional_or_keyword
user_id str - positional_or_keyword
grant_write_access bool False positional_or_keyword

Parameter Details

document_version: A DocumentVersion model instance representing the specific version of a document to be shared. Must have attributes like 'document', 'version_number', and optionally 'share_id' and 'share_url'. The function will create and populate share attributes if they don't exist.

user_id: The user's email address, which serves as their FileCloud identifier. This is used to grant or update access permissions for the specific user in the FileCloud system.

grant_write_access: Boolean flag determining the permission level. If True, grants edit/write access to the document share. If False (default), grants read-only/view access. This allows fine-grained control over user permissions.

Return Value

Type: Dict[str, Any]

Returns a dictionary with three keys: 'success' (boolean indicating whether the operation succeeded), 'message' (string with detailed information about the operation result or error details), and 'share_url' (string URL to access the document, only present if successful). Example success: {'success': True, 'message': 'User access with edit rights set successfully', 'share_url': 'https://...'}, Example failure: {'success': False, 'message': 'FileCloud connection not available'}

Dependencies

  • logging
  • typing
  • CDocs.models.document
  • CDocs.controllers.filecloud_controller

Required Imports

import logging
from typing import Dict, Any
from CDocs.models.document import DocumentVersion
from CDocs.controllers.filecloud_controller import get_filecloud_client

Conditional/Optional Imports

These imports are only needed under specific conditions:

from CDocs.controllers.filecloud_controller import create_document_share_link

Condition: only when document_version does not have a share_id attribute or it is None/empty, triggering share creation

Required (conditional)

Usage Example

from CDocs.models.document import DocumentVersion
from manage_user_share_access import manage_user_share_access

# Get a document version instance (from database)
doc_version = DocumentVersion.objects.get(id=123)

# Grant read-only access to a user
result = manage_user_share_access(
    document_version=doc_version,
    user_id='user@example.com',
    grant_write_access=False
)

if result['success']:
    print(f"Access granted! Share URL: {result['share_url']}")
    print(result['message'])
else:
    print(f"Failed: {result['message']}")

# Grant edit access to another user
edit_result = manage_user_share_access(
    document_version=doc_version,
    user_id='editor@example.com',
    grant_write_access=True
)

if edit_result['success']:
    print(f"Edit access granted: {edit_result['message']}")

Best Practices

  • Always check the 'success' key in the returned dictionary before proceeding with operations
  • Handle the case where FileCloud client is unavailable gracefully in your application
  • The function automatically creates a share if one doesn't exist, so ensure the document_version.document relationship is properly loaded
  • User email addresses must be valid FileCloud user identifiers; ensure users exist in FileCloud before calling this function
  • The function uses fallback parameter names (user_email/user_id, permission/permissions) to handle different FileCloud API versions
  • Ensure proper error logging is configured as the function logs errors extensively
  • The function modifies the document_version object by adding/updating share_id and share_url attributes and saves it to the database
  • Consider wrapping calls in a try-except block for additional error handling at the application level
  • Be aware that this function performs database writes (document_version.save()) which may have transaction implications

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function manage_user_share_access_v1 98.2% 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 manage_user_share_access_v2 97.6% 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 get_user_access_url 77.5% similar

    Retrieves a share URL for a document version and determines the appropriate access level (read/write) for a specific user based on their role (owner, author, reviewer, approver) and the document's current status.

    From: /tf/active/vicechatdev/CDocs/controllers/share_controller.py
  • function remove_user_access 76.4% similar

    Removes a user's access permissions from a specific document version share in FileCloud by delegating to the FileCloud client's remove_user_from_share method.

    From: /tf/active/vicechatdev/CDocs/controllers/share_controller.py
  • function manage_document_permissions 73.3% similar

    Comprehensive function to manage document sharing and user permissions. This function: 1. Creates a share only if needed for active users 2. Adds/updates users with appropriate permissions based on their roles 3. Removes users who shouldn't have access anymore 4. Cleans up shares that are no longer needed 5. Manages ACL entries for write permissions on the document's folder Args: document: The document to manage permissions for Returns: Dict: Result of permission updates with detailed information

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