🔍 Code Extractor

function user_has_permission_for_resource

Maturity: 52

Checks if a user has a specific permission for a resource, considering both general permissions and resource-specific ownership/creator rights.

File:
/tf/active/vicechatdev/CDocs/config/permissions.py
Lines:
176 - 221
Complexity:
moderate

Purpose

This function implements a hierarchical permission checking system that first validates general user permissions, then checks resource-specific permissions based on ownership or creator status. It's designed for access control in document management systems where users may have permissions through general roles or through their relationship to specific resources (owner/creator). The function provides special handling for EDIT_DOCUMENT and CREATE_VERSION permissions for resource owners and creators.

Source Code

def user_has_permission_for_resource(user, permission_name, resource=None):
    """
    Check if a user has a specific permission for a particular resource.
    
    Args:
        user: The user to check permissions for
        permission_name: The name of the permission to check
        resource: The resource (e.g., a document) to check permissions for
        
    Returns:
        bool: True if the user has the permission, False otherwise
    """
    # First check if user has general permission
    if user_has_permission(user, permission_name):
        return True
        
    # If resource is provided, check resource-specific permissions
    if resource:
        # Check if user is the owner of the resource
        resource_owner = None
        if hasattr(resource, 'owner_uid'):
            resource_owner = resource.owner_uid
        elif hasattr(resource, 'get') and callable(resource.get):
            resource_owner = resource.get('owner_uid')
            
        if resource_owner and resource_owner == user.uid:
            # Resource owners can edit their own resources
            if permission_name in ["EDIT_DOCUMENT", "CREATE_VERSION"]:
                logger.debug(f"Permission {permission_name} granted as resource owner")
                return True
                
        # Check if user is the creator of the resource
        resource_creator = None
        if hasattr(resource, 'creator_uid'):
            resource_creator = resource.creator_uid
        elif hasattr(resource, 'get') and callable(resource.get):
            resource_creator = resource.get('creator_uid')
            
        if resource_creator and resource_creator == user.uid:
            # Resource creators can edit their own resources
            if permission_name in ["EDIT_DOCUMENT", "CREATE_VERSION"]:
                logger.debug(f"Permission {permission_name} granted as resource creator")
                return True
    
    # Default to false for safety
    return False

Parameters

Name Type Default Kind
user - - positional_or_keyword
permission_name - - positional_or_keyword
resource - None positional_or_keyword

Parameter Details

user: The user object to check permissions for. Must have a 'uid' attribute for resource ownership comparison. Expected to be compatible with the user_has_permission function.

permission_name: String representing the permission to check (e.g., 'EDIT_DOCUMENT', 'CREATE_VERSION'). This is checked against both general permissions and resource-specific permissions.

resource: Optional resource object (e.g., a document) to check permissions against. Can be None for general permission checks. Should have 'owner_uid' and/or 'creator_uid' attributes, or be a dict-like object with a 'get' method that can retrieve these values.

Return Value

Returns a boolean value: True if the user has the specified permission (either through general permissions or resource-specific ownership/creator rights), False otherwise. Defaults to False for safety when no permission conditions are met.

Dependencies

  • logging

Required Imports

import logging

Usage Example

# Assuming user_has_permission function and logger are defined
import logging

logger = logging.getLogger(__name__)

def user_has_permission(user, permission_name):
    return permission_name in user.permissions

class User:
    def __init__(self, uid, permissions):
        self.uid = uid
        self.permissions = permissions

class Document:
    def __init__(self, owner_uid, creator_uid):
        self.owner_uid = owner_uid
        self.creator_uid = creator_uid

# Create user and document
user = User(uid='user123', permissions=['READ_DOCUMENT'])
document = Document(owner_uid='user123', creator_uid='user456')

# Check if user can edit their own document
can_edit = user_has_permission_for_resource(user, 'EDIT_DOCUMENT', document)
print(f"Can edit: {can_edit}")  # True (user is owner)

# Check general permission
can_read = user_has_permission_for_resource(user, 'READ_DOCUMENT', document)
print(f"Can read: {can_read}")  # True (has general permission)

# Check without resource
can_delete = user_has_permission_for_resource(user, 'DELETE_DOCUMENT')
print(f"Can delete: {can_delete}")  # False (no general permission)

Best Practices

  • Always provide a user object with a valid 'uid' attribute for proper ownership comparison
  • The function defaults to False for safety, ensuring restrictive access control by default
  • Resource objects should implement either direct attributes (owner_uid, creator_uid) or a dict-like interface with a 'get' method
  • The function depends on an external 'user_has_permission' function that must be defined in the same scope
  • A 'logger' object must be available in the module scope for debug logging to work
  • Currently only EDIT_DOCUMENT and CREATE_VERSION permissions are granted to owners/creators; extend this list as needed for your use case
  • Consider the order of checks: general permissions are checked first, then ownership, then creator status
  • The function uses early returns for efficiency, stopping checks as soon as permission is granted

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function user_has_permission 83.2% similar

    Validates whether a user has one or more specified permissions based on their assigned roles and a role-permission mapping configuration.

    From: /tf/active/vicechatdev/CDocs/config/permissions.py
  • function check_document_permission 78.1% similar

    Validates whether a user has specific permission(s) to access or modify a document based on their roles, ownership status, and configured role permissions.

    From: /tf/active/vicechatdev/CDocs/config/permissions.py
  • function require_permission 65.7% similar

    A decorator function that enforces permission-based access control by checking if a user has required permissions before executing the decorated function.

    From: /tf/active/vicechatdev/CDocs/controllers/__init__.py
  • function get_user_permissions 58.5% similar

    Retrieves all permissions for a user by aggregating permissions from their assigned roles, with fallback to default USER role permissions.

    From: /tf/active/vicechatdev/CDocs/config/permissions.py
  • function get_user_access_url 52.8% 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
← Back to Browse