0
# Utilities and Helpers
1
2
Collection of utility functions and helper classes that support the social authentication process. These utilities handle URL manipulation, session management, pipeline data processing, user validation, security operations, and other common tasks used throughout the authentication workflow.
3
4
## Capabilities
5
6
### Module and Import Utilities
7
8
Functions for dynamic module loading and member access by string paths.
9
10
```python { .api }
11
def import_module(name: str):
12
"""
13
Import module by string name.
14
15
Dynamically imports a Python module using its string name,
16
useful for loading backends and pipeline functions from configuration.
17
18
Parameters:
19
- name: Module name string (e.g., 'social_core.backends.google')
20
21
Returns:
22
Imported module object
23
"""
24
25
def module_member(name: str):
26
"""
27
Get module member by dotted path.
28
29
Imports a module and returns a specific member (class, function, variable)
30
using a dotted path notation.
31
32
Parameters:
33
- name: Dotted path to member (e.g., 'social_core.backends.google.GoogleOAuth2')
34
35
Returns:
36
Module member object (class, function, etc.)
37
38
Example:
39
backend_class = module_member('social_core.backends.google.GoogleOAuth2')
40
"""
41
```
42
43
### HTTP and Network Utilities
44
45
Functions for handling HTTP requests, User-Agent strings, and network-related operations.
46
47
```python { .api }
48
def user_agent() -> str:
49
"""
50
Build User-Agent string for HTTP requests.
51
52
Creates a standardized User-Agent header string that identifies
53
requests as coming from social-auth-core with version information.
54
55
Returns:
56
User-Agent string in format 'social-auth-{version}'
57
58
Example:
59
'social-auth-4.7.0'
60
"""
61
```
62
63
### URL Manipulation Utilities
64
65
Functions for URL parsing, parameter manipulation, and validation.
66
67
```python { .api }
68
def url_add_parameters(url: str, params: dict | None, _unquote_query: bool = False) -> str:
69
"""
70
Add parameters to URL query string.
71
72
Appends parameters to a URL's query string, handling existing parameters
73
and proper URL encoding. Parameters will be repeated if already present.
74
75
Parameters:
76
- url: Base URL string
77
- params: Dictionary of parameters to add (optional)
78
- _unquote_query: Whether to unquote existing query parameters (default: False)
79
80
Returns:
81
URL string with added parameters
82
83
Example:
84
url_add_parameters('https://example.com', {'foo': 'bar'})
85
# Returns: 'https://example.com?foo=bar'
86
"""
87
88
def parse_qs(value: str, keep_blank_values: bool = False, strict_parsing: bool = False):
89
"""
90
Parse query string into dictionary.
91
92
Enhanced query string parsing with additional options for handling
93
blank values and strict parsing mode.
94
95
Parameters:
96
- value: Query string to parse
97
- keep_blank_values: Whether to keep parameters with blank values
98
- strict_parsing: Whether to raise errors on parsing failures
99
100
Returns:
101
Dictionary with parameter names as keys and lists of values
102
"""
103
def get_querystring(url: str) -> dict:
104
"""
105
Extract query parameters from URL.
106
107
Parameters:
108
- url: URL string with query parameters
109
110
Returns:
111
Dictionary of query parameters
112
"""
113
114
def drop_lists(value: dict) -> dict:
115
"""
116
Convert list values to single values in dictionary.
117
118
Takes a dictionary that may have list values (like from query parsing)
119
and converts single-item lists to scalar values.
120
121
Parameters:
122
- value: Dictionary with potential list values
123
124
Returns:
125
Dictionary with scalar values where possible
126
"""
127
128
def is_url(value: str) -> bool:
129
"""
130
Check if string is a valid URL.
131
132
Parameters:
133
- value: String to validate
134
135
Returns:
136
Boolean indicating if string is a valid URL
137
"""
138
139
def append_slash(url: str) -> str:
140
"""
141
Add trailing slash to URL if missing.
142
143
Parameters:
144
- url: URL string
145
146
Returns:
147
URL string with trailing slash
148
"""
149
150
def build_absolute_uri(host_url: str, path: str | None = None) -> str:
151
"""
152
Build absolute URI from host and path.
153
154
Parameters:
155
- host_url: Base host URL
156
- path: Optional path to append
157
158
Returns:
159
Complete absolute URI
160
"""
161
```
162
163
### Security and Validation Utilities
164
165
Functions for security operations, redirect validation, and input sanitization.
166
167
```python { .api }
168
def sanitize_redirect(allowed_hosts: list, redirect_uri: str) -> str | None:
169
"""
170
Sanitize redirect URI for security.
171
172
Validates a redirect URI against a list of allowed hosts to prevent
173
open redirect vulnerabilities and malicious redirections.
174
175
Parameters:
176
- allowed_hosts: List of allowed host names/domains
177
- redirect_uri: URI to validate and sanitize
178
179
Returns:
180
Sanitized URI string if valid, None if invalid/unsafe
181
182
Example:
183
sanitize_redirect(['myapp.com'], 'https://myapp.com/dashboard')
184
# Returns: 'https://myapp.com/dashboard'
185
186
sanitize_redirect(['myapp.com'], 'https://evil.com/steal')
187
# Returns: None
188
"""
189
190
def setting_url(backend, name: str, default: str | None = None) -> str:
191
"""
192
Get URL setting with proper validation.
193
194
Retrieves a URL-type setting from backend configuration with
195
validation and default value handling.
196
197
Parameters:
198
- backend: Authentication backend instance
199
- name: Setting name
200
- default: Default URL if setting not found
201
202
Returns:
203
Validated URL string
204
"""
205
206
def constant_time_compare(val1: str, val2: str) -> bool:
207
"""
208
Compare two strings in constant time to prevent timing attacks.
209
210
Parameters:
211
- val1: First string to compare
212
- val2: Second string to compare
213
214
Returns:
215
Boolean indicating if strings are equal
216
"""
217
218
def slugify(value: str) -> str:
219
"""
220
Convert string to URL-safe slug format.
221
222
Parameters:
223
- value: String to slugify
224
225
Returns:
226
URL-safe slug string
227
"""
228
229
def first(func, items):
230
"""
231
Return first item from iterable that matches function.
232
233
Parameters:
234
- func: Function to test items with
235
- items: Iterable of items to test
236
237
Returns:
238
First matching item or None
239
"""
240
241
def handle_http_errors(func):
242
"""
243
Decorator to handle HTTP errors in API requests.
244
245
Parameters:
246
- func: Function to wrap
247
248
Returns:
249
Decorated function that handles HTTP errors
250
"""
251
```
252
253
### User State Utilities
254
255
Functions for checking user authentication and activation status.
256
257
```python { .api }
258
def user_is_authenticated(user) -> bool:
259
"""
260
Check if user is authenticated.
261
262
Framework-agnostic check for user authentication status,
263
handling different user model implementations.
264
265
Parameters:
266
- user: User instance to check
267
268
Returns:
269
Boolean indicating if user is authenticated
270
271
Example:
272
if user_is_authenticated(request.user):
273
# User is logged in
274
pass
275
"""
276
277
def user_is_active(user) -> bool:
278
"""
279
Check if user account is active.
280
281
Framework-agnostic check for user account activation status,
282
handling different user model implementations.
283
284
Parameters:
285
- user: User instance to check
286
287
Returns:
288
Boolean indicating if user account is active
289
290
Example:
291
if user_is_active(user):
292
# User account is enabled
293
pass
294
"""
295
```
296
297
### Pipeline Data Utilities
298
299
Functions for managing partial pipeline data and authentication state.
300
301
```python { .api }
302
def partial_pipeline_data(backend, user, *args, **kwargs):
303
"""
304
Get partial pipeline data for current authentication.
305
306
Retrieves stored partial pipeline data if the current authentication
307
flow was interrupted and needs to be resumed.
308
309
Parameters:
310
- backend: Authentication backend instance
311
- user: Current user instance
312
- Additional arguments from authentication flow
313
314
Returns:
315
Partial pipeline data object or None if no partial data exists
316
317
Example:
318
partial = partial_pipeline_data(backend, user)
319
if partial:
320
# Resume interrupted authentication
321
user = backend.continue_pipeline(partial)
322
"""
323
```
324
325
### Configuration Utilities
326
327
Functions and constants for handling social auth configuration.
328
329
```python { .api }
330
# Configuration constants
331
SETTING_PREFIX: str = "SOCIAL_AUTH"
332
"""
333
Prefix used for all social auth configuration settings.
334
335
All social auth settings follow the pattern:
336
SOCIAL_AUTH_<BACKEND>_<SETTING> or SOCIAL_AUTH_<SETTING>
337
338
Example:
339
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY
340
SOCIAL_AUTH_LOGIN_REDIRECT_URL
341
"""
342
343
PARTIAL_TOKEN_SESSION_NAME: str = "partial_pipeline_token"
344
"""
345
Session key name for storing partial pipeline tokens.
346
347
Used to store tokens that identify interrupted authentication
348
flows that can be resumed later.
349
"""
350
351
def setting_name(backend, name: str) -> str:
352
"""
353
Generate setting name with proper prefixing.
354
355
Creates the full setting name using the social auth prefix
356
and backend-specific naming conventions.
357
358
Parameters:
359
- backend: Authentication backend instance
360
- name: Base setting name
361
362
Returns:
363
Full setting name string
364
365
Example:
366
setting_name(google_backend, 'KEY')
367
# Returns: 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY'
368
"""
369
```
370
371
### Logging Utilities
372
373
Logging configuration and utilities for debugging social authentication.
374
375
```python { .api }
376
social_logger: logging.Logger
377
"""
378
Logger instance for social authentication operations.
379
380
Pre-configured logger with name 'social' for consistent logging
381
across social auth components.
382
383
Example:
384
from social_core.utils import social_logger
385
social_logger.info('Authentication started for user %s', username)
386
"""
387
```
388
389
### String and Data Processing Utilities
390
391
Functions for string manipulation and data processing.
392
393
```python { .api }
394
def slugify_username(username: str) -> str:
395
"""
396
Convert username to URL-safe slug format.
397
398
Processes usernames to remove special characters and create
399
URL-safe versions suitable for use in web applications.
400
401
Parameters:
402
- username: Original username string
403
404
Returns:
405
Slugified username string
406
"""
407
408
def handle_http_errors(func):
409
"""
410
Decorator for handling HTTP errors in backend methods.
411
412
Catches common HTTP exceptions and converts them to
413
appropriate social auth exceptions with better error messages.
414
415
Parameters:
416
- func: Function to wrap with error handling
417
418
Returns:
419
Wrapped function with error handling
420
"""
421
```
422
423
### Cryptographic Utilities
424
425
Functions for cryptographic operations and security.
426
427
```python { .api }
428
def build_absolute_uri(host: str, path: str | None = None) -> str:
429
"""
430
Build absolute URI from host and path components.
431
432
Constructs a complete URI from separate host and path components,
433
handling proper URL formatting and encoding.
434
435
Parameters:
436
- host: Host name or base URL
437
- path: Path component (optional)
438
439
Returns:
440
Complete absolute URI string
441
"""
442
443
def constant_time_compare(val1: str, val2: str) -> bool:
444
"""
445
Compare two strings in constant time.
446
447
Performs string comparison that takes the same amount of time
448
regardless of where the strings differ, preventing timing attacks.
449
450
Parameters:
451
- val1: First string to compare
452
- val2: Second string to compare
453
454
Returns:
455
Boolean indicating if strings are equal
456
"""
457
```
458
459
## Usage Examples
460
461
### Dynamic Backend Loading
462
463
```python
464
from social_core.utils import module_member
465
466
# Load backend class dynamically
467
backend_path = 'social_core.backends.google.GoogleOAuth2'
468
BackendClass = module_member(backend_path)
469
470
# Create backend instance
471
backend = BackendClass(strategy, redirect_uri='/auth/complete/')
472
```
473
474
### URL Parameter Manipulation
475
476
```python
477
from social_core.utils import url_add_parameters
478
479
base_url = 'https://accounts.google.com/oauth/authorize'
480
params = {
481
'client_id': '12345',
482
'redirect_uri': 'https://myapp.com/auth/complete/',
483
'scope': 'openid email profile',
484
'response_type': 'code'
485
}
486
487
auth_url = url_add_parameters(base_url, params)
488
# Result: https://accounts.google.com/oauth/authorize?client_id=12345&redirect_uri=...
489
```
490
491
### Redirect Validation
492
493
```python
494
from social_core.utils import sanitize_redirect
495
496
allowed_hosts = ['myapp.com', 'subdomain.myapp.com']
497
user_redirect = request.GET.get('next', '/')
498
499
safe_redirect = sanitize_redirect(allowed_hosts, user_redirect)
500
if safe_redirect:
501
return redirect(safe_redirect)
502
else:
503
# Invalid redirect, use default
504
return redirect('/')
505
```
506
507
### User State Checking
508
509
```python
510
from social_core.utils import user_is_authenticated, user_is_active
511
512
def require_auth(user):
513
if not user_is_authenticated(user):
514
raise AuthException('User not authenticated')
515
516
if not user_is_active(user):
517
raise AuthException('User account is inactive')
518
519
return user
520
```
521
522
The utilities and helpers provide essential functionality for secure, robust social authentication while maintaining framework independence and security best practices.