Managing Users

Master AuthTuna's user management system — from registration to lifecycle management

The Heart of Your Application

Users are the foundation of your application's identity system. AuthTuna provides comprehensive user management capabilities that handle everything from registration and authentication to account lifecycle management, all with built-in security, audit trails, and compliance features.

User CRUD

Complete create, read, update, delete operations with validation and error handling.

Password Management

Secure password handling with hashing, validation, and audit logging.

Account Control

Suspend, unsuspend, and manage user account states with proper authorization.

Advanced Search

Powerful filtering and search capabilities for user discovery and management.

Creating & Retrieving Users

User creation involves validation, security checks, and audit logging. AuthTuna ensures data integrity and provides multiple ways to retrieve user information.

User Properties

Required Fields

  • id - Auto-generated unique identifier
  • email - Valid email address
  • username - Unique username

Optional Fields

  • password - User password (hashed)
  • is_active - Account status
  • email_verified - Email verification status
  • • Custom fields via kwargs

Creating Users

from authtuna.integrations import auth_service

user_manager = auth_service.users

# Create a user with password
new_user = await user_manager.create(
    email="[email protected]",
    username="johndoe",
    password="secure_password_123",
    ip_address="192.168.1.100"
)

# Create a user without password (for OAuth/social login)
oauth_user = await user_manager.create(
    email="[email protected]",
    username="janesmith",
    ip_address="192.168.1.100"
)

print(f"Created user: {new_user.id}")

Retrieving Users

# Get user by ID (with roles and permissions)
user = await user_manager.get_by_id("user_123", with_relations=True)

# Get user by email
user_by_email = await user_manager.get_by_email("[email protected]")

# Get user by username
user_by_username = await user_manager.get_by_username("johndoe")

# List users with pagination
users = await user_manager.list(skip=0, limit=50)

# Check if user exists
if user:
    print(f"Found user: {user.username} - {user.email}")
    print(f"Roles: {[role.name for role in user.roles]}")
else:
    print("User not found")

✅ Validation & Security

  • • Email format validation
  • • Username uniqueness checks
  • • Password strength requirements
  • • Automatic audit logging
  • • IP address tracking

❌ Common Errors

  • • Duplicate email/username
  • • Invalid email format
  • • Weak password
  • • Missing required fields

Updating & Managing User Accounts

AuthTuna provides comprehensive user account management with secure updates, password management, and account state control.

Updating User Information

# Update user profile information
updated_user = await user_manager.update(
    user_id="user_123",
    update_data={
        "username": "new_username",
        "email_verified": True,
        "last_login": datetime.now()
    },
    ip_address="192.168.1.100"
)

# Only certain fields can be updated
# Protected fields: id, password_hash

Password Management

# Set a new password for a user
await user_manager.set_password(
    user_id="user_123",
    new_password="new_secure_password_456",
    ip_address="192.168.1.100"
)

# Passwords are automatically hashed
# Previous passwords are invalidated
# Audit trail is created

Account Suspension & Activation

Suspending Users

# Suspend a user account
suspended_user = await user_manager.suspend_user(
    user_id="user_123",
    admin_id="admin_456",
    reason="Violation of terms of service"
)

# User cannot log in while suspended
# All active sessions are invalidated
# Reason is logged for audit purposes

Reactivating Users

# Unsuspend a user account
reactivated_user = await user_manager.unsuspend_user(
    user_id="user_123",
    admin_id="admin_456",
    reason="Appeal approved"
)

# User can log in again
# Account status is restored
# Reactivation is logged

Searching & Filtering Users

AuthTuna provides powerful search capabilities for finding users based on various criteria, with privacy-conscious options for public search interfaces.

Advanced User Search

Search users by identity (email/username), role assignments, scope, and account status. All filters use AND logic for precise results.

# Search by identity (email or username)
users = await user_manager.search_users(
    identity="john",  # Matches email or username containing "john"
    skip=0,
    limit=20
)

# Search by role
admin_users = await user_manager.search_users(
    role="Admin",
    is_active=True
)

