CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-allauth

Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Pending
Overview
Eval results
Files

social-authentication.mddocs/

Social Authentication

OAuth 1.0/2.0 integration supporting 50+ providers including Google, Facebook, GitHub, Twitter, and enterprise providers. Provides complete social login flows with account linking capabilities and extensive provider ecosystem support.

Capabilities

Models

Core models for managing social applications, user accounts, and OAuth tokens.

class SocialApp(models.Model):
    """
    Configuration for social authentication providers.
    """
    provider: str = models.CharField(max_length=30)
    provider_id: str = models.CharField(max_length=200, blank=True)
    name: str = models.CharField(max_length=40)
    client_id: str = models.CharField(max_length=191)
    secret: str = models.CharField(max_length=191, blank=True)
    key: str = models.CharField(max_length=191, blank=True)
    certificate_key: str = models.TextField(blank=True)
    settings: dict = models.JSONField(default=dict)
    
    objects: SocialAppManager
    
    def __str__(self) -> str: ...

class SocialAccount(models.Model):
    """
    User's connected social media account.
    """
    user: User = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    provider: str = models.CharField(max_length=200)
    uid: str = models.CharField(max_length=191)
    last_login: datetime = models.DateTimeField(auto_now=True)
    date_joined: datetime = models.DateTimeField(auto_now_add=True)
    extra_data: dict = models.JSONField(default=dict)
    
    def __str__(self) -> str: ...
    def get_provider(self): ...
    def get_provider_account(self): ...

class SocialToken(models.Model):
    """
    OAuth tokens for social accounts.
    """
    app: SocialApp = models.ForeignKey(SocialApp, on_delete=models.CASCADE)
    account: SocialAccount = models.ForeignKey(SocialAccount, on_delete=models.CASCADE)
    token: str = models.TextField()
    token_secret: str = models.TextField(blank=True)
    expires_at: Optional[datetime] = models.DateTimeField(null=True, blank=True)
    
    def __str__(self) -> str: ...

Managers

Database managers for social app and account queries.

class SocialAppManager(models.Manager):
    """
    Manager for SocialApp model with site-aware filtering.
    """
    
    def on_site(self, request: HttpRequest) -> QuerySet:
        """
        Filter social apps available on current site.
        
        Parameters:
        - request: HTTP request object
        
        Returns:
        Filtered queryset of SocialApp instances
        """

Views

Django views for social authentication flows including OAuth redirects, callbacks, and account management.

class LoginView(View):
    """
    Initiate social authentication login flow.
    """
    
    def dispatch(self, request: HttpRequest, provider: str) -> HttpResponse: ...

class CallbackView(View):
    """
    Handle OAuth callback from social provider.
    """
    
    def dispatch(self, request: HttpRequest, provider: str) -> HttpResponse: ...

class SignupView(CloseableSignupMixin, AjaxCapableProcessFormViewMixin, FormView):
    """
    Social account signup with additional information collection.
    """
    template_name: str = "socialaccount/signup.html"
    form_class: type = SignupForm
    
    def get_form_kwargs(self) -> Dict[str, Any]: ...
    def form_valid(self, form: SignupForm) -> HttpResponse: ...

class ConnectionsView(AjaxCapableProcessFormViewMixin, FormView):
    """
    Manage connected social accounts.
    """
    template_name: str = "socialaccount/connections.html"
    form_class: type = DisconnectForm
    
    def get_form_kwargs(self) -> Dict[str, Any]: ...
    def form_valid(self, form: DisconnectForm) -> HttpResponse: ...

class LoginCancelledView(TemplateView):
    """
    Handle cancelled social login attempts.
    """
    template_name: str = "socialaccount/login_cancelled.html"

class LoginErrorView(TemplateView):
    """
    Handle social login errors.
    """
    template_name: str = "socialaccount/login_error.html"

Providers

Provider registry and base classes for social authentication providers.

