-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcallback_server.py
More file actions
263 lines (224 loc) · 7.65 KB
/
Copy pathcallback_server.py
File metadata and controls
263 lines (224 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""OAuth callback server for handling authorization redirects.
Provides a local HTTP server that receives OAuth authorization callbacks
and extracts the authorization code for token exchange.
"""
import asyncio
import webbrowser
from dataclasses import dataclass
from typing import Optional
from aiohttp import web
@dataclass
class CallbackResult:
"""Result from OAuth callback."""
success: bool
code: Optional[str] = None
state: Optional[str] = None
error: Optional[str] = None
error_description: Optional[str] = None
# HTML templates for callback responses
SUCCESS_HTML = """
<!DOCTYPE html>
<html>
<head>
<title>Authentication Successful</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
text-align: center;
padding: 40px;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
max-width: 400px;
}
.icon { font-size: 64px; margin-bottom: 20px; }
h1 { color: #333; margin-bottom: 10px; }
p { color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="icon">✔</div>
<h1>Authentication Successful!</h1>
<p>You can close this window and return to the terminal.</p>
</div>
</body>
</html>
"""
ERROR_HTML = """
<!DOCTYPE html>
<html>
<head>
<title>Authentication Failed</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.container {
text-align: center;
padding: 40px;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
max-width: 400px;
}
.icon { font-size: 64px; margin-bottom: 20px; }
h1 { color: #333; margin-bottom: 10px; }
p { color: #666; }
.error { color: #e74c3c; font-family: monospace; margin-top: 15px; }
</style>
</head>
<body>
<div class="container">
<div class="icon">❌</div>
<h1>Authentication Failed</h1>
<p>An error occurred during authentication.</p>
<p class="error">{error}</p>
</div>
</body>
</html>
"""
class OAuthCallbackServer:
"""Local HTTP server for OAuth callbacks.
Starts a temporary server on localhost to receive OAuth redirect
with authorization code.
"""
def __init__(self, port: int, callback_path: str = "/auth/callback"):
"""Initialize callback server.
Args:
port: Port to listen on
callback_path: URL path to handle callbacks on
"""
self.port = port
self.callback_path = callback_path
self._result: Optional[CallbackResult] = None
self._callback_received = asyncio.Event()
self._app: Optional[web.Application] = None
self._runner: Optional[web.AppRunner] = None
self._site: Optional[web.TCPSite] = None
async def _handle_callback(self, request: web.Request) -> web.Response:
"""Handle OAuth callback request.
Args:
request: Incoming HTTP request
Returns:
HTML response
"""
# Parse query parameters
query = request.query
# Check for error
error = query.get("error")
if error:
self._result = CallbackResult(
success=False,
error=error,
error_description=query.get("error_description"),
)
self._callback_received.set()
return web.Response(
text=ERROR_HTML.format(error=f"{error}: {query.get('error_description', '')}"),
content_type="text/html",
)
# Extract code and state
code = query.get("code")
state = query.get("state")
if not code:
self._result = CallbackResult(
success=False,
error="missing_code",
error_description="No authorization code in callback",
)
self._callback_received.set()
return web.Response(
text=ERROR_HTML.format(error="No authorization code received"),
content_type="text/html",
)
self._result = CallbackResult(
success=True,
code=code,
state=state,
)
self._callback_received.set()
return web.Response(text=SUCCESS_HTML, content_type="text/html")
async def start(self) -> None:
"""Start the callback server."""
self._app = web.Application()
self._app.router.add_get(self.callback_path, self._handle_callback)
self._runner = web.AppRunner(self._app)
await self._runner.setup()
self._site = web.TCPSite(self._runner, "localhost", self.port)
await self._site.start()
async def stop(self) -> None:
"""Stop the callback server."""
if self._site:
await self._site.stop()
if self._runner:
await self._runner.cleanup()
async def wait_for_callback(self, timeout: float = 300) -> CallbackResult:
"""Wait for OAuth callback.
Args:
timeout: Maximum time to wait in seconds
Returns:
CallbackResult with code or error
Raises:
asyncio.TimeoutError: If timeout expires
"""
try:
await asyncio.wait_for(self._callback_received.wait(), timeout=timeout)
return self._result or CallbackResult(
success=False, error="unknown", error_description="No result received"
)
except asyncio.TimeoutError:
return CallbackResult(
success=False,
error="timeout",
error_description=f"Callback not received within {timeout} seconds",
)
async def __aenter__(self):
"""Async context manager entry."""
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.stop()
async def run_oauth_flow(
auth_url: str,
port: int,
callback_path: str = "/auth/callback",
timeout: float = 300,
open_browser: bool = True,
) -> CallbackResult:
"""Run complete OAuth flow with callback server.
Args:
auth_url: Authorization URL to open
port: Port for callback server to listen on
callback_path: URL path to handle callbacks
timeout: Maximum time to wait for callback
open_browser: Whether to automatically open browser
Returns:
CallbackResult with authorization code or error
"""
async with OAuthCallbackServer(port=port, callback_path=callback_path) as server:
# Open browser
if open_browser:
print("\nOpening browser for authentication...")
webbrowser.open(auth_url)
else:
print(f"\nPlease open this URL in your browser:\n{auth_url}")
print(f"\nWaiting for authentication (timeout: {timeout}s)...")
# Wait for callback
result = await server.wait_for_callback(timeout=timeout)
return result