CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-supabase

Supabase client for Python providing database operations, authentication, storage, real-time subscriptions, and edge functions.

Overview
Eval results
Files

authentication.mddocs/

Authentication

User registration, login, session management, OAuth integration, and authentication state handling. Provides complete authentication functionality through integration with Supabase Auth (GoTrue), supporting various auth flows including email/password, OAuth providers, magic links, and MFA.

Capabilities

Authentication Client Access

Access the authentication client through the main Supabase client instance.

@property  
def auth(self) -> SyncSupabaseAuthClient | AsyncSupabaseAuthClient:
    """
    Authentication client providing complete GoTrue functionality.
    
    Returns:
    Auth client instance (sync or async) with methods for:
    - User registration and login
    - OAuth provider integration  
    - Session management and token refresh
    - Password reset and email verification
    - Multi-factor authentication
    - User profile management
    """

User Registration

Register new users with email/password or other authentication methods.

# Core registration methods (inherited from GoTrue)
def sign_up(self, credentials: dict) -> AuthResponse:
    """
    Register a new user with email and password.

    Parameters:
    - credentials: Dict with 'email' and 'password' keys, plus optional metadata

    Returns:
    AuthResponse with user data and session information

    Raises:
    AuthWeakPasswordError: If password doesn't meet requirements
    AuthApiError: If email already exists or other API errors
    """

def sign_up_with_phone(self, credentials: dict) -> AuthResponse:
    """
    Register a new user with phone number and password.

    Parameters:
    - credentials: Dict with 'phone' and 'password' keys

    Returns:
    AuthResponse with user data and session information
    """

Usage Examples:

# Basic email registration
try:
    response = supabase.auth.sign_up({
        "email": "user@example.com",
        "password": "secure_password123"
    })
    user = response.user
    session = response.session
    print(f"User registered: {user.id}")
except AuthWeakPasswordError:
    print("Password is too weak")
except AuthApiError as e:
    print(f"Registration failed: {e}")

# Registration with additional metadata
response = supabase.auth.sign_up({
    "email": "user@example.com", 
    "password": "secure_password123",
    "options": {
        "data": {
            "full_name": "John Doe",
            "age": 30
        }
    }
})

# Phone registration
response = supabase.auth.sign_up({
    "phone": "+1234567890",
    "password": "secure_password123"
})

User Login

Authenticate existing users with various login methods.

def sign_in_with_password(self, credentials: dict) -> AuthResponse:
    """
    Sign in user with email/phone and password.

    Parameters:
    - credentials: Dict with 'email'/'phone' and 'password' keys

    Returns:
    AuthResponse with user data and session information

    Raises:
    AuthInvalidCredentialsError: If credentials are incorrect
    AuthApiError: For other authentication errors
    """

def sign_in_with_otp(self, credentials: dict) -> AuthResponse:
    """
    Sign in with one-time password (magic link or SMS).

    Parameters:
    - credentials: Dict with 'email'/'phone' and optional 'token'

    Returns:
    AuthResponse with user data and session information
    """

Usage Examples:

# Email/password login
try:
    response = supabase.auth.sign_in_with_password({
        "email": "user@example.com",
        "password": "secure_password123"
    })
    session = response.session
    user = response.user
    print(f"Signed in: {user.email}")
except AuthInvalidCredentialsError:
    print("Invalid email or password")

# Phone/password login  
response = supabase.auth.sign_in_with_password({
    "phone": "+1234567890",
    "password": "secure_password123"
})

# Magic link login (send OTP)
supabase.auth.sign_in_with_otp({
    "email": "user@example.com"
})
# User receives email with magic link

# Verify OTP token
response = supabase.auth.verify_otp({
    "email": "user@example.com",
    "token": "123456",
    "type": "email"
})

OAuth Authentication

Integrate with third-party OAuth providers for social login.

def sign_in_with_oauth(self, provider: str, options: dict = None) -> AuthResponse:
    """
    Sign in with OAuth provider.

    Parameters:
    - provider: OAuth provider name (google, github, facebook, etc.)
    - options: Additional OAuth options (redirect_to, scopes, etc.)

    Returns:
    AuthResponse with authentication URL for redirect-based flow
    """

Usage Examples:

# Google OAuth
response = supabase.auth.sign_in_with_oauth("google", {
    "options": {
        "redirect_to": "https://myapp.com/auth/callback"
    }
})
# Redirect user to response.url

# GitHub OAuth with custom scopes
response = supabase.auth.sign_in_with_oauth("github", {
    "options": {
        "scopes": "user:email",
        "redirect_to": "https://myapp.com/auth/callback"
    } 
})

# Multiple provider support
providers = ["google", "github", "facebook", "twitter"]
for provider in providers:
    auth_url = supabase.auth.sign_in_with_oauth(provider)
    print(f"{provider} login: {auth_url.url}")

Session Management

Manage user sessions, tokens, and authentication state.

def get_session(self) -> Session | None:
    """
    Get the current user session.

    Returns:
    Current session with access token and user data, or None if not authenticated
    """

def get_user(self) -> User | None:
    """
    Get the current authenticated user.

    Returns:
    Current user data, or None if not authenticated
    """

def refresh_session(self) -> AuthResponse:
    """
    Refresh the current session using the refresh token.

    Returns:
    AuthResponse with new session data

    Raises:
    AuthSessionMissingError: If no session exists to refresh
    """

def sign_out(self) -> None:
    """
    Sign out the current user and clear session.

    Raises:
    AuthApiError: If sign out fails
    """

Usage Examples:

# Check current session
session = supabase.auth.get_session()
if session:
    print(f"User is logged in: {session.user.email}")
    print(f"Access token expires: {session.expires_at}")
else:
    print("No active session")

