CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-social-auth-core

Python social authentication framework with 195+ backend providers for OAuth, OpenID Connect, and SAML integration.

Pending
Overview
Eval results
Files

exception-handling.mddocs/

Exception Handling

Comprehensive exception hierarchy for handling authentication errors, backend configuration issues, pipeline failures, and security violations. The exception system provides detailed error information and enables proper error handling throughout the social authentication process.

Capabilities

Base Exception Classes

Foundation exception classes that provide the structure for all social authentication error handling.

class SocialAuthBaseException(ValueError):
    """
    Base class for all social authentication exceptions.
    
    All social auth related exceptions inherit from this base class,
    making it easy to catch any social auth error with a single except clause.
    """

class AuthException(SocialAuthBaseException):
    """
    General authentication process exception.
    
    Raised when authentication fails due to provider issues, invalid responses,
    network problems, or other general authentication errors.
    """
    
    def __init__(self, backend, *args, **kwargs):
        """
        Initialize authentication exception.
        
        Parameters:
        - backend: Authentication backend instance that raised the exception
        - Additional arguments passed to parent exception
        """
        self.backend = backend
        super().__init__(*args, **kwargs)

Backend Configuration Exceptions

Exceptions related to backend configuration, availability, and setup issues.

class WrongBackend(SocialAuthBaseException):
    """
    Incorrect authentication service error.
    
    Raised when the requested backend name doesn't match the expected
    backend for the current authentication flow.
    """
    
    def __init__(self, backend_name: str):
        """
        Initialize wrong backend exception.
        
        Parameters:
        - backend_name: Name of the incorrect backend
        """
        self.backend_name = backend_name
        super().__init__()
    
    def __str__(self) -> str:
        return f'Incorrect authentication service "{self.backend_name}"'

class MissingBackend(WrongBackend):
    """
    Missing backend entry error.
    
    Raised when a requested backend is not available in the current
    configuration or has not been properly installed/configured.
    """
    
    def __str__(self) -> str:
        return f'Missing backend "{self.backend_name}" entry'

Strategy and Feature Exceptions

Exceptions related to strategy implementation and feature support.

class StrategyMissingFeatureError(SocialAuthBaseException):
    """
    Strategy does not support required feature.
    
    Raised when the current strategy implementation lacks support
    for a feature required by a backend or pipeline function.
    """
    
    def __init__(self, strategy_name: str, feature_name: str):
        """
        Initialize missing feature exception.
        
        Parameters:
        - strategy_name: Name of the strategy implementation
        - feature_name: Name of the missing feature
        """
        self.strategy_name = strategy_name
        self.feature_name = feature_name
        super().__init__()
    
    def __str__(self) -> str:
        return f"Strategy {self.strategy_name} does not support {self.feature_name}"

User Account Management Exceptions

Exceptions related to user account operations and restrictions.

class NotAllowedToDisconnect(SocialAuthBaseException):
    """
    User not allowed to disconnect social account.
    
    Raised when a user attempts to disconnect a social account but doing so
    would leave them without any way to authenticate (no password, no other
    social accounts, etc.).
    """
    
    def __str__(self) -> str:
        return "This account is not allowed to be disconnected."

Authentication Flow Exceptions

Exceptions that occur during the authentication process and user interaction.

class AuthCanceled(AuthException):
    """
    Authentication canceled by user.
    
    Raised when the user explicitly cancels the authentication process
    at the provider's authorization page.
    """
    
    def __str__(self) -> str:
        return "Authentication process was canceled by the user"

class AuthForbidden(AuthException):
    """
    Authentication forbidden by policy.
    
    Raised when authentication is blocked by access control policies
    such as domain restrictions, email whitelists, or other security rules.
    """
    
    def __str__(self) -> str:
        return "Authentication is forbidden by access control policy"

class AuthFailed(AuthException):
    """
    Authentication failed due to invalid credentials or provider error.
    
    Raised when the authentication provider rejects the credentials
    or returns an error response during the authentication process.
    """
    
    def __str__(self) -> str:
        return "Authentication failed"

class AuthMissingParameter(AuthException):
    """
    Required authentication parameter missing.
    
    Raised when a required parameter is missing from the authentication
    request or provider response.
    """
    
    def __init__(self, backend, parameter, *args, **kwargs):
        """
        Initialize missing parameter exception.
        
        Parameters:
        - backend: Authentication backend instance
        - parameter: Name of the missing parameter
        """
        self.parameter = parameter
        super().__init__(backend, *args, **kwargs)
    
    def __str__(self) -> str:
        return f"Missing required parameter: {self.parameter}"

class AuthStateMissing(AuthException):
    """
    OAuth state parameter missing or invalid.
    
    Raised when the OAuth state parameter is missing from the callback
    or doesn't match the expected value, indicating a potential CSRF attack.
    """
    
    def __str__(self) -> str:
        return "OAuth state parameter is missing or invalid"

class AuthStateForbidden(AuthException):
    """
    OAuth state parameter validation failed.
    
    Raised when the OAuth state parameter fails validation checks,
    indicating a security issue or tampering attempt.
    """
    
    def __str__(self) -> str:
        return "OAuth state parameter validation failed"

Network and Communication Exceptions

Exceptions related to network connectivity and provider communication.

class AuthConnectionError(AuthException):
    """
    Connection error during authentication.
    
    Raised when network connectivity issues prevent communication
    with the authentication provider's servers.
    """
    
    def __str__(self) -> str:
        return "Failed to connect to authentication provider"

class AuthUnreachableProvider(AuthException):
    """
    Authentication provider is unreachable.
    
    Raised when the authentication provider's servers are unavailable
    or returning error responses consistently.
    """
    
    def __str__(self) -> str:
        return "Authentication provider is currently unreachable"

class AuthTimeout(AuthException):
    """
    Authentication request timeout.
    
    Raised when requests to the authentication provider exceed
    the configured timeout period.
    """
    
    def __str__(self) -> str:
        return "Authentication request timed out"

class AuthUnknownError(AuthException):
    """
    Unknown authentication error.
    
    Raised when an unexpected error occurs during authentication
    that doesn't fit into other exception categories.
    """
    
    def __str__(self) -> str:
        return "An unknown authentication error occurred"

Token Management Exceptions

Exceptions related to token handling and refresh operations.

class AuthTokenError(AuthException):
    """
    Token-related authentication error.
    
    Raised when issues occur with access tokens, refresh tokens,
    or other authentication tokens.
    """
    
    def __str__(self) -> str:
        return "Authentication token error"

class AuthTokenRevoked(AuthTokenError):
    """
    Authentication token has been revoked.
    
    Raised when an access token or refresh token has been revoked
    by the user or provider and is no longer valid.
    """
    
    def __str__(self) -> str:
        return "Authentication token has been revoked"

class AuthTokenExpired(AuthTokenError):
    """
    Authentication token has expired.
    
    Raised when attempting to use an expired token and no refresh
    token is available or refresh fails.
    """
    
    def __str__(self) -> str:
        return "Authentication token has expired"

Exception Handling Patterns

Basic Exception Handling

from social_core.exceptions import (
    AuthException, AuthCanceled, AuthForbidden,
    MissingBackend, NotAllowedToDisconnect
)

try:
    user = do_complete(backend, login, user=current_user)
except AuthCanceled:
    # User canceled at provider
    messages.info(request, 'Authentication was canceled')
    return redirect('/login/')
except AuthForbidden:
    # Access denied by policy
    messages.error(request, 'Access denied by security policy')
    return redirect('/login/')
except MissingBackend as e:
    # Backend not configured
    messages.error(request, f'Authentication service not available: {e.backend_name}')
    return redirect('/login/')
except AuthException as e:
    # General authentication error
    messages.error(request, f'Authentication failed: {e}')
    return redirect('/login/')

Disconnect Exception Handling

from social_core.exceptions import NotAllowedToDisconnect

try:
    backend.disconnect(user, association_id)
except NotAllowedToDisconnect:
    messages.error(request, 'Cannot disconnect - this is your only login method')
    return redirect('/profile/connections/')

Network Error Handling

from social_core.exceptions import (
    AuthConnectionError, AuthUnreachableProvider, AuthTimeout
)

try:
    user = backend.complete()
except (AuthConnectionError, AuthUnreachableProvider, AuthTimeout) as e:
    # Network/provider issues - suggest retry
    messages.warning(request, f'Service temporarily unavailable: {e}')
    return redirect('/login/?retry=1')
except AuthException as e:
    # Other auth errors
    messages.error(request, f'Authentication failed: {e}')
    return redirect('/login/')

Custom Exception Handling

def handle_social_auth_error(exception, backend=None):
    """Centralized exception handler for social auth errors."""
    
    if isinstance(exception, AuthCanceled):
        return {
            'message': 'Authentication was canceled by the user',
            'level': 'info',
            'retry': True
        }
    elif isinstance(exception, AuthForbidden):
        return {
            'message': 'Access denied by security policy',
            'level': 'error',
            'retry': False
        }
    elif isinstance(exception, MissingBackend):
        return {
            'message': f'Authentication service "{exception.backend_name}" not available',
            'level': 'error',
            'retry': False
        }
    elif isinstance(exception, (AuthConnectionError, AuthTimeout)):
        return {
            'message': 'Service temporarily unavailable, please try again',
            'level': 'warning',
            'retry': True
        }
    else:
        return {
            'message': 'Authentication failed',
            'level': 'error',
            'retry': True
        }

# Usage in views
try:
    user = do_complete(backend, login)
except SocialAuthBaseException as e:
    error_info = handle_social_auth_error(e, backend)
    messages.add_message(request, getattr(messages, error_info['level'].upper()), 
                        error_info['message'])

Logging Exception Details

import logging
from social_core.exceptions import AuthException

logger = logging.getLogger('social_auth')

try:
    user = backend.complete()
except AuthException as e:
    logger.error(
        'Authentication failed for backend %s: %s',
        getattr(e, 'backend', {}).name if hasattr(e, 'backend') else 'unknown',
        str(e),
        extra={
            'backend': getattr(e, 'backend', None),
            'user': request.user.id if request.user.is_authenticated else None,
            'ip': request.META.get('REMOTE_ADDR'),
            'user_agent': request.META.get('HTTP_USER_AGENT')
        }
    )
    raise

The exception handling system provides comprehensive error coverage for all aspects of social authentication, enabling applications to provide meaningful error messages to users while maintaining security and supporting debugging during development.

Install with Tessl CLI

npx tessl i tessl/pypi-social-auth-core

docs

authentication-actions.md

authentication-backends.md

exception-handling.md

index.md

pipeline-system.md

storage-models.md

strategy-interface.md

utilities-helpers.md

tile.json