class ProviderRegistry:
    """
    Registry for managing social authentication providers.
    """
    
    def register(self, cls: type) -> None:
        """Register a provider class."""
    
    def get_class(self, provider_id: str) -> Optional[type]:
        """Get provider class by ID."""
    
    def get_class_list(self) -> List[type]:
        """Get list of all registered provider classes."""
    
    def by_id(self, provider_id: str, request: HttpRequest = None):
        """Get provider instance by ID."""

registry: ProviderRegistry

class Provider:
    """
    Base class for social authentication providers.
    """
    id: str
    name: str
    package: str
    
    def __init__(self, request: HttpRequest, app: SocialApp = None): ...
    def get_login_url(self, request: HttpRequest, **kwargs) -> str: ...
    def get_auth_url(self, request: HttpRequest, action: str) -> str: ...
    def get_callback_url(self, request: HttpRequest, app: SocialApp) -> str: ...

class OAuth2Provider(Provider):
    """
    Base class for OAuth 2.0 providers.
    """
    supports_state: bool = True
    pkce_enabled_default: bool = False
    
    def get_auth_params(self, request: HttpRequest, action: str) -> Dict[str, Any]: ...
    def get_scope(self, request: HttpRequest) -> List[str]: ...

class OAuth1Provider(Provider):
    """
    Base class for OAuth 1.0 providers.
    """
    
    def get_request_token(self, request: HttpRequest) -> Dict[str, str]: ...

Adapters

Customizable adapter classes for social authentication behavior.

class SocialAccountAdapter:
    """
    Adapter for customizing social authentication behavior.
    """
    
    def new_user(self, request: HttpRequest, sociallogin) -> User:
        """
        Create new user from social login data.
        
        Parameters:
        - request: HTTP request object
        - sociallogin: SocialLogin instance
        
        Returns:
        New User instance
        """
    
    def save_user(self, request: HttpRequest, sociallogin, form: forms.Form = None) -> User:
        """
        Save user from social login data.
        
        Parameters:
        - request: HTTP request object
        - sociallogin: SocialLogin instance
        - form: Optional form data
        
        Returns:
        Saved User instance
        """
    
    def populate_user(self, request: HttpRequest, sociallogin, data: Dict[str, Any]) -> User:
        """
        Populate user fields from social account data.
        
        Parameters:
        - request: HTTP request object
        - sociallogin: SocialLogin instance
        - data: Social account data
        
        Returns:
        User instance with populated fields
        """
    
    def get_connect_redirect_url(self, request: HttpRequest, socialaccount: SocialAccount) -> str:
        """Get redirect URL after connecting social account."""
    
    def is_open_for_signup(self, request: HttpRequest, sociallogin) -> bool:
        """Check if signup is open for social login."""
    
    def is_auto_signup_allowed(self, request: HttpRequest, sociallogin) -> bool:
        """Check if automatic signup is allowed."""

def get_adapter(request: HttpRequest = None) -> SocialAccountAdapter:
    """
    Get social account adapter instance.
    
    Parameters:
    - request: Optional HTTP request object
    
    Returns:
    SocialAccountAdapter instance
    """

Provider-Specific Classes

Individual provider implementations for major social platforms.

# Google OAuth2
class GoogleProvider(OAuth2Provider):
    id: str = "google"
    name: str = "Google"
    
# Facebook OAuth2
class FacebookProvider(OAuth2Provider):
    id: str = "facebook"
    name: str = "Facebook"
    
# GitHub OAuth2
class GitHubProvider(OAuth2Provider):
    id: str = "github"
    name: str = "GitHub"
    
# Twitter OAuth2
class TwitterProvider(OAuth2Provider):
    id: str = "twitter"
    name: str = "Twitter"
    
# Microsoft OAuth2
class MicrosoftProvider(OAuth2Provider):
    id: str = "microsoft"
    name: str = "Microsoft"
    
# LinkedIn OAuth2
class LinkedInProvider(OAuth2Provider):
    id: str = "linkedin"
    name: str = "LinkedIn"

Utilities and Helpers

Helper functions for social authentication flows.

def complete_social_login(request: HttpRequest, sociallogin) -> HttpResponse:
    """
    Complete social login process.
    
    Parameters:
    - request: HTTP request object
    - sociallogin: SocialLogin instance
    
    Returns:
    HTTP response for completed login
    """