# Search by scope
project_users = await user_manager.search_users(
    scope="project:web-app"
)

# Combine multiple filters
team_members = await user_manager.search_users(
    role="Developer",
    scope="team:frontend",
    is_active=True
)

Privacy-Aware Search

For public user search interfaces, use basic_search_users which only returns usernames and IDs, protecting email privacy.

# Privacy-safe search for user interfaces
basic_results = await user_manager.basic_search_users(
    identity="john",
    skip=0,
    limit=10
)

# Returns only: [{"user_id": "...", "username": "..."}]
# No email addresses or sensitive information

# Example API endpoint
@app.get("/api/users/search")
async def search_users(query: str, current_user=Depends(get_current_user)):
    # Only admins can search with full details
    if "admin" in [role.name for role in current_user.roles]:
        return await user_manager.search_users(identity=query)
    else:
        return await user_manager.basic_search_users(identity=query)

User Deletion & Data Management

User deletion is a sensitive operation that requires careful handling. AuthTuna provides safe deletion with data archiving and audit trails.

Safe User Deletion

Deleting users permanently removes their data, but AuthTuna archives user information for compliance and audit purposes.

# Delete a user (with archiving)
await user_manager.delete(
    user_id="user_123",
    ip_address="192.168.1.100"
)

# What happens:
# 1. User data is archived to DeletedUser table
# 2. User is removed from main User table
# 3. All associated data (sessions, role assignments) are cleaned up
# 4. Audit event is logged
# 5. Transaction is committed atomically

Data Archiving Strategy

What Gets Archived

  • • User ID and email
  • • All user profile data
  • • Deletion timestamp
  • • Deletion reason (if provided)

What Gets Removed

  • • Password hashes
  • • Active sessions
  • • Role assignments
  • • Personal tokens

Audit Trails & Compliance

Every user management operation is automatically logged for security, compliance, and debugging purposes.

Comprehensive Audit Logging

User Creation

Logs who created the account, IP address, and creation method

Password Changes

Tracks password updates with IP addresses and timestamps

Account State Changes

Logs suspensions, reactivations, and reasons

Profile Updates

Records which fields were changed and by whom

Account Deletion

Logs deletion with archiving confirmation

Querying Audit Logs

# Query audit events for a user
user_events = await db_manager.get_audit_logs(
    user_id="user_123",
    event_types=["USER_UPDATED", "USER_SUSPENDED"],
    limit=50
)

# Query by IP address
ip_events = await db_manager.get_audit_logs(
    ip_address="192.168.1.100",
    since=datetime.now() - timedelta(days=7)
)

# Query by admin actions
admin_actions = await db_manager.get_audit_logs(
    event_types=["USER_SUSPENDED", "USER_UNSUSPENDED", "USER_DELETED"],
    limit=100
)

Best Practices & Security

✅ Security Best Practices

  • • Always validate user input
  • • Use strong password requirements
  • • Implement account lockout policies
  • • Log all administrative actions
  • • Use IP-based rate limiting
  • • Implement two-factor authentication

🔧 Implementation Tips

  • • Use transactions for data consistency
  • • Implement proper error handling
  • • Cache user data appropriately
  • • Use background jobs for bulk operations
  • • Implement user data export features

❌ Common Pitfalls

  • • Storing sensitive data in plain text
  • • Not handling concurrent updates
  • • Missing audit trails
  • • Weak password policies
  • • Not implementing proper session management
  • • Ignoring GDPR/privacy requirements

🛡️ Compliance Considerations

  • • Implement data retention policies
  • • Support user data export/deletion
  • • Maintain comprehensive audit logs
  • • Implement proper consent management
  • • Support account deactivation

Key Takeaways

  • Users are Central: Everything in AuthTuna revolves around user accounts and their lifecycle
  • Security First: Every operation includes validation, authorization checks, and audit logging
  • Data Integrity: Transactions ensure consistency even during complex operations
  • Privacy Matters: Implement privacy-aware search and data handling practices
  • Compliance Ready: Built-in audit trails and data archiving support regulatory requirements
  • Scalable Design: Efficient queries and pagination support large user bases