0
# Authentication and Session Management
1
2
Core authentication functionality using Tesla's OAuth 2 Single Sign-On service with support for multiple authentication methods, token caching, and automatic token refresh capabilities.
3
4
## Capabilities
5
6
### Tesla Session Initialization
7
8
Creates and manages the main Tesla API session with OAuth 2 authentication, supporting various configuration options for proxy, timeout, caching, and custom authentication methods.
9
10
```python { .api }
11
class Tesla(OAuth2Session):
12
def __init__(self, email, verify=True, proxy=None, retry=0, timeout=10,
13
user_agent=None, authenticator=None, cache_file='cache.json',
14
cache_loader=None, cache_dumper=None, sso_base_url=None,
15
code_verifier=None, app_user_agent=None, **kwargs):
16
"""
17
Initialize Tesla API session.
18
19
Parameters:
20
- email (str): SSO identity (required)
21
- verify (bool): Verify SSL certificate (default: True)
22
- proxy (str): URL of proxy server (optional)
23
- retry (int or Retry): Number of connection retries or Retry instance (default: 0)
24
- timeout (int): Connect/read timeout in seconds (default: 10)
25
- user_agent (str): The User-Agent string (optional)
26
- authenticator (callable): Function with one argument (authorization URL) that returns redirected URL (optional)
27
- cache_file (str): Path to cache file used by default loader and dumper (default: 'cache.json')
28
- cache_loader (callable): Function that returns the cache dict (optional)
29
- cache_dumper (callable): Function with one argument (cache dict) (optional)
30
- sso_base_url (str): URL of SSO service, use 'https://auth.tesla.cn/' for China region (optional)
31
- code_verifier (str): PKCE code verifier string (optional)
32
- app_user_agent (str): X-Tesla-User-Agent string (optional)
33
- **kwargs: Extra keyword arguments for OAuth2Session constructor
34
"""
35
```
36
37
### Token Management
38
39
Methods for obtaining, refreshing, and managing OAuth 2 tokens with automatic persistence and refresh capabilities.
40
41
```python { .api }
42
def fetch_token(self, token_url='oauth2/v3/token', **kwargs):
43
"""
44
Sign into Tesla's SSO service using Authorization Code grant with PKCE extension.
45
46
Parameters:
47
- token_url (str): Token endpoint URL (default: 'oauth2/v3/token')
48
- authorization_response (str): Authorization response URL (optional)
49
- code_verifier (str): Code verifier cryptographic random string (optional)
50
51
Returns:
52
dict: The token dictionary
53
54
Raises:
55
CustomOAuth2Error: On authentication errors
56
"""
57
58
def refresh_token(self, token_url='oauth2/v3/token', **kwargs):
59
"""
60
Refresh Tesla's SSO token.
61
62
Parameters:
63
- token_url (str): The token endpoint (default: 'oauth2/v3/token')
64
- refresh_token (str): The refresh_token to use (optional)
65
66
Returns:
67
dict: The refreshed token dictionary
68
69
Raises:
70
ValueError: If refresh_token is not set and not authorized
71
ServerError: On server errors
72
"""
73
```
74
75
### Session Management
76
77
Session lifecycle management including logout and connection handling.
78
79
```python { .api }
80
def logout(self, sign_out=False):
81
"""
82
Remove token from cache, return logout URL, and optionally log out using default browser.
83
84
Parameters:
85
- sign_out (bool): Sign out using system's default web browser (default: False)
86
87
Returns:
88
str or None: Logout URL or None if not authorized
89
"""
90
91
def close(self):
92
"""
93
Remove all adapters on close.
94
"""
95
```
96
97
### Authorization URL Generation
98
99
Generate authorization URLs for manual authentication flows with PKCE support.
100
101
```python { .api }
102
def authorization_url(self, url='oauth2/v3/authorize', code_verifier=None, **kwargs):
103
"""
104
Form an authorization URL with PKCE extension for Tesla's SSO service.
105
106
Parameters:
107
- url (str): Authorization endpoint url (default: 'oauth2/v3/authorize')
108
- code_verifier (str): PKCE code verifier string (optional)
109
- state (str): A state string for CSRF protection (optional)
110
111
Returns:
112
str or None: Authorization URL or None if already authorized
113
"""
114
115
@staticmethod
116
def new_code_verifier():
117
"""
118
Generate code verifier for PKCE as per RFC 7636 section 4.1.
119
120
Returns:
121
bytes: Code verifier
122
"""
123
```
124
125
### API Request Methods
126
127
Core API request functionality with endpoint name support and path variable substitution.
128
129
```python { .api }
130
def api(self, name, path_vars=None, **kwargs):
131
"""
132
Convenience method to perform API request for given endpoint name with keyword arguments as parameters.
133
134
Parameters:
135
- name (str): Endpoint name from endpoints.json
136
- path_vars (dict): Path variables for URI substitution (optional)
137
- **kwargs: Parameters for the API call
138
139
Returns:
140
JsonDict or str: API response
141
142
Raises:
143
ValueError: On unknown endpoint name or missing path variables
144
"""
145
146
def request(self, method, url, serialize=True, **kwargs):
147
"""
148
Perform API request with relative URL support, serialization and error message handling.
149
150
Parameters:
151
- method (str): HTTP method to use
152
- url (str): URL to send (relative or absolute)
153
- serialize (bool): (de)serialize request/response body (default: True)
154
- withhold_token (bool): Perform unauthenticated request (optional)
155
- params (dict): URL parameters to append to the URL (optional)
156
- data: The body to attach to the request (optional)
157
- json: JSON for the body to attach to the request (optional)
158
159
Returns:
160
JsonDict or str or requests.Response: Response based on serialize parameter
161
162
Raises:
163
HTTPError: When an error occurs
164
"""
165
```
166
167
### Product List Methods
168
169
Methods to retrieve lists of Tesla products associated with the account.
170
171
```python { .api }
172
def vehicle_list(self):
173
"""
174
Returns a list of Vehicle objects.
175
176
Returns:
177
list[Vehicle]: List of Vehicle objects
178
"""
179
180
def battery_list(self):
181
"""
182
Returns a list of Battery objects.
183
184
Returns:
185
list[Battery]: List of Battery objects
186
"""
187
188
def solar_list(self):
189
"""
190
Returns a list of SolarPanel objects.
191
192
Returns:
193
list[SolarPanel]: List of SolarPanel objects
194
"""
195
```
196
197
### Properties
198
199
Session properties for token and URL management.
200
201
```python { .api }
202
@property
203
def expires_at(self):
204
"""
205
Returns unix time when token needs refreshing.
206
207
Returns:
208
int or None: Unix timestamp of token expiration
209
"""
210
211
@property
212
def auto_refresh_url(self):
213
"""
214
Returns refresh token endpoint URL for auto-renewal access token.
215
216
Returns:
217
str or None: Refresh token endpoint URL
218
"""
219
220
@auto_refresh_url.setter
221
def auto_refresh_url(self, url):
222
"""
223
Sets refresh token endpoint URL for auto-renewal of access token.
224
225
Parameters:
226
- url (str): Refresh token endpoint URL
227
"""
228
```
229
230
## Usage Examples
231
232
### Basic Authentication
233
234
```python
235
import teslapy
236
237
# Basic authentication with email
238
tesla = teslapy.Tesla('elon@tesla.com')
239
if not tesla.authorized:
240
tesla.fetch_token() # Opens browser for authentication
241
242
# Use context manager for automatic cleanup
243
with teslapy.Tesla('elon@tesla.com') as tesla:
244
vehicles = tesla.vehicle_list()
245
```
246
247
### Custom Authentication
248
249
```python
250
import teslapy
251
252
def custom_auth(url):
253
print(f"Open this URL to authenticate: {url}")
254
return input("Enter the redirected URL: ")
255
256
tesla = teslapy.Tesla('elon@tesla.com', authenticator=custom_auth)
257
if not tesla.authorized:
258
tesla.fetch_token()
259
```
260
261
### Staged Authentication
262
263
```python
264
import teslapy
265
266
# First stage - generate URLs
267
tesla = teslapy.Tesla('elon@tesla.com')
268
if not tesla.authorized:
269
state = tesla.new_state()
270
code_verifier = tesla.new_code_verifier()
271
auth_url = tesla.authorization_url(state=state, code_verifier=code_verifier)
272
print(f"Open: {auth_url}")
273
274
tesla.close()
275
276
# Second stage - complete authentication
277
tesla = teslapy.Tesla('elon@tesla.com', state=state, code_verifier=code_verifier)
278
if not tesla.authorized:
279
auth_response = input('Enter URL after authentication: ')
280
tesla.fetch_token(authorization_response=auth_response)
281
```
282
283
### Using Refresh Token
284
285
```python
286
import teslapy
287
288
with teslapy.Tesla('elon@tesla.com') as tesla:
289
if not tesla.authorized:
290
refresh_token = input('Enter SSO refresh token: ')
291
tesla.refresh_token(refresh_token=refresh_token)
292
vehicles = tesla.vehicle_list()
293
```
294
295
### Custom Cache Implementation
296
297
```python
298
import json
299
import sqlite3
300
import teslapy
301
302
def db_load():
303
con = sqlite3.connect('cache.db')
304
cur = con.cursor()
305
cache = {}
306
try:
307
for row in cur.execute('select * from teslapy'):
308
cache[row[0]] = json.loads(row[1])
309
except sqlite3.OperationalError:
310
pass
311
con.close()
312
return cache
313
314
def db_dump(cache):
315
con = sqlite3.connect('cache.db')
316
con.execute('create table if not exists teslapy (email text primary key, data json)')
317
for email, data in cache.items():
318
con.execute('replace into teslapy values (?, ?)', [email, json.dumps(data)])
319
con.commit()
320
con.close()
321
322
with teslapy.Tesla('elon@tesla.com', cache_loader=db_load, cache_dumper=db_dump) as tesla:
323
tesla.fetch_token()
324
```
325
326
## Error Handling
327
328
```python
329
import teslapy
330
331
try:
332
tesla = teslapy.Tesla('elon@tesla.com')
333
vehicles = tesla.vehicle_list()
334
except teslapy.HTTPError as e:
335
print(f"HTTP Error: {e}")
336
except ValueError as e:
337
print(f"Configuration Error: {e}")
338
```