Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.
—
REST API endpoints for mobile and single-page applications. Provides JSON-based authentication flows without traditional Django templates and forms, enabling modern frontend frameworks to integrate with django-allauth authentication system.
Core constants defining client types and authentication flows.
from enum import Enum
class Client(str, Enum):
"""
Client type enumeration for headless authentication.
"""
APP = "app"
BROWSER = "browser"
class Flow(str, Enum):
"""
Authentication flow enumeration.
"""
VERIFY_EMAIL = "verify_email"
LOGIN = "login"
LOGIN_BY_CODE = "login_by_code"
SIGNUP = "signup"
PASSWORD_RESET_BY_CODE = "password_reset_by_code"
PROVIDER_REDIRECT = "provider_redirect"
PROVIDER_SIGNUP = "provider_signup"
PROVIDER_TOKEN = "provider_token"
REAUTHENTICATE = "reauthenticate"
MFA_REAUTHENTICATE = "mfa_reauthenticate"
MFA_AUTHENTICATE = "mfa_authenticate"
MFA_LOGIN_WEBAUTHN = "mfa_login_webauthn"
MFA_SIGNUP_WEBAUTHN = "mfa_signup_webauthn"
MFA_TRUST = "mfa_trust"Core REST API components providing input validation, response formatting, and view base classes.
class Input:
"""
Base class for API input validation.
"""
def __init__(self, data: Dict[str, Any]): ...
def is_valid(self) -> bool: ...
def get_errors(self) -> Dict[str, List[str]]: ...
class Response:
"""
Base class for API response formatting.
"""
def __init__(self, request: HttpRequest, **kwargs): ...
def to_dict(self) -> Dict[str, Any]: ...
class APIView(View):
"""
Base API view class with input validation and response formatting.
"""
input_class: Optional[type] = None
def dispatch(self, request: HttpRequest, *args, **kwargs) -> JsonResponse: ...
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
def get_input_kwargs(self, request: HttpRequest, *args, **kwargs) -> Dict[str, Any]: ...REST API endpoints for account management operations.
class LoginView(APIView):
"""
User login via REST API.
"""
input_class: type = LoginInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class SignupView(APIView):
"""
User registration via REST API.
"""
input_class: type = SignupInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class LogoutView(APIView):
"""
User logout via REST API.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class PasswordResetView(APIView):
"""
Password reset request via REST API.
"""
input_class: type = PasswordResetInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class ConfirmPasswordResetView(APIView):
"""
Password reset confirmation via REST API.
"""
input_class: type = ConfirmPasswordResetInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class PasswordChangeView(APIView):
"""
Password change via REST API.
"""
input_class: type = PasswordChangeInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class EmailVerificationView(APIView):
"""
Email verification via REST API.
"""
input_class: type = EmailVerificationInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class RequestEmailVerificationView(APIView):
"""
Request email verification via REST API.
"""
input_class: type = RequestEmailVerificationInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...Input validation classes for API requests.
class LoginInput(Input):
"""
Input validation for login requests.
"""
email: str
password: str
def clean_email(self) -> str: ...
def clean_password(self) -> str: ...
class SignupInput(Input):
"""
Input validation for signup requests.
"""
email: str
password: str
username: Optional[str] = None
def clean_email(self) -> str: ...
def clean_password(self) -> str: ...
def clean_username(self) -> Optional[str]: ...
class PasswordResetInput(Input):
"""
Input validation for password reset requests.
"""
email: str
def clean_email(self) -> str: ...
class ConfirmPasswordResetInput(Input):
"""
Input validation for password reset confirmation.
"""
key: str
password: str
def clean_key(self) -> str: ...
def clean_password(self) -> str: ...
class PasswordChangeInput(Input):
"""
Input validation for password change requests.
"""
current_password: str
new_password: str
def clean_current_password(self) -> str: ...
def clean_new_password(self) -> str: ...
class EmailVerificationInput(Input):
"""
Input validation for email verification.
"""
key: str
def clean_key(self) -> str: ...
class RequestEmailVerificationInput(Input):
"""
Input validation for email verification requests.
"""
email: str
def clean_email(self) -> str: ...Response formatting classes for API responses.
class AuthenticationResponse(Response):
"""
Response for authentication operations.
"""
def __init__(self, request: HttpRequest, user: User = None, access_token: str = None, **kwargs): ...
def to_dict(self) -> Dict[str, Any]: ...
class UserResponse(Response):
"""
Response containing user information.
"""
def __init__(self, request: HttpRequest, user: User, **kwargs): ...
def to_dict(self) -> Dict[str, Any]: ...
class FlowResponse(Response):
"""
Response for multi-step authentication flows.
"""
def __init__(self, request: HttpRequest, flow: str, pending: bool = False, **kwargs): ...
def to_dict(self) -> Dict[str, Any]: ...
class ErrorResponse(Response):
"""
Response for API errors.
"""
def __init__(self, request: HttpRequest, errors: Dict[str, List[str]], **kwargs): ...
def to_dict(self) -> Dict[str, Any]: ...REST API endpoints for social authentication.
class ProviderRedirectView(APIView):
"""
Initiate social provider authentication.
"""
def handle(self, request: HttpRequest, provider: str, *args, **kwargs) -> Response: ...
class ProviderCallbackView(APIView):
"""
Handle social provider authentication callback.
"""
def handle(self, request: HttpRequest, provider: str, *args, **kwargs) -> Response: ...
class ProviderTokenView(APIView):
"""
Authenticate using social provider access token.
"""
input_class: type = ProviderTokenInput
def handle(self, request: HttpRequest, provider: str, *args, **kwargs) -> Response: ...
class ProvidersView(APIView):
"""
List available social authentication providers.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...REST API endpoints for multi-factor authentication.
class MFAAuthenticateView(APIView):
"""
MFA authentication via REST API.
"""
input_class: type = MFAAuthenticateInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class TOTPAddView(APIView):
"""
Add TOTP authenticator via REST API.
"""
input_class: type = TOTPAddInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class WebAuthnAddView(APIView):
"""
Add WebAuthn authenticator via REST API.
"""
input_class: type = WebAuthnAddInput
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class AuthenticatorsView(APIView):
"""
List user's MFA authenticators via REST API.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class RecoveryCodesView(APIView):
"""
Manage recovery codes via REST API.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...Session and authentication token management for headless clients.
class SessionView(APIView):
"""
Get current session information.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
class ConfigView(APIView):
"""
Get authentication configuration for client.
"""
def handle(self, request: HttpRequest, *args, **kwargs) -> Response: ...
def create_session_token(user: User, client: Client = Client.BROWSER) -> str:
"""
Create session token for headless authentication.
Parameters:
- user: User instance
- client: Client type
Returns:
Session token string
"""
def validate_session_token(token: str) -> Optional[User]:
"""
Validate session token and return user.
Parameters:
- token: Session token
Returns:
User instance if valid, None otherwise
"""import requests
# Login via API
login_data = {
'email': 'user@example.com',
'password': 'password123'
}
response = requests.post('/auth/login/', json=login_data)
if response.status_code == 200:
data = response.json()
access_token = data['access_token']
user_id = data['user']['id']
print(f"Logged in as user {user_id}")
# Use authentication token for subsequent requests
headers = {'Authorization': f'Bearer {access_token}'}
profile_response = requests.get('/auth/user/', headers=headers)# Signup via API
signup_data = {
'email': 'newuser@example.com',
'password': 'securepassword123',
'username': 'newuser'
}
response = requests.post('/auth/signup/', json=signup_data)
if response.status_code == 200:
data = response.json()
if data.get('verification_sent'):
print("Verification email sent")
# Verify email
verify_data = {
'key': 'verification_key_from_email'
}
verify_response = requests.post('/auth/email/verify/', json=verify_data)# Get social providers
providers_response = requests.get('/auth/providers/')
providers = providers_response.json()['providers']
# Initiate Google OAuth flow
google_response = requests.post('/auth/providers/google/redirect/')
redirect_url = google_response.json()['redirect_url']
# After user completes OAuth, handle callback
callback_data = {
'code': 'oauth_code_from_callback',
'state': 'oauth_state_from_callback'
}
auth_response = requests.post('/auth/providers/google/callback/', json=callback_data)
# Or authenticate with existing access token
token_data = {
'access_token': 'google_access_token'
}
token_response = requests.post('/auth/providers/google/token/', json=token_data)# Login triggers MFA if enabled
login_response = requests.post('/auth/login/', json=login_data)
if login_response.json().get('flow') == 'mfa_authenticate':
mfa_token = login_response.json()['mfa_token']
# Complete MFA authentication
mfa_data = {
'token': mfa_token,
'code': '123456' # TOTP code
}
mfa_response = requests.post('/auth/mfa/authenticate/', json=mfa_data)
if mfa_response.status_code == 200:
access_token = mfa_response.json()['access_token']
# Add TOTP authenticator
totp_setup_response = requests.post('/auth/mfa/totp/add/')
secret = totp_setup_response.json()['secret']
qr_code = totp_setup_response.json()['qr_code']
# Confirm TOTP setup
confirm_data = {
'secret': secret,
'code': '123456' # Code from authenticator app
}
confirm_response = requests.post('/auth/mfa/totp/confirm/', json=confirm_data)# Request password reset
reset_data = {
'email': 'user@example.com'
}
reset_response = requests.post('/auth/password/reset/', json=reset_data)
# Confirm password reset with key from email
confirm_data = {
'key': 'reset_key_from_email',
'password': 'newpassword123'
}
confirm_response = requests.post('/auth/password/reset/confirm/', json=confirm_data)
# Change password (authenticated user)
change_data = {
'current_password': 'oldpassword123',
'new_password': 'newpassword123'
}
headers = {'Authorization': f'Bearer {access_token}'}
change_response = requests.post('/auth/password/change/', json=change_data, headers=headers)class AuthAPI {
constructor(baseURL = '/auth') {
this.baseURL = baseURL;
this.token = localStorage.getItem('auth_token');
}
async login(email, password) {
const response = await fetch(`${this.baseURL}/login/`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email, password})
});
const data = await response.json();
if (data.access_token) {
this.token = data.access_token;
localStorage.setItem('auth_token', this.token);
}
return data;
}
async getUser() {
const response = await fetch(`${this.baseURL}/user/`, {
headers: {'Authorization': `Bearer ${this.token}`}
});
return response.json();
}
async logout() {
await fetch(`${this.baseURL}/logout/`, {
method: 'POST',
headers: {'Authorization': `Bearer ${this.token}`}
});
this.token = null;
localStorage.removeItem('auth_token');
}
}
// Usage
const auth = new AuthAPI();
// Login
auth.login('user@example.com', 'password123')
.then(data => {
if (data.user) {
console.log('Logged in:', data.user);
} else if (data.flow === 'mfa_authenticate') {
// Handle MFA flow
showMFAPrompt(data.mfa_token);
}
});# In Django settings.py
# Enable headless mode
INSTALLED_APPS = [
# ...
'allauth.headless',
]
# Headless-specific settings
HEADLESS_ENABLED = True
HEADLESS_ONLY = False # Set to True to disable traditional views
# Token authentication settings
HEADLESS_TOKEN_STRATEGY = 'allauth.headless.tokens.SessionTokenStrategy'
HEADLESS_TOKEN_LIFETIME = 3600 # 1 hour
# CORS settings for API access
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # React dev server
"https://myapp.com",
]
# URL configuration
urlpatterns = [
path('auth/', include('allauth.headless.urls')),
]Install with Tessl CLI
npx tessl i tessl/pypi-django-allauth