Python class to integrate Boto3's Cognito client so it is easy to login users with SRP support.
—
Comprehensive user management operations for AWS Cognito User Pools, including user registration, profile management, user retrieval, deletion, and administrative user operations. Supports both user-level operations (using access tokens) and admin-level operations (using admin privileges).
Register new users in the Cognito User Pool with attributes and optional email/SMS verification.
def register(self, username: str, password: str, attr_map: dict = None, client_metadata: dict = None) -> dict:
"""
Register a new user in the user pool.
Args:
username (str): Unique username for the user
password (str): User's password (must meet pool requirements)
attr_map (dict, optional): Map custom attribute names to Cognito attributes
client_metadata (dict, optional): Custom workflow metadata
Returns:
dict: Registration response with confirmation details
{
'UserConfirmed': bool,
'CodeDeliveryDetails': {
'Destination': str, # Obfuscated email/phone
'DeliveryMedium': str, # 'SMS' or 'EMAIL'
'AttributeName': str
}
}
Note:
Use set_base_attributes() and add_custom_attributes() before calling
to set user attributes during registration.
"""
def set_base_attributes(self, **kwargs) -> None:
"""
Set base user attributes for registration and updates.
Args:
**kwargs: Attribute name-value pairs
Common attributes:
- email: Email address
- given_name: First name
- family_name: Last name
- phone_number: Phone number (+1234567890 format)
- birthdate: Birth date (YYYY-MM-DD)
- gender: Gender
- locale: Locale preference
- picture: Profile picture URL
- website: Website URL
"""
def add_custom_attributes(self, **kwargs) -> None:
"""
Add custom attributes with 'custom:' prefix.
Args:
**kwargs: Custom attribute name-value pairs
Note:
Custom attributes must be defined in the User Pool schema
and the client must have write permissions for them.
"""Usage Example:
from pycognito import Cognito
u = Cognito('your-user-pool-id', 'your-client-id')
# Set user attributes
u.set_base_attributes(
email='user@example.com',
given_name='John',
family_name='Doe',
phone_number='+1234567890'
)
# Add custom attributes
u.add_custom_attributes(
company='ACME Corp',
role='developer'
)
# Register user
response = u.register('johndoe', 'SecurePassword123!')
if not response['UserConfirmed']:
print(f"Confirmation code sent via {response['CodeDeliveryDetails']['DeliveryMedium']}")Confirm user registration using verification codes sent via email or SMS.
def confirm_sign_up(self, confirmation_code: str, username: str = None) -> None:
"""
Confirm user registration using verification code.
Args:
confirmation_code (str): Code sent via email/SMS
username (str, optional): Username to confirm (uses instance username if not provided)
"""
def admin_confirm_sign_up(self, username: str = None) -> None:
"""
Admin confirm user registration without verification code.
Args:
username (str, optional): Username to confirm (uses instance username if not provided)
Note:
Requires admin privileges on the user pool.
"""
def resend_confirmation_code(self, username: str) -> None:
"""
Resend the confirmation code to the user.
Args:
username (str): Username to resend code for
"""Usage Example:
# Confirm registration with code
u.confirm_sign_up('123456', username='johndoe')
# Or admin confirm without code
u.admin_confirm_sign_up(username='johndoe')
# Resend confirmation if needed
u.resend_confirmation_code('johndoe')Retrieve user information and attributes using different access levels.
def get_user(self, attr_map: dict = None) -> UserObj:
"""
Get current user information using access token.
Args:
attr_map (dict, optional): Map Cognito attributes to custom names
Returns:
UserObj: User object with attributes and methods
Requires:
Valid access token (user must be authenticated)
"""
def admin_get_user(self, attr_map: dict = None) -> UserObj:
"""
Get user information using admin privileges.
Args:
attr_map (dict, optional): Map Cognito attributes to custom names
Returns:
UserObj: User object with additional admin metadata
Additional metadata includes:
- enabled: Whether user account is enabled
- user_status: User status (CONFIRMED, UNCONFIRMED, etc.)
- create_date: Account creation date
- modified_date: Last modification date
"""
def get_users(self, attr_map: dict = None) -> list[UserObj]:
"""
Get all users in the user pool (admin operation).
Args:
attr_map (dict, optional): Map Cognito attributes to custom names
Returns:
list[UserObj]: List of all users in the pool
Note:
Handles pagination automatically for large user pools.
"""Usage Example:
# Get current authenticated user
user = u.get_user()
print(f"Username: {user.username}")
print(f"Email: {user.email}")
print(f"Name: {user.given_name} {user.family_name}")
# Get user with admin privileges
admin_user = u.admin_get_user()
print(f"User status: {admin_user.user_status}")
print(f"Account enabled: {admin_user.enabled}")
# Get all users (admin operation)
all_users = u.get_users()
print(f"Total users: {len(all_users)}")Update user attributes and profile information.
def update_profile(self, attrs: dict, attr_map: dict = None) -> None:
"""
Update user attributes using access token.
Args:
attrs (dict): Attribute name-value pairs to update
attr_map (dict, optional): Map custom names to Cognito attributes
Note:
User must be authenticated. Some attributes may require verification.
"""
def admin_update_profile(self, attrs: dict, attr_map: dict = None) -> None:
"""
Update user attributes using admin privileges.
Args:
attrs (dict): Attribute name-value pairs to update
attr_map (dict, optional): Map custom names to Cognito attributes
Note:
Can update any user attribute without requiring user authentication.
"""Usage Example:
# Update user profile (requires authentication)
u.update_profile({
'given_name': 'Jane',
'family_name': 'Smith',
'phone_number': '+9876543210'
})
# Admin update (no authentication required)
u.admin_update_profile({
'email': 'newemail@example.com',
'email_verified': True
})Create users with administrative privileges, including temporary passwords and custom attributes.
def admin_create_user(self, username: str, temporary_password: str = "",
additional_kwargs: dict = None, attr_map: dict = None, **kwargs) -> dict:
"""
Create a user using admin privileges.
Args:
username (str): Username for the new user
temporary_password (str, optional): Temporary password (Cognito generates one if empty)
additional_kwargs (dict, optional): Additional AWS parameters (e.g., MessageAction)
attr_map (dict, optional): Map custom attribute names to Cognito attributes
**kwargs: User attributes (email, given_name, etc.)
Returns:
dict: User creation response with user details
Common additional_kwargs:
- MessageAction: 'SUPPRESS' to skip welcome message
- ForceAliasCreation: True to allow email/phone reuse
"""Usage Example:
# Create user with temporary password
response = u.admin_create_user(
username='newuser',
temporary_password='TempPass123!',
email='newuser@example.com',
given_name='New',
family_name='User',
additional_kwargs={'MessageAction': 'SUPPRESS'}
)
print(f"User created: {response['User']['Username']}")Delete user accounts with user-level or admin-level operations.
def delete_user(self) -> None:
"""
Delete the current authenticated user.
Note:
User must be authenticated. This is irreversible.
"""
def admin_delete_user(self) -> None:
"""
Delete user using admin privileges.
Note:
Uses the username set on the Cognito instance.
This is irreversible.
"""Usage Example:
# User deletes their own account
u.delete_user()
# Admin deletes a user account
u = Cognito('pool-id', 'client-id', username='user-to-delete')
u.admin_delete_user()Enable, disable, and manage user account status.
def admin_enable_user(self, username: str) -> None:
"""
Enable a user account.
Args:
username (str): Username to enable
"""
def admin_disable_user(self, username: str) -> None:
"""
Disable a user account.
Args:
username (str): Username to disable
Note:
Disabled users cannot authenticate but their data is preserved.
"""Usage Example:
# Disable user account
u.admin_disable_user('problematic-user')
# Re-enable user account
u.admin_enable_user('problematic-user')Work with UserObj instances for convenient user operations.
class UserObj:
"""User object with attributes and convenience methods."""
# Properties
username: str
sub: str # User's unique subject ID
email_verified: bool
phone_number_verified: bool
def save(self, admin: bool = False) -> None:
"""
Save user attribute changes.
Args:
admin (bool): Use admin privileges for update
"""
def delete(self, admin: bool = False) -> None:
"""
Delete this user.
Args:
admin (bool): Use admin privileges for deletion
"""Usage Example:
# Get user and modify attributes
user = u.get_user()
user.given_name = 'Updated Name'
user.save() # Save changes
# Delete user through object
user.delete() # User-level deletion
# or
user.delete(admin=True) # Admin-level deletionfrom pycognito import Cognito
# Registration
u = Cognito('pool-id', 'client-id')
u.set_base_attributes(email='user@example.com', given_name='John')
response = u.register('johndoe', 'Password123!')
if not response['UserConfirmed']:
# Handle confirmation
code = input("Enter confirmation code: ")
u.confirm_sign_up(code, 'johndoe')
print("User registered and confirmed!")# Create and manage users as admin
u = Cognito('pool-id', 'client-id')
# Create user
u.admin_create_user(
username='employee1',
email='emp1@company.com',
given_name='Employee',
family_name='One'
)
# Update user
u.admin_update_profile({'department': 'Engineering'})
# List all users
users = u.get_users()
for user in users:
print(f"{user.username}: {user.email}")# Authenticated user updates profile
u = Cognito('pool-id', 'client-id', username='user')
u.authenticate(password='password')
# Get current profile
user = u.get_user()
print(f"Current email: {user.email}")
# Update profile
u.update_profile({
'given_name': 'Updated',
'phone_number': '+1234567890'
})
# Verify changes
updated_user = u.get_user()
print(f"New name: {updated_user.given_name}")Install with Tessl CLI
npx tessl i tessl/pypi-pycognito