0
# Authentication Management
1
2
Token management utilities for handling OpenAI authentication, including automatic login flow, token validation, manual token operations, and session management.
3
4
## Capabilities
5
6
### Token Status Functions
7
8
Utilities for checking and retrieving stored authentication tokens.
9
10
```python { .api }
11
def token_expired() -> bool:
12
"""
13
Check if the stored access token has expired.
14
15
Returns:
16
bool: True if token is expired or missing, False if valid
17
18
Note:
19
Checks token stored in classes/auth.json file. Returns True if
20
file doesn't exist, token is malformed, or expiry time has passed.
21
"""
22
```
23
24
```python { .api }
25
def get_access_token() -> Tuple[str or None, str or None]:
26
"""
27
Retrieve stored access token and expiry time.
28
29
Returns:
30
Tuple[str or None, str or None]: (access_token, expires_at) or (None, None) if not found
31
32
Note:
33
Reads from classes/auth.json file. Returns None values if file
34
doesn't exist or is malformed.
35
"""
36
```
37
38
#### Usage Example
39
40
```python
41
from pychatgpt import OpenAI
42
43
# Check token status
44
if OpenAI.token_expired():
45
print("Token is expired or missing")
46
else:
47
token, expiry = OpenAI.get_access_token()
48
print(f"Token: {token[:20]}...")
49
print(f"Expires at: {expiry}")
50
```
51
52
### Auth Class
53
54
Handles the complete OpenAI authentication flow including login, captcha solving, and token creation.
55
56
```python { .api }
57
class Auth:
58
"""
59
Manages OpenAI authentication through TLS-based login flow.
60
61
Args:
62
email_address (str): OpenAI account email address
63
password (str): OpenAI account password
64
proxy (str, optional): Proxy URL for network requests
65
"""
66
def __init__(
67
self,
68
email_address: str,
69
password: str,
70
proxy: str = None
71
): ...
72
```
73
74
### Token Creation
75
76
Perform the complete authentication flow to create a new access token.
77
78
```python { .api }
79
def create_token(self):
80
"""
81
Execute the full authentication flow to create and save an access token.
82
83
This method handles the complex multi-step OpenAI login process including:
84
- Initial login page request
85
- CSRF token retrieval
86
- Auth0 authentication flow
87
- State token management
88
- Captcha handling (if required)
89
- Access token extraction and storage
90
91
Raises:
92
PyChatGPTException: If email/password not provided
93
Auth0Exception: If authentication steps fail
94
IPAddressRateLimitException: If IP is rate limited
95
96
Note:
97
If captcha is detected, saves captcha.png and prompts user for input.
98
Token is automatically saved to classes/auth.json on success.
99
"""
100
```
101
102
#### Usage Example
103
104
```python
105
from pychatgpt import OpenAI
106
107
# Create authentication handler
108
auth = OpenAI.Auth(
109
email_address="user@example.com",
110
password="your-password"
111
)
112
113
# Optional: use with proxy
114
auth = OpenAI.Auth(
115
email_address="user@example.com",
116
password="your-password",
117
proxy="http://proxy.example.com:8080"
118
)
119
120
try:
121
# Perform authentication flow
122
auth.create_token()
123
print("Authentication successful!")
124
125
# Token is now available
126
token, expiry = OpenAI.get_access_token()
127
print(f"Token created: {token[:20]}...")
128
129
except OpenAI.PyChatGPTException as e:
130
print(f"Authentication failed: {e.message}")
131
```
132
133
### Manual Token Management
134
135
Save access tokens manually for advanced use cases.
136
137
```python { .api }
138
@staticmethod
139
def save_access_token(access_token: str, expiry: int or None = None):
140
"""
141
Manually save an access token with expiry time.
142
143
Args:
144
access_token (str): The access token to save
145
expiry (int, optional): Token expiry timestamp. Defaults to 1 hour from now.
146
147
Raises:
148
Exception: If file operations fail
149
150
Note:
151
Saves token to classes/auth.json file. If expiry is not provided,
152
sets expiry to current time + 3600 seconds (1 hour).
153
"""
154
```
155
156
#### Usage Example
157
158
```python
159
import time
160
from pychatgpt import OpenAI
161
162
# Save a token manually (advanced usage)
163
OpenAI.Auth.save_access_token(
164
access_token="your-token-here",
165
expiry=int(time.time()) + 3600 # Expires in 1 hour
166
)
167
168
# Verify it was saved
169
if not OpenAI.token_expired():
170
print("Token saved successfully")
171
```
172
173
## Authentication Flow Details
174
175
The authentication process involves these steps:
176
177
1. **Initial Request**: GET to https://chat.openai.com/auth/login
178
2. **CSRF Token**: GET to https://chat.openai.com/api/auth/csrf
179
3. **Auth0 Signin**: POST to signin endpoint with CSRF token
180
4. **Login Page**: GET to Auth0 login page with state parameter
181
5. **Captcha Check**: Parse page for captcha requirements
182
6. **Email Submit**: POST email address with optional captcha solution
183
7. **Password Submit**: POST password to complete login
184
8. **Token Extract**: Extract access token from response
185
9. **Token Save**: Store token and expiry to auth.json file
186
187
### Captcha Handling
188
189
When a captcha is detected:
190
191
1. SVG captcha is extracted and converted to PNG
192
2. File saved as `captcha.png` in current directory
193
3. User prompted to solve captcha via console input
194
4. Solution submitted with login credentials
195
196
### Proxy Support
197
198
All authentication requests support proxy configuration:
199
200
```python
201
from pychatgpt import OpenAI
202
203
# String proxy
204
auth = OpenAI.Auth(
205
email_address="user@example.com",
206
password="password",
207
proxy="http://proxy.example.com:8080"
208
)
209
210
# Or as dictionary in Options when using Chat class
211
from pychatgpt import Chat, Options
212
213
options = Options()
214
options.proxies = {
215
"http": "http://proxy.example.com:8080",
216
"https": "https://secure-proxy.example.com:8443"
217
}
218
219
chat = Chat(email="user@example.com", password="password", options=options)
220
```
221
222
### Error Handling
223
224
Authentication can raise several exception types:
225
226
```python
227
from pychatgpt import OpenAI
228
229
try:
230
auth = OpenAI.Auth("user@example.com", "password")
231
auth.create_token()
232
233
except OpenAI.PyChatGPTException as e:
234
print(f"General error: {e.message}")
235
236
except OpenAI.Auth0Exception as e:
237
print(f"Authentication error: {e.message}")
238
239
except OpenAI.IPAddressRateLimitException as e:
240
print(f"Rate limited: {e.message}")
241
print("Try again in a few minutes or use a proxy")
242
```
243
244
### Token Storage
245
246
Tokens are stored in `classes/auth.json` with this format:
247
248
```json
249
{
250
"access_token": "eyJhbGciOiJSUzI1NiIs...",
251
"expires_at": 1683847200
252
}
253
```
254
255
The file is automatically created and managed by the authentication system.