or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdcore-config.mdheadless-api.mdindex.mdmfa.mdsocial-authentication.mdtemplate-system.mduser-sessions.md

social-authentication.mddocs/

0

# Social Authentication

1

2

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.

3

4

## Capabilities

5

6

### Models

7

8

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

9

10

```python { .api }

11

class SocialApp(models.Model):

12

"""

13

Configuration for social authentication providers.

14

"""

15

provider: str = models.CharField(max_length=30)

16

provider_id: str = models.CharField(max_length=200, blank=True)

17

name: str = models.CharField(max_length=40)

18

client_id: str = models.CharField(max_length=191)

19

secret: str = models.CharField(max_length=191, blank=True)

20

key: str = models.CharField(max_length=191, blank=True)

21

certificate_key: str = models.TextField(blank=True)

22

settings: dict = models.JSONField(default=dict)

23

24

objects: SocialAppManager

25

26

def __str__(self) -> str: ...

27

28

class SocialAccount(models.Model):

29

"""

30

User's connected social media account.

31

"""

32

user: User = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

33

provider: str = models.CharField(max_length=200)

34

uid: str = models.CharField(max_length=191)

35

last_login: datetime = models.DateTimeField(auto_now=True)

36

date_joined: datetime = models.DateTimeField(auto_now_add=True)

37

extra_data: dict = models.JSONField(default=dict)

38

39

def __str__(self) -> str: ...

40

def get_provider(self): ...

41

def get_provider_account(self): ...

42

43

class SocialToken(models.Model):

44

"""

45

OAuth tokens for social accounts.

46

"""

47

app: SocialApp = models.ForeignKey(SocialApp, on_delete=models.CASCADE)

48

account: SocialAccount = models.ForeignKey(SocialAccount, on_delete=models.CASCADE)

49

token: str = models.TextField()

50

token_secret: str = models.TextField(blank=True)

51

expires_at: Optional[datetime] = models.DateTimeField(null=True, blank=True)

52

53

def __str__(self) -> str: ...

54

```

55

56

### Managers

57

58

Database managers for social app and account queries.

59

60

```python { .api }

61

class SocialAppManager(models.Manager):

62

"""

63

Manager for SocialApp model with site-aware filtering.

64

"""

65

66

def on_site(self, request: HttpRequest) -> QuerySet:

67

"""

68

Filter social apps available on current site.

69

70

Parameters:

71

- request: HTTP request object

72

73

Returns:

74

Filtered queryset of SocialApp instances

75

"""

76

```

77

78

### Views

79

80

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

81

82

```python { .api }

83

class LoginView(View):

84

"""

85

Initiate social authentication login flow.

86

"""

87

88

def dispatch(self, request: HttpRequest, provider: str) -> HttpResponse: ...

89

90

class CallbackView(View):

91

"""

92

Handle OAuth callback from social provider.

93

"""

94

95

def dispatch(self, request: HttpRequest, provider: str) -> HttpResponse: ...

96

97

class SignupView(CloseableSignupMixin, AjaxCapableProcessFormViewMixin, FormView):

98

"""

99

Social account signup with additional information collection.

100

"""

101

template_name: str = "socialaccount/signup.html"

102

form_class: type = SignupForm

103

104

def get_form_kwargs(self) -> Dict[str, Any]: ...

105

def form_valid(self, form: SignupForm) -> HttpResponse: ...

106

107

class ConnectionsView(AjaxCapableProcessFormViewMixin, FormView):

108

"""

109

Manage connected social accounts.

110

"""

111

template_name: str = "socialaccount/connections.html"

112

form_class: type = DisconnectForm

113

114

def get_form_kwargs(self) -> Dict[str, Any]: ...

115

def form_valid(self, form: DisconnectForm) -> HttpResponse: ...

116

117

class LoginCancelledView(TemplateView):

118

"""

119

Handle cancelled social login attempts.

120

"""

121

template_name: str = "socialaccount/login_cancelled.html"

122

123

class LoginErrorView(TemplateView):

124

"""

125

Handle social login errors.

126

"""

127

template_name: str = "socialaccount/login_error.html"

128

```

129

130

### Providers

131

132

Provider registry and base classes for social authentication providers.

133

134