# Get current user
user = supabase.auth.get_user()
if user:
    print(f"Current user: {user.email}")
    print(f"User metadata: {user.user_metadata}")

# Refresh session
try:
    response = supabase.auth.refresh_session()
    new_session = response.session
    print("Session refreshed successfully")
except AuthSessionMissingError:
    print("No session to refresh")

# Sign out
supabase.auth.sign_out()
print("User signed out")

Password Management

Handle password resets, updates, and security operations.

def reset_password_email(self, email: str, options: dict = None) -> None:
    """
    Send password reset email to user.

    Parameters:
    - email: User's email address
    - options: Additional options (redirect_to, etc.)

    Raises:
    AuthApiError: If email sending fails
    """

def update_user(self, attributes: dict) -> AuthResponse:
    """
    Update user profile and authentication data.

    Parameters:
    - attributes: Dict with user data to update (email, password, data, etc.)

    Returns:
    AuthResponse with updated user data

    Raises:
    AuthSessionMissingError: If no active session
    AuthWeakPasswordError: If new password is too weak
    """

Usage Examples:

# Send password reset email
supabase.auth.reset_password_email("user@example.com", {
    "redirect_to": "https://myapp.com/reset-password"
})

# Update user password
response = supabase.auth.update_user({
    "password": "new_secure_password123"
})

# Update user metadata
response = supabase.auth.update_user({
    "data": {
        "full_name": "Jane Smith",
        "preferences": {"theme": "dark"}
    }
})

# Update email (requires verification)
response = supabase.auth.update_user({
    "email": "newemail@example.com"
})

Authentication State Events

Listen for authentication state changes and handle session events.

def on_auth_state_change(self, callback: Callable) -> None:
    """
    Register callback for authentication state changes.

    Parameters:
    - callback: Function called on auth events (event, session)

    Events:
    - SIGNED_IN: User signed in
    - SIGNED_OUT: User signed out  
    - TOKEN_REFRESHED: Session token refreshed
    - USER_UPDATED: User profile updated
    - PASSWORD_RECOVERY: Password reset initiated
    """

Usage Examples:

def auth_state_handler(event, session):
    """Handle authentication state changes."""
    if event == "SIGNED_IN":
        print(f"User signed in: {session.user.email}")
        # Update UI, redirect, etc.
    elif event == "SIGNED_OUT":
        print("User signed out")
        # Clear user data, redirect to login
    elif event == "TOKEN_REFRESHED":
        print("Session refreshed")
        # Update stored tokens
    elif event == "USER_UPDATED":
        print("User profile updated")

# Register the handler
supabase.auth.on_auth_state_change(auth_state_handler)

# Example: Automatic session management
def handle_session_change(event, session):
    if event in ["SIGNED_IN", "TOKEN_REFRESHED"]:
        # Update authorization headers for other clients
        if session:
            supabase.options.headers["Authorization"] = f"Bearer {session.access_token}"
    elif event == "SIGNED_OUT":
        # Clear authorization
        supabase.options.headers.pop("Authorization", None)

supabase.auth.on_auth_state_change(handle_session_change)

Multi-Factor Authentication

Handle MFA enrollment, verification, and management.

# MFA methods (available through GoTrue integration)
def enroll_mfa(self, params: dict) -> MFAEnrollResponse:
    """
    Enroll user in multi-factor authentication.

    Parameters:
    - params: MFA enrollment parameters (factor_type, friendly_name, etc.)

    Returns:
    MFA enrollment response with QR code and recovery codes
    """

def challenge_mfa(self, params: dict) -> MFAChallengeResponse:
    """
    Create MFA challenge for verification.

    Parameters:
    - params: Challenge parameters (factor_id)

    Returns:
    MFA challenge response
    """

def verify_mfa(self, params: dict) -> AuthResponse:
    """
    Verify MFA challenge with code.

    Parameters:
    - params: Verification parameters (factor_id, challenge_id, code)

    Returns:
    AuthResponse with verified session
    """

Error Handling

Handle various authentication errors and edge cases.

# Authentication exceptions (from supabase_auth)
class AuthApiError(Exception):
    """General Auth API errors"""

class AuthError(Exception):
    """Base authentication error"""

class AuthInvalidCredentialsError(Exception):
    """Invalid email/password or credentials"""

class AuthSessionMissingError(Exception):
    """No active session when required"""

class AuthWeakPasswordError(Exception):
    """Password doesn't meet strength requirements"""

class AuthImplicitGrantRedirectError(Exception):
    """OAuth redirect errors"""

class AuthRetryableError(Exception):
    """Temporary errors that can be retried"""

class AuthUnknownError(Exception):
    """Unknown authentication errors"""

Error Handling Examples:

from supabase import AuthInvalidCredentialsError, AuthWeakPasswordError, AuthApiError

# Login error handling
try:
    response = supabase.auth.sign_in_with_password({
        "email": "user@example.com",
        "password": "wrong_password"
    })
except AuthInvalidCredentialsError:
    print("Invalid email or password")
except AuthApiError as e:
    print(f"Login failed: {e}")

# Registration error handling
try:
    response = supabase.auth.sign_up({
        "email": "user@example.com",
        "password": "weak"
    })
except AuthWeakPasswordError:
    print("Password must be at least 8 characters")
except AuthApiError as e:
    if "already registered" in str(e):
        print("Email already exists")
    else:
        print(f"Registration failed: {e}")

# Session operation error handling
try:
    response = supabase.auth.update_user({"password": "new_password"})
except AuthSessionMissingError:
    print("Please log in first")
except AuthWeakPasswordError:
    print("New password is too weak")

Install with Tessl CLI

npx tessl i tessl/pypi-supabase

docs

authentication.md

client-management.md

database-operations.md

edge-functions.md

index.md

realtime-subscriptions.md

storage-operations.md

tile.json