def render_authentication_error(request: HttpRequest, provider: Provider, error: str = None, exception: Exception = None, extra_context: Dict[str, Any] = None) -> HttpResponse:
    """
    Render authentication error page.
    
    Parameters:
    - request: HTTP request object
    - provider: Provider instance
    - error: Error message
    - exception: Exception instance
    - extra_context: Additional template context
    
    Returns:
    HTTP response with error page
    """

Usage Examples

Basic Social App Configuration

from allauth.socialaccount.models import SocialApp

# Create Google OAuth2 app
google_app = SocialApp.objects.create(
    provider='google',
    name='My App Google Login',
    client_id='your-google-client-id',
    secret='your-google-client-secret',
    settings={
        'scope': ['email', 'profile']
    }
)

# Add to current site (if using Django sites)
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
google_app.sites.add(current_site)

Provider Registration and Usage

from allauth.socialaccount import providers

# Get provider by ID
google_provider = providers.registry.by_id('google', request)

# Get all available providers
provider_classes = providers.registry.get_class_list()

# Generate login URL
login_url = google_provider.get_login_url(request, process='login')

Social Account Management

from allauth.socialaccount.models import SocialAccount, SocialToken

# Get user's social accounts
social_accounts = SocialAccount.objects.filter(user=user)

# Get specific provider account
try:
    google_account = SocialAccount.objects.get(user=user, provider='google')
    print(f"Google UID: {google_account.uid}")
    print(f"Extra data: {google_account.extra_data}")
except SocialAccount.DoesNotExist:
    print("No Google account connected")

# Get OAuth tokens
tokens = SocialToken.objects.filter(account__user=user, account__provider='google')
for token in tokens:
    print(f"Token: {token.token}")
    if token.expires_at:
        print(f"Expires: {token.expires_at}")

Custom Social Adapter

from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

class MySocialAccountAdapter(DefaultSocialAccountAdapter):
    def new_user(self, request, sociallogin):
        user = super().new_user(request, sociallogin)
        # Custom user initialization
        return user
    
    def populate_user(self, request, sociallogin, data):
        user = super().populate_user(request, sociallogin, data)
        # Custom field mapping from social data
        if 'company' in data:
            user.company = data['company']
        return user
    
    def is_auto_signup_allowed(self, request, sociallogin):
        # Custom auto-signup logic
        return sociallogin.account.provider == 'google'

# In settings.py
SOCIALACCOUNT_ADAPTER = 'myapp.adapters.MySocialAccountAdapter'

Template Usage

<!-- Login with social providers -->
{% load socialaccount %}

{% get_providers as socialaccount_providers %}
{% for provider in socialaccount_providers %}
    {% if provider.id == "google" %}
        <a href="{% provider_login_url 'google' process='login' scope='email,profile' %}">
            Login with Google
        </a>
    {% endif %}
{% endfor %}

<!-- Show connected accounts -->
{% if user.is_authenticated %}
    {% for account in user.socialaccount_set.all %}
        <p>Connected: {{ account.get_provider.name }} ({{ account.uid }})</p>
    {% endfor %}
{% endif %}

Provider Settings Configuration

# In Django settings.py
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        },
        'OAUTH_PKCE_ENABLED': True,
    },
    'facebook': {
        'METHOD': 'oauth2',
        'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',
        'SCOPE': ['email', 'public_profile'],
        'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
        'INIT_PARAMS': {'cookie': True},
        'FIELDS': [
            'id',
            'first_name',
            'last_name',
            'middle_name',
            'name',
            'name_format',
            'picture',
            'short_name',
            'email',
        ],
        'EXCHANGE_TOKEN': True,
        'LOCALE_FUNC': 'path.to.callable',
        'VERIFIED_EMAIL': False,
        'VERSION': 'v13.0',
    }
}

Install with Tessl CLI

npx tessl i tessl/pypi-django-allauth

docs

account-management.md

core-config.md

headless-api.md

index.md

mfa.md

social-authentication.md

template-system.md

user-sessions.md

tile.json