```python { .api }

135

class ProviderRegistry:

136

"""

137

Registry for managing social authentication providers.

138

"""

139

140

def register(self, cls: type) -> None:

141

"""Register a provider class."""

142

143

def get_class(self, provider_id: str) -> Optional[type]:

144

"""Get provider class by ID."""

145

146

def get_class_list(self) -> List[type]:

147

"""Get list of all registered provider classes."""

148

149

def by_id(self, provider_id: str, request: HttpRequest = None):

150

"""Get provider instance by ID."""

151

152

registry: ProviderRegistry

153

154

class Provider:

155

"""

156

Base class for social authentication providers.

157

"""

158

id: str

159

name: str

160

package: str

161

162

def __init__(self, request: HttpRequest, app: SocialApp = None): ...

163

def get_login_url(self, request: HttpRequest, **kwargs) -> str: ...

164

def get_auth_url(self, request: HttpRequest, action: str) -> str: ...

165

def get_callback_url(self, request: HttpRequest, app: SocialApp) -> str: ...

166

167

class OAuth2Provider(Provider):

168

"""

169

Base class for OAuth 2.0 providers.

170

"""

171

supports_state: bool = True

172

pkce_enabled_default: bool = False

173

174

def get_auth_params(self, request: HttpRequest, action: str) -> Dict[str, Any]: ...

175

def get_scope(self, request: HttpRequest) -> List[str]: ...

176

177

class OAuth1Provider(Provider):

178

"""

179

Base class for OAuth 1.0 providers.

180

"""

181

182

def get_request_token(self, request: HttpRequest) -> Dict[str, str]: ...

183

```

184

185

### Adapters

186

187

Customizable adapter classes for social authentication behavior.

188

189

```python { .api }

190

class SocialAccountAdapter:

191

"""

192

Adapter for customizing social authentication behavior.

193

"""

194

195

def new_user(self, request: HttpRequest, sociallogin) -> User:

196

"""

197

Create new user from social login data.

198

199

Parameters:

200

- request: HTTP request object

201

- sociallogin: SocialLogin instance

202

203

Returns:

204

New User instance

205

"""

206

207

def save_user(self, request: HttpRequest, sociallogin, form: forms.Form = None) -> User:

208

"""

209

Save user from social login data.

210

211

Parameters:

212

- request: HTTP request object

213

- sociallogin: SocialLogin instance

214

- form: Optional form data

215

216

Returns:

217

Saved User instance

218

"""

219

220

def populate_user(self, request: HttpRequest, sociallogin, data: Dict[str, Any]) -> User:

221

"""

222

Populate user fields from social account data.

223

224

Parameters:

225

- request: HTTP request object

226

- sociallogin: SocialLogin instance

227

- data: Social account data

228

229

Returns:

230

User instance with populated fields

231

"""

232

233

def get_connect_redirect_url(self, request: HttpRequest, socialaccount: SocialAccount) -> str:

234

"""Get redirect URL after connecting social account."""

235

236

def is_open_for_signup(self, request: HttpRequest, sociallogin) -> bool:

237

"""Check if signup is open for social login."""

238

239

def is_auto_signup_allowed(self, request: HttpRequest, sociallogin) -> bool:

240

"""Check if automatic signup is allowed."""

241

242

def get_adapter(request: HttpRequest = None) -> SocialAccountAdapter:

243

"""

244

Get social account adapter instance.

245

246

Parameters:

247

- request: Optional HTTP request object

248

249

Returns:

250

SocialAccountAdapter instance

251

"""

252

```

253

254

### Provider-Specific Classes

255

256

Individual provider implementations for major social platforms.

257

258

```python { .api }

259

# Google OAuth2

260

class GoogleProvider(OAuth2Provider):

261

id: str = "google"

262

name: str = "Google"

263

264

# Facebook OAuth2

265

class FacebookProvider(OAuth2Provider):

266

id: str = "facebook"

267

name: str = "Facebook"

268

269

# GitHub OAuth2

270

class GitHubProvider(OAuth2Provider):

271

id: str = "github"

272

name: str = "GitHub"

273

274

# Twitter OAuth2

275

class TwitterProvider(OAuth2Provider):

276

id: str = "twitter"

277

name: str = "Twitter"

278

279

# Microsoft OAuth2

280

class MicrosoftProvider(OAuth2Provider):

281

id: str = "microsoft"

282

name: str = "Microsoft"

283

284

# LinkedIn OAuth2

285

class LinkedInProvider(OAuth2Provider):

286

id: str = "linkedin"

287

name: str = "LinkedIn"

288

```

289

290

### Utilities and Helpers

291

292

Helper functions for social authentication flows.

293

294

```python { .api }

295

def complete_social_login(request: HttpRequest, sociallogin) -> HttpResponse:

296

"""

297

Complete social login process.

298

299

Parameters:

300

- request: HTTP request object

301

- sociallogin: SocialLogin instance

302

303

Returns:

304

HTTP response for completed login

305

"""

306

307

def render_authentication_error(request: HttpRequest, provider: Provider, error: str = None, exception: Exception = None, extra_context: Dict[str, Any] = None) -> HttpResponse:

308

"""

309

Render authentication error page.

310

311

Parameters:

312

- request: HTTP request object

313

- provider: Provider instance

314

- error: Error message

315

- exception: Exception instance

316

- extra_context: Additional template context

317

318

Returns:

319

HTTP response with error page

320

"""

321

```

