or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-actions.mdauthentication-backends.mdexception-handling.mdindex.mdpipeline-system.mdstorage-models.mdstrategy-interface.mdutilities-helpers.md

authentication-actions.mddocs/

0

# Authentication Actions

1

2

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.

3

4

## Capabilities

5

6

### Authentication Initiation

7

8

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

9

10

```python { .api }

11

def do_auth(backend, redirect_name="next"):

12

"""

13

Initiate authentication flow with the specified backend.

14

15

This function prepares the authentication process by:

16

- Saving request data and configured fields to session

17

- Validating and sanitizing redirect URLs for security

18

- Calling the backend's start() method to begin authentication

19

20

Parameters:

21

- backend: Authentication backend instance (subclass of BaseAuth)

22

- redirect_name: Name of the redirect parameter in request data (default: "next")

23

24

Returns:

25

Backend-specific response, typically a redirect to the provider's auth URL

26

or HTML content for non-redirect flows

27

28

Raises:

29

- AuthException: If authentication cannot be initiated

30

"""

31

```

32

33

**Usage Example:**

34

35

```python

36

from social_core.actions import do_auth

37

from social_core.backends.google import GoogleOAuth2

38

39

# Initialize backend with strategy and redirect URI

40

backend = GoogleOAuth2(strategy, redirect_uri='/auth/complete/google/')

41

42

# Start authentication - returns redirect response to Google OAuth

43

response = do_auth(backend, redirect_name='next')

44

```

45

46

### Authentication Completion

47

48

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

49

50

```python { .api }

51

def do_complete(backend, login, user=None, redirect_name="next", *args, **kwargs):

52

"""

53

Complete authentication flow and return authenticated user.

54

55

This function handles the provider callback by:

56

- Processing partial pipeline data if present

57

- Running the complete authentication pipeline

58

- Calling the login function on successful authentication

59

- Managing session cleanup and redirect handling

60

61

Parameters:

62

- backend: Authentication backend instance (subclass of BaseAuth)

63

- login: Function to call for logging in the user (e.g., Django's login())

64

- user: Current user instance, if any (default: None)

65

- redirect_name: Name of the redirect parameter (default: "next")

66

- *args: Additional arguments passed to backend.complete()

67

- **kwargs: Additional keyword arguments passed to backend.complete()

68

69

Returns:

70

- Authenticated user instance on successful authentication

71

- None if authentication failed

72

- HttpResponse for redirects or partial pipeline interruptions

73

74

Raises:

75

- AuthException: If authentication process fails

76

- Various provider-specific exceptions based on backend implementation

77

"""

78

```

79

80

**Usage Example:**

81

82

```python

83

from social_core.actions import do_complete

84

from social_core.backends.google import GoogleOAuth2

85

from django.contrib.auth import login

86

87

# In your OAuth callback view

88

def auth_complete_google(request):

89

backend = GoogleOAuth2(strategy, redirect_uri='/auth/complete/google/')

90

91

# Complete authentication and login user

92

user = do_complete(

93

backend=backend,

94

login=login,

95

user=request.user if request.user.is_authenticated else None,

96

redirect_name='next',

97

request=request

98

)

99

100

if user:

101

# Authentication successful

102

return redirect(request.GET.get('next', '/dashboard/'))

103

else:

104

# Authentication failed

105

return redirect('/login/?error=auth_failed')

106

```

107

108

### Social Account Disconnection

109

110

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

111

112

```python { .api }

113

def do_disconnect(backend, user, association_id=None, redirect_name="next", *args, **kwargs):

114

"""

115

Disconnect social account association from user.

116

117

This function handles social account disconnection by:

118

- Validating that disconnection is allowed for the user

119

- Running the complete disconnection pipeline

120

- Optionally revoking access tokens at the provider

121

- Removing social account associations from storage

122

123

Parameters:

124

- backend: Authentication backend instance (subclass of BaseAuth)

125

- user: User instance to disconnect social account from

126

- association_id: Optional specific association ID to disconnect (default: None)

127

- redirect_name: Name of the redirect parameter (default: "next")

128

- *args: Additional arguments passed to disconnect pipeline

129

- **kwargs: Additional keyword arguments passed to disconnect pipeline

130

131

Returns:

132

- Dictionary with 'url' key containing redirect URL on success

133

- Dictionary with disconnect results and metadata

134

135

Raises:

136

- NotAllowedToDisconnect: If user cannot disconnect this account

137

- AuthException: If disconnection process fails

138

"""

139

```

140

141

**Usage Example:**

142

143

```python

144

from social_core.actions import do_disconnect

145

from social_core.backends.google import GoogleOAuth2

146

from social_core.exceptions import NotAllowedToDisconnect

147

148

def disconnect_google(request):

149

backend = GoogleOAuth2(strategy)

150

151

try:

152

result = do_disconnect(

153

backend=backend,

154

user=request.user,

155

association_id=request.GET.get('association_id'),

156

redirect_name='next'

157

)

158

159

if 'url' in result:

160

# Redirect after successful disconnection

161

return redirect(result['url'])

162

else:

163

# Disconnection completed

164

return redirect('/profile/?message=disconnected')

165

166

except NotAllowedToDisconnect:

167

# User must keep at least one login method

168

return redirect('/profile/?error=cannot_disconnect')

169

```

170

171

## Integration Patterns

172

173

### Framework Integration

174

175

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

176

177

```python

178

# Django example

179

from social_core.actions import do_auth, do_complete

180

from myapp.strategy import DjangoStrategy

181

182

def auth_start(request, backend_name):

183

strategy = DjangoStrategy(request)

184

backend = strategy.get_backend(backend_name)

185

return do_auth(backend)

186

187

def auth_complete(request, backend_name):

188

strategy = DjangoStrategy(request)

189

backend = strategy.get_backend(backend_name)

190

return do_complete(backend, login, user=request.user)

191

```

192

193

### Error Handling

194

195

Both functions may raise exceptions that should be handled appropriately:

196

197

```python

198

from social_core.exceptions import AuthException, AuthCanceled

199

200

try:

201

user = do_complete(backend, login, user=current_user)

202

except AuthCanceled:

203

# User canceled authentication at provider

204

return redirect('/login/?message=canceled')

205

except AuthException as e:

206

# Other authentication errors

207

return redirect(f'/login/?error={e}')

208

```

209

210

### Session Management

211

212

The authentication actions automatically handle session data including:

213

214

- Storing configured fields from `FIELDS_STORED_IN_SESSION` setting

215

- Managing partial pipeline tokens for multi-step authentication

216

- Preserving redirect URLs with security validation

217

- Cleaning up session data after completion

218

219

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