CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pycognito

Python class to integrate Boto3's Cognito client so it is easy to login users with SRP support.

Pending
Overview
Eval results
Files

group-management.mddocs/

Group Management

Group operations for AWS Cognito User Pools, including group retrieval, user group membership management, and administrative group operations. Groups provide a way to organize users and assign permissions or roles within your application.

Capabilities

Group Retrieval

Retrieve group information and list all groups in the user pool.

def get_group(self, group_name: str) -> GroupObj:
    """
    Get a specific group by name.
    
    Args:
        group_name (str): Name of the group to retrieve
        
    Returns:
        GroupObj: Group object with properties and metadata
        
    Raises:
        Exception: If group doesn't exist or access is denied
    """

def get_groups(self) -> list[GroupObj]:
    """
    Get all groups in the user pool.
    
    Returns:
        list[GroupObj]: List of all groups in the user pool
        
    Note:
        Returns empty list if no groups exist or user lacks permissions
    """

Usage Example:

from pycognito import Cognito

u = Cognito('your-user-pool-id', 'your-client-id')

# Get specific group
admin_group = u.get_group('administrators')
print(f"Group: {admin_group.group_name}")
print(f"Description: {admin_group.description}")
print(f"Precedence: {admin_group.precedence}")

# Get all groups
all_groups = u.get_groups()
print(f"Total groups: {len(all_groups)}")

for group in all_groups:
    print(f"- {group.group_name}: {group.description}")

User Group Membership

Manage user membership in groups using administrative operations.

def admin_add_user_to_group(self, username: str, group_name: str) -> None:
    """
    Add a user to a specific group.
    
    Args:
        username (str): Username to add to group
        group_name (str): Name of the group
        
    Requirements:
        - Group must exist in the user pool
        - User must exist in the user pool
        - Requires admin privileges on the user pool
        
    Actions:
        - Adds user to group membership
        - User inherits group permissions/roles
        - Multiple group memberships are allowed
    """

def admin_remove_user_from_group(self, username: str, group_name: str) -> None:
    """
    Remove a user from a specific group.
    
    Args:
        username (str): Username to remove from group
        group_name (str): Name of the group
        
    Actions:
        - Removes user from group membership
        - User loses group permissions/roles
        - Does not affect other group memberships
    """

def admin_list_groups_for_user(self, username: str) -> list[str]:
    """
    Get list of groups a user belongs to.
    
    Args:
        username (str): Username to check group membership for
        
    Returns:
        list[str]: List of group names the user belongs to
        
    Note:
        Handles pagination automatically for users with many group memberships
    """

Usage Example:

# Add user to groups
u.admin_add_user_to_group('john.doe', 'developers')
u.admin_add_user_to_group('john.doe', 'beta-testers')
print("User added to groups")

# Check user's group memberships
user_groups = u.admin_list_groups_for_user('john.doe')
print(f"User belongs to groups: {user_groups}")

# Remove user from a group
u.admin_remove_user_from_group('john.doe', 'beta-testers')
print("User removed from beta-testers group")

# Verify removal
updated_groups = u.admin_list_groups_for_user('john.doe')
print(f"Updated group memberships: {updated_groups}")

User Account Status Management

Enable and disable user accounts administratively.

def admin_enable_user(self, username: str) -> None:
    """
    Enable a user account.
    
    Args:
        username (str): Username to enable
        
    Actions:
        - Enables the user account for authentication
        - User can log in and access the application
        - Reverses previous admin_disable_user() call
        
    Use cases:
        - Re-enabling temporarily suspended accounts
        - Activating accounts after review
        - Bulk account management operations
    """

def admin_disable_user(self, username: str) -> None:
    """
    Disable a user account.
    
    Args:
        username (str): Username to disable
        
    Actions:
        - Disables the user account from authentication
        - User cannot log in but data is preserved
        - Existing sessions may continue until token expiry
        
    Use cases:
        - Temporary account suspension
        - Security incident response
        - Deactivating terminated employees
        
    Note:
        Disabled users retain all data and group memberships
    """

Usage Example:

# Disable problematic user account
u.admin_disable_user('problematic.user')
print("User account disabled")

# Later, re-enable the account
u.admin_enable_user('problematic.user')
print("User account re-enabled")

Group Object

The GroupObj class represents a Cognito group with properties and metadata.

class GroupObj:
    """Represents a Cognito user group."""
    
    def __init__(self, group_data: dict, cognito_obj: Cognito):
        """
        Initialize group object.
        
        Args:
            group_data (dict): Group data from AWS Cognito
            cognito_obj (Cognito): Parent Cognito instance
        """
    
    # Properties
    group_name: str           # Group name/identifier
    description: str          # Group description
    creation_date: datetime   # When group was created
    last_modified_date: datetime  # Last modification time
    role_arn: str            # IAM role ARN for group permissions
    precedence: int          # Group precedence (lower = higher priority)

Usage Example:

# Get group and examine properties
group = u.get_group('administrators')

print(f"Group Name: {group.group_name}")
print(f"Description: {group.description}")
print(f"Created: {group.creation_date}")
print(f"Modified: {group.last_modified_date}")
print(f"Role ARN: {group.role_arn}")
print(f"Precedence: {group.precedence}")

# Groups with lower precedence values have higher priority
if group.precedence < 10:
    print("This is a high-priority group")

Usage Patterns

User Role Management

def assign_user_role(username, role):
    """Assign user to role-based groups."""
    u = Cognito('pool-id', 'client-id')
    
    # Remove from all role groups first
    current_groups = u.admin_list_groups_for_user(username)
    role_groups = ['admin', 'manager', 'employee', 'guest']
    
    for group in current_groups:
        if group in role_groups:
            u.admin_remove_user_from_group(username, group)
    
    # Add to new role group
    if role in role_groups:
        u.admin_add_user_to_group(username, role)
        print(f"User {username} assigned role: {role}")
    else:
        print(f"Invalid role: {role}")

# Usage
assign_user_role('john.doe', 'manager')

Group-Based Access Control

def check_user_permissions(username, required_groups):
    """Check if user has required group memberships."""
    u = Cognito('pool-id', 'client-id')
    
    user_groups = u.admin_list_groups_for_user(username)
    
    # Check if user belongs to any required group
    has_access = any(group in user_groups for group in required_groups)
    
    return has_access, user_groups

def enforce_group_access(username, required_groups):
    """Enforce group-based access control."""
    has_access, user_groups = check_user_permissions(username, required_groups)
    
    if has_access:
        print(f"Access granted. User groups: {user_groups}")
        return True
    else:
        print(f"Access denied. User groups: {user_groups}, Required: {required_groups}")
        return False

# Usage
if enforce_group_access('john.doe', ['admin', 'manager']):
    # Grant access to admin functionality
    perform_admin_operation()

Bulk Group Management

def bulk_group_operations():
    """Perform bulk group management operations."""
    u = Cognito('pool-id', 'client-id')
    
    # Get all groups for overview
    all_groups = u.get_groups()
    print(f"Managing {len(all_groups)} groups:")
    
    for group in all_groups:
        print(f"- {group.group_name} (precedence: {group.precedence})")
    
    # Bulk user assignment
    new_employees = ['emp1', 'emp2', 'emp3']
    
    for username in new_employees:
        try:
            # Add to employee group
            u.admin_add_user_to_group(username, 'employees')
            
            # Add to department-specific group
            u.admin_add_user_to_group(username, 'engineering')
            
            print(f"Added {username} to employee groups")
            
        except Exception as e:
            print(f"Failed to add {username}: {e}")

bulk_group_operations()

Hierarchical Group Management

def manage_hierarchical_groups():
    """Manage groups with hierarchical permissions."""
    u = Cognito('pool-id', 'client-id')
    
    # Define group hierarchy (lower precedence = higher authority)
    group_hierarchy = {
        'super_admin': 1,
        'admin': 10,
        'manager': 20,
        'employee': 30,
        'guest': 40
    }
    
    def get_user_highest_role(username):
        """Get user's highest authority role."""
        user_groups = u.admin_list_groups_for_user(username)
        
        # Find lowest precedence (highest authority) group
        highest_precedence = float('inf')
        highest_role = 'guest'
        
        for group in user_groups:
            if group in group_hierarchy:
                precedence = group_hierarchy[group]
                if precedence < highest_precedence:
                    highest_precedence = precedence
                    highest_role = group
        
        return highest_role, highest_precedence
    
    def promote_user(username, new_role):
        """Promote user to higher role."""
        if new_role not in group_hierarchy:
            print(f"Invalid role: {new_role}")
            return
        
        current_role, current_precedence = get_user_highest_role(username)
        new_precedence = group_hierarchy[new_role]
        
        if new_precedence < current_precedence:
            # Remove from current role groups
            current_groups = u.admin_list_groups_for_user(username)
            for group in current_groups:
                if group in group_hierarchy:
                    u.admin_remove_user_from_group(username, group)
            
            # Add to new role group
            u.admin_add_user_to_group(username, new_role)
            print(f"Promoted {username} from {current_role} to {new_role}")
        else:
            print(f"Cannot promote {username} from {current_role} to {new_role}")
    
    # Usage
    promote_user('john.doe', 'manager')
    
    # Check final role
    role, precedence = get_user_highest_role('john.doe')
    print(f"John's current role: {role} (precedence: {precedence})")

manage_hierarchical_groups()

Group Audit and Reporting

def generate_group_report():
    """Generate comprehensive group membership report."""
    u = Cognito('pool-id', 'client-id')
    
    # Get all groups
    all_groups = u.get_groups()
    
    # Get all users
    all_users = u.get_users()
    
    print("=== GROUP MEMBERSHIP REPORT ===\n")
    
    # Report by group
    print("GROUPS AND THEIR MEMBERS:")
    for group in all_groups:
        print(f"\n{group.group_name} ({group.description})")
        print(f"  Created: {group.creation_date}")
        print(f"  Precedence: {group.precedence}")
        
        # Find members (this requires checking each user)
        members = []
        for user in all_users:
            user_groups = u.admin_list_groups_for_user(user.username)
            if group.group_name in user_groups:
                members.append(user.username)
        
        print(f"  Members ({len(members)}): {', '.join(members) if members else 'None'}")
    
    # Report by user
    print("\n\nUSERS AND THEIR GROUPS:")
    for user in all_users:
        user_groups = u.admin_list_groups_for_user(user.username)
        print(f"{user.username}: {', '.join(user_groups) if user_groups else 'No groups'}")

generate_group_report()

Install with Tessl CLI

npx tessl i tessl/pypi-pycognito

docs

authentication.md

device-authentication.md

group-management.md

http-integration.md

index.md

mfa.md

password-management.md

srp-authentication.md

user-management.md

tile.json