Repository navigation
Expand file tree
/
Copy pathbrowser_signin.py
More file actions
128 lines (102 loc) · 4.28 KB
/
Copy pathbrowser_signin.py
File metadata and controls
128 lines (102 loc) · 4.28 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
"""Browser-consent sign-in with OAuth 2.1 authorization code + PKCE.
Run once and it opens a consent page, captures the redirect on 127.0.0.1, and
writes the grant to disk. Run again and it reuses what it saved.
python examples/browser_signin.py
Two things this example exists to demonstrate, both of which are easy to get
wrong and only fail later:
1. The registered client id is persisted **with its redirect URI**, and the
listener re-binds that exact port on the next run. Authorization servers
match redirect URIs exactly, with no loopback-port exemption.
2. DataGrout rotates refresh tokens, so a refreshed grant is written back. A
grant that is refreshed and not persisted leaves a consumed token on disk,
and the next run fails with ``invalid_grant``.
"""
import asyncio
import json
import os
from pathlib import Path
from typing import Optional, Tuple
from datagrout.conduit import (
AuthCodeFlow,
AuthCodeProvider,
Client,
Grant,
LoopbackListener,
RegisteredClient,
)
GATEWAY = "https://gateway.datagrout.ai/connect"
# Where this example keeps its credentials.
#
# A file, and deliberately called out as such: it holds a refresh token, which
# is a long-lived credential. A real application should prefer the OS keychain.
# The SDK does not choose for you.
STORE = Path.home() / ".config" / "conduit-example" / "signin.json"
def load() -> Optional[Tuple[RegisteredClient, Grant]]:
try:
saved = json.loads(STORE.read_text())
except (OSError, ValueError):
return None
return (
RegisteredClient.from_dict(saved["registered"]),
Grant.from_dict(saved["grant"]),
)
def save(registered: RegisteredClient, grant: Grant) -> None:
STORE.parent.mkdir(parents=True, exist_ok=True)
STORE.write_text(
json.dumps({"registered": registered.to_dict(), "grant": grant.to_dict()}, indent=2)
)
os.chmod(STORE, 0o600)
async def sign_in(
existing: Optional[RegisteredClient] = None,
) -> Tuple[RegisteredClient, Grant]:
"""Run the full consent flow and return something worth persisting."""
# Bind first: the real port has to be known before the redirect URI is
# registered. Reusing a saved registration means re-binding its exact port.
if existing is not None:
try:
listener = await LoopbackListener.bind_for(existing.redirect_uri)
except Exception:
print(f"port for {existing.redirect_uri} is taken — registering a fresh client")
listener = await LoopbackListener.bind()
else:
listener = await LoopbackListener.bind()
async with await AuthCodeFlow.discover(GATEWAY) as flow:
# A saved registration is only reusable if the listener came back on
# its port; otherwise register anew rather than authorize against a URI
# the server will reject.
if existing is not None and listener.redirect_uri == existing.redirect_uri:
flow.with_registered_client(existing)
registered = existing
else:
registered = await flow.register("Conduit Example", listener.redirect_uri)
url, pending = flow.authorize_url()
print(f"\nOpen this URL to sign in:\n\n {url}\n")
redirect = await listener.wait(timeout=300)
grant = await flow.exchange(pending, redirect.code, redirect.state)
return registered, grant
async def main() -> None:
saved = load()
if saved is not None:
print("using the saved sign-in")
registered, grant = saved
else:
registered, grant = await sign_in()
save(registered, grant)
print(f"signed in; credentials written to {STORE}")
# Own the provider so a rotated refresh token can be written back.
provider = AuthCodeProvider(grant)
client = Client(url=GATEWAY, auth={"authorization_code": provider})
await client.connect()
try:
tools = await client.list_tools()
print(f"\n{len(tools)} tools available on this server:")
for tool in tools[:5]:
print(f" - {tool['name']}")
finally:
rotated = provider.take_if_dirty()
if rotated is not None:
save(registered, rotated)
print("\n(the grant was refreshed and re-saved)")
await client.disconnect()
if __name__ == "__main__":
asyncio.run(main())