function manage_user_share_access
Manages user access permissions (read-only or edit) to a specific document version share in FileCloud, creating the share if it doesn't exist.
/tf/active/vicechatdev/CDocs/controllers/filecloud_helper.py
16 - 152
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
loggingtypingCDocs.models.documentCDocs.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function manage_user_share_access_v1 98.2% similar
-
function manage_user_share_access_v2 97.6% similar
-
function get_user_access_url 77.5% similar
-
function remove_user_access 76.4% similar
-
function manage_document_permissions 73.3% similar