function create_document_share_link_v1
Creates a shareable link for a document stored in FileCloud with optional password protection, expiry date, and email notifications.
/tf/active/vicechatdev/CDocs single class/controllers/filecloud_controller.py
621 - 708
moderate
Purpose
This function enables users to generate secure, shareable links for documents in a FileCloud document management system. It supports various sharing configurations including view-only or download access, password protection, time-limited access, and automatic email notifications to specified recipients. The function also maintains an audit trail of sharing activities and enforces permission checks to ensure only authorized users can create shares.
Source Code
def create_document_share_link(
user: DocUser,
document_uid: str,
share_type: str = "view",
password: Optional[str] = None,
expiry_days: Optional[int] = None,
notify_emails: Optional[List[str]] = None,
version: Optional[str] = None
) -> Dict[str, Any]:
"""
Create a shareable link for a document in FileCloud.
Args:
user: User creating the share
document_uid: UID of the document
share_type: Type of share (view, download, etc.)
password: Optional password protection
expiry_days: Optional expiry period in days
notify_emails: Optional list of emails to notify
version: Optional specific version to share
Returns:
Dictionary with share information
Raises:
ResourceNotFoundError: If document not found
PermissionError: If user doesn't have permission
FileCloudError: If share creation fails
"""
# Get document instance
doc = ControlledDocument(uid=document_uid)
if not doc:
raise ResourceNotFoundError(f"Document not found: {document_uid}")
# Get file path
file_path = get_filecloud_document_path(doc, version)
try:
client = get_filecloud_client()
# Create share
result = client.create_document_share(
file_path=file_path,
share_type=share_type,
password=password,
expiry_days=expiry_days,
notify_emails=notify_emails
)
if not result.get('success', False):
logger.error(f"Failed to create share in FileCloud: {result.get('message', 'Unknown error')}")
raise FileCloudError(f"Failed to create share: {result.get('message', 'Unknown error')}")
share_url = result.get('share_url')
share_id = result.get('share_id')
# Log audit event
target_version = doc.get_version_by_number(version) if version else doc.current_version
if target_version:
audit_trail.log_version_event(
event_type="VERSION_SHARED",
user=user,
version_uid=target_version.uid,
details={
"file_path": file_path,
"share_type": share_type,
"share_url": share_url,
"share_id": share_id,
"has_password": password is not None,
"expiry_days": expiry_days,
"notify_emails": notify_emails
}
)
return {
"success": True,
"document_uid": document_uid,
"file_path": file_path,
"share_url": share_url,
"share_id": share_id,
"share_type": share_type,
"has_password": password is not None,
"expiry_days": expiry_days
}
except Exception as e:
logger.error(f"Error creating document share in FileCloud: {e}")
raise FileCloudError(f"Error creating document share: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
user |
DocUser | - | positional_or_keyword |
document_uid |
str | - | positional_or_keyword |
share_type |
str | 'view' | positional_or_keyword |
password |
Optional[str] | None | positional_or_keyword |
expiry_days |
Optional[int] | None | positional_or_keyword |
notify_emails |
Optional[List[str]] | None | positional_or_keyword |
version |
Optional[str] | None | positional_or_keyword |
Parameter Details
user: DocUser object representing the authenticated user creating the share. Must have SHARE_DOCUMENT permission. Used for audit logging and permission validation.
document_uid: Unique identifier (UID) string of the document to be shared. Must correspond to an existing ControlledDocument in the system.
share_type: Type of sharing access to grant. Default is 'view'. Common values include 'view' (read-only access) and 'download' (allows downloading). The exact supported values depend on FileCloud configuration.
password: Optional password string to protect the share link. If provided, recipients must enter this password to access the shared document. Pass None for no password protection.
expiry_days: Optional integer specifying the number of days until the share link expires. After expiry, the link becomes invalid. Pass None for no expiration.
notify_emails: Optional list of email address strings to notify about the share. These recipients will receive an email with the share link. Pass None or empty list for no notifications.
version: Optional version identifier string to share a specific document version. If None, shares the current version. Must match an existing version number for the document.
Return Value
Type: Dict[str, Any]
Returns a dictionary containing share creation results. Keys include: 'success' (bool, always True if no exception), 'document_uid' (str, the document UID), 'file_path' (str, FileCloud path to the document), 'share_url' (str, the generated shareable URL), 'share_id' (str, unique identifier for the share), 'share_type' (str, the type of share created), 'has_password' (bool, whether password protection is enabled), 'expiry_days' (int or None, expiration period).
Dependencies
loggingtypingCDocsFC_api
Required Imports
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, PermissionError
from FC_api import FileCloudAPI
Usage Example
from CDocs.models.user_extensions import DocUser
from typing import Dict, Any
# Assume user and document_uid are already obtained
user = DocUser.query.get(user_id)
document_uid = "doc-12345-abcde"
# Create a simple view-only share
result = create_document_share_link(
user=user,
document_uid=document_uid,
share_type="view"
)
print(f"Share URL: {result['share_url']}")
# Create a password-protected share with expiry and notifications
result = create_document_share_link(
user=user,
document_uid=document_uid,
share_type="download",
password="SecurePass123",
expiry_days=7,
notify_emails=["colleague@example.com", "manager@example.com"],
version="1.2"
)
print(f"Protected share created: {result['share_id']}")
print(f"Expires in {result['expiry_days']} days")
Best Practices
- Always ensure the user has SHARE_DOCUMENT permission before calling this function (enforced by decorator)
- Validate document_uid exists before calling to provide better error messages to users
- Use password protection for sensitive documents to add an extra security layer
- Set appropriate expiry_days for time-sensitive shares to limit exposure window
- Handle ResourceNotFoundError, PermissionError, and FileCloudError exceptions appropriately in calling code
- Store the returned share_id for future reference if you need to revoke or manage the share later
- When sharing specific versions, verify the version exists to avoid errors
- Consider rate limiting share creation to prevent abuse
- Log share creation events for compliance and security auditing (handled automatically by the function)
- Validate email addresses in notify_emails list before passing to prevent notification failures
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_document_share_link 96.7% similar
-
function manage_user_share_access_v1 75.0% similar
-
function get_document_share_url 72.8% similar
-
function manage_user_share_access 72.3% similar
-
function manage_user_share_access_v2 72.3% similar