322

323

## Usage Examples

324

325

### Basic Social App Configuration

326

327

```python

328

from allauth.socialaccount.models import SocialApp

329

330

# Create Google OAuth2 app

331

google_app = SocialApp.objects.create(

332

provider='google',

333

name='My App Google Login',

334

client_id='your-google-client-id',

335

secret='your-google-client-secret',

336

settings={

337

'scope': ['email', 'profile']

338

}

339

)

340

341

# Add to current site (if using Django sites)

342

from django.contrib.sites.models import Site

343

current_site = Site.objects.get_current()

344

google_app.sites.add(current_site)

345

```

346

347

### Provider Registration and Usage

348

349

```python

350

from allauth.socialaccount import providers

351

352

# Get provider by ID

353

google_provider = providers.registry.by_id('google', request)

354

355

# Get all available providers

356

provider_classes = providers.registry.get_class_list()

357

358

# Generate login URL

359

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

360

```

361

362

### Social Account Management

363

364

```python

365

from allauth.socialaccount.models import SocialAccount, SocialToken

366

367

# Get user's social accounts

368

social_accounts = SocialAccount.objects.filter(user=user)

369

370

# Get specific provider account

371

try:

372

google_account = SocialAccount.objects.get(user=user, provider='google')

373

print(f"Google UID: {google_account.uid}")

374

print(f"Extra data: {google_account.extra_data}")

375

except SocialAccount.DoesNotExist:

376

print("No Google account connected")

377

378

# Get OAuth tokens

379

tokens = SocialToken.objects.filter(account__user=user, account__provider='google')

380

for token in tokens:

381

print(f"Token: {token.token}")

382

if token.expires_at:

383

print(f"Expires: {token.expires_at}")

384

```

385

386

### Custom Social Adapter

387

388

```python

389

from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

390

391

class MySocialAccountAdapter(DefaultSocialAccountAdapter):

392

def new_user(self, request, sociallogin):

393

user = super().new_user(request, sociallogin)

394

# Custom user initialization

395

return user

396

397

def populate_user(self, request, sociallogin, data):

398

user = super().populate_user(request, sociallogin, data)

399

# Custom field mapping from social data

400

if 'company' in data:

401

user.company = data['company']

402

return user

403

404

def is_auto_signup_allowed(self, request, sociallogin):

405

# Custom auto-signup logic

406

return sociallogin.account.provider == 'google'

407

408

# In settings.py

409

SOCIALACCOUNT_ADAPTER = 'myapp.adapters.MySocialAccountAdapter'

410

```

411

412

### Template Usage

413

414

```html

415

<!-- Login with social providers -->

416

{% load socialaccount %}

417

418

{% get_providers as socialaccount_providers %}

419

{% for provider in socialaccount_providers %}

420

{% if provider.id == "google" %}

421

<a href="{% provider_login_url 'google' process='login' scope='email,profile' %}">

422

Login with Google

423

</a>

424

{% endif %}

425

{% endfor %}

426

427

<!-- Show connected accounts -->

428

{% if user.is_authenticated %}

429

{% for account in user.socialaccount_set.all %}

430

<p>Connected: {{ account.get_provider.name }} ({{ account.uid }})</p>

431

{% endfor %}

432

{% endif %}

433

```

434

435

### Provider Settings Configuration

436

437

```python

438

# In Django settings.py

439

SOCIALACCOUNT_PROVIDERS = {

440

'google': {

441

'SCOPE': [

442

'profile',

443

'email',

444

],

445

'AUTH_PARAMS': {

446

'access_type': 'online',

447

},

448

'OAUTH_PKCE_ENABLED': True,

449

},

450

'facebook': {

451

'METHOD': 'oauth2',

452

'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',

453

'SCOPE': ['email', 'public_profile'],

454

'AUTH_PARAMS': {'auth_type': 'reauthenticate'},

455

'INIT_PARAMS': {'cookie': True},

456

'FIELDS': [

457

'id',

458

'first_name',

459

'last_name',

460

'middle_name',

461

'name',

462

'name_format',

463

'picture',

464

'short_name',

465

'email',

466

],

467

'EXCHANGE_TOKEN': True,

468

'LOCALE_FUNC': 'path.to.callable',

469

'VERIFIED_EMAIL': False,

470

'VERSION': 'v13.0',

471

}

472

}

473

```