function manage_user_share_access_v1
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.
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
819 - 960
complex
Purpose
This function ensures proper access control for document sharing in FileCloud. It handles the complete workflow of: (1) creating a document share if one doesn't exist, (2) adding a user to the share if not already present, and (3) setting appropriate access permissions (read-only or write). It's designed for document management systems that need to control user access to versioned documents stored in FileCloud.
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
# 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'
}
# 1. First check if user is already in the share
user_exists_in_share = False
users_result = fc_client.get_users_for_share(share_id=share_id)
if users_result.get('success', False):
# Extract users from the result
if 'data' in users_result and 'users' in users_result['data']:
users = users_result['data']['users']
if isinstance(users, list):
for user in users:
if user.get('userid') == user_id or user.get('email') == user_id:
user_exists_in_share = True
logger.info(f"User {user_id} already exists in share {share_id}")
break
# 2. Add user to share if not already added
if not user_exists_in_share:
# Add user to share first - using the correct parameter name 'user_id'
add_result = fc_client.add_user_to_share(
user_id=user_id, # Correct parameter name
share_id=share_id # Correct parameter name
)
if not add_result.get('success', False):
logger.error(f"Failed to add user to share: {add_result.get('message', 'Unknown error')}")
return {
'success': False,
'message': f"Failed to add user to share: {add_result.get('message', 'Unknown error')}"
}
# 3. Set appropriate access rights (regardless of whether user was just added or already existed)
# Use the set_user_access_for_share method to grant appropriate permissions
perm_result = fc_client.set_user_access_for_share(
share_id=share_id,
user_id=user_id,
write=grant_write_access, # Set write permission based on grant_write_access parameter
download=True, # Always allow download
share=False # Don't allow resharing by default
)
if not perm_result.get('success', False):
logger.warning(f"Set user access permissions failed: {perm_result.get('message', 'Unknown error')}")
# Continue despite permission setting issues - at least user has basic access
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),
'share_id': share_id,
'user_id': user_id,
'permission': "write" if grant_write_access else "read"
}
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_id/share_url if they don't exist.
user_id: String identifier for the user, typically their email address, which serves as the FileCloud user identifier. This is used to add the user to the share and set their permissions.
grant_write_access: Boolean flag determining permission level. If True, grants write/edit access to the document; if False (default), grants read-only access. Download permission is always granted regardless of this setting.
Return Value
Type: Dict[str, Any]
Returns a dictionary with keys: 'success' (bool indicating operation success), 'message' (str with descriptive information about the operation result), 'share_url' (str URL to access the document, present on success), 'share_id' (str FileCloud share identifier, present on success), 'user_id' (str echoed user identifier, present on success), and 'permission' (str either 'write' or 'read', present on success). On failure, only 'success' (False) and 'message' (error description) are guaranteed.
Dependencies
loggingCDocs.dbCDocs.config.settingsCDocs.models.document.DocumentVersionCDocs.utils.FC_api.FileCloudAPICDocs.controllers.log_controller_action
Required Imports
import logging
from typing import Dict, Any
from CDocs.models.document import DocumentVersion
from CDocs.controllers import log_controller_action
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.utils.FC_api import FileCloudAPI
Condition: Required for FileCloud client operations via get_filecloud_client() function
Required (conditional)from CDocs.controllers.document_controller import create_document_share_link
Condition: Required when document_version doesn't have a share_id and a new share needs to be created
Required (conditional)Usage Example
from CDocs.models.document import DocumentVersion
from CDocs.controllers.document_controller import manage_user_share_access
# Get a document version instance (from database query)
doc_version = DocumentVersion.query.filter_by(id=123).first()
# 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"User granted access: {result['share_url']}")
print(f"Permission level: {result['permission']}")
else:
print(f"Failed: {result['message']}")
# Grant write access to another user
write_result = manage_user_share_access(
document_version=doc_version,
user_id='editor@example.com',
grant_write_access=True
)
if write_result['success']:
print(f"Editor access granted with permission: {write_result['permission']}")
Best Practices
- Always check the 'success' key in the returned dictionary before accessing other keys like 'share_url' or 'share_id'
- The function handles share creation automatically if share_id doesn't exist, but ensure the document_version has a valid 'document' relationship
- User identification relies on email addresses matching FileCloud user IDs - ensure consistency in user identifier format
- The function continues execution even if permission setting fails after user is added, providing partial success - check the message for warnings
- Download permission is always granted regardless of grant_write_access setting; resharing is always disabled by default
- The function modifies the document_version object by adding/updating share_id and share_url attributes and calling save() - ensure proper transaction handling in calling code
- Error handling is comprehensive but logs errors - ensure proper logging configuration for troubleshooting
- The function is decorated with @log_controller_action - ensure this decorator is properly configured in your environment
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function manage_user_share_access 98.2% similar
-
function manage_user_share_access_v2 97.2% similar
-
function get_user_access_url 75.3% similar
-
function remove_user_access 74.8% similar
-
function manage_document_permissions 74.2% similar