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

authentication-actions.mddocs/

Authentication Actions

High-level functions that orchestrate the complete social authentication flow from initiation to completion. These functions handle session management, redirect validation, pipeline execution, and provide the main entry points for implementing social authentication in web applications.

Capabilities

Authentication Initiation

Starts the authentication process by preparing session data, validating redirects, and initiating the provider-specific authentication flow.

def do_auth(backend, redirect_name="next"):
    """
    Initiate authentication flow with the specified backend.
    
    This function prepares the authentication process by:
    - Saving request data and configured fields to session
    - Validating and sanitizing redirect URLs for security
    - Calling the backend's start() method to begin authentication
    
    Parameters:
    - backend: Authentication backend instance (subclass of BaseAuth)
    - redirect_name: Name of the redirect parameter in request data (default: "next")
    
    Returns:
    Backend-specific response, typically a redirect to the provider's auth URL
    or HTML content for non-redirect flows
    
    Raises:
    - AuthException: If authentication cannot be initiated
    """

Usage Example:

from social_core.actions import do_auth
from social_core.backends.google import GoogleOAuth2

# Initialize backend with strategy and redirect URI
backend = GoogleOAuth2(strategy, redirect_uri='/auth/complete/google/')

# Start authentication - returns redirect response to Google OAuth
response = do_auth(backend, redirect_name='next')

Authentication Completion

Completes the authentication flow by processing the provider response, executing the authentication pipeline, and returning the authenticated user.

def do_complete(backend, login, user=None, redirect_name="next", *args, **kwargs):
    """
    Complete authentication flow and return authenticated user.
    
    This function handles the provider callback by:
    - Processing partial pipeline data if present
    - Running the complete authentication pipeline
    - Calling the login function on successful authentication
    - Managing session cleanup and redirect handling
    
    Parameters:
    - backend: Authentication backend instance (subclass of BaseAuth)
    - login: Function to call for logging in the user (e.g., Django's login())
    - user: Current user instance, if any (default: None)
    - redirect_name: Name of the redirect parameter (default: "next")
    - *args: Additional arguments passed to backend.complete()
    - **kwargs: Additional keyword arguments passed to backend.complete()
    
    Returns:
    - Authenticated user instance on successful authentication
    - None if authentication failed
    - HttpResponse for redirects or partial pipeline interruptions
    
    Raises:
    - AuthException: If authentication process fails
    - Various provider-specific exceptions based on backend implementation
    """

Usage Example:

from social_core.actions import do_complete
from social_core.backends.google import GoogleOAuth2
from django.contrib.auth import login

# In your OAuth callback view
def auth_complete_google(request):
    backend = GoogleOAuth2(strategy, redirect_uri='/auth/complete/google/')
    
    # Complete authentication and login user
    user = do_complete(
        backend=backend,
        login=login,
        user=request.user if request.user.is_authenticated else None,
        redirect_name='next',
        request=request
    )
    
    if user:
        # Authentication successful
        return redirect(request.GET.get('next', '/dashboard/'))
    else:
        # Authentication failed
        return redirect('/login/?error=auth_failed')

Social Account Disconnection

Removes social account associations, optionally revoking provider access tokens and running the disconnect pipeline.

def do_disconnect(backend, user, association_id=None, redirect_name="next", *args, **kwargs):
    """
    Disconnect social account association from user.
    
    This function handles social account disconnection by:
    - Validating that disconnection is allowed for the user
    - Running the complete disconnection pipeline
    - Optionally revoking access tokens at the provider
    - Removing social account associations from storage
    
    Parameters:
    - backend: Authentication backend instance (subclass of BaseAuth)
    - user: User instance to disconnect social account from
    - association_id: Optional specific association ID to disconnect (default: None)
    - redirect_name: Name of the redirect parameter (default: "next")
    - *args: Additional arguments passed to disconnect pipeline
    - **kwargs: Additional keyword arguments passed to disconnect pipeline
    
    Returns:
    - Dictionary with 'url' key containing redirect URL on success
    - Dictionary with disconnect results and metadata
    
    Raises:
    - NotAllowedToDisconnect: If user cannot disconnect this account
    - AuthException: If disconnection process fails
    """

Usage Example:

from social_core.actions import do_disconnect
from social_core.backends.google import GoogleOAuth2
from social_core.exceptions import NotAllowedToDisconnect

def disconnect_google(request):
    backend = GoogleOAuth2(strategy)
    
    try:
        result = do_disconnect(
            backend=backend,
            user=request.user,
            association_id=request.GET.get('association_id'),
            redirect_name='next'
        )
        
        if 'url' in result:
            # Redirect after successful disconnection
            return redirect(result['url'])
        else:
            # Disconnection completed
            return redirect('/profile/?message=disconnected')
            
    except NotAllowedToDisconnect:
        # User must keep at least one login method
        return redirect('/profile/?error=cannot_disconnect')

Integration Patterns

Framework Integration

Authentication actions work with any Python web framework through the strategy pattern:

# Django example
from social_core.actions import do_auth, do_complete
from myapp.strategy import DjangoStrategy

def auth_start(request, backend_name):
    strategy = DjangoStrategy(request)
    backend = strategy.get_backend(backend_name)
    return do_auth(backend)

def auth_complete(request, backend_name):
    strategy = DjangoStrategy(request)  
    backend = strategy.get_backend(backend_name)
    return do_complete(backend, login, user=request.user)

Error Handling

Both functions may raise exceptions that should be handled appropriately:

from social_core.exceptions import AuthException, AuthCanceled

try:
    user = do_complete(backend, login, user=current_user)
except AuthCanceled:
    # User canceled authentication at provider
    return redirect('/login/?message=canceled')
except AuthException as e:
    # Other authentication errors
    return redirect(f'/login/?error={e}')

Session Management

The authentication actions automatically handle session data including:

  • Storing configured fields from FIELDS_STORED_IN_SESSION setting
  • Managing partial pipeline tokens for multi-step authentication
  • Preserving redirect URLs with security validation
  • Cleaning up session data after completion

This session management ensures secure handling of authentication state across the multi-request OAuth flow.

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