Debian Codegraph @

examples/browser_auth.py

raw
1 #!/usr/bin/env python3
2 """
3 Browser-based OAuth authentication helper for Duke Energy.
4
5 This script handles the OAuth flow for Duke Energy's mobile API:
6 1. Generates PKCE challenge and opens browser for login
7 2. User logs in and uses Chrome extension to capture the redirect code
8 3. Script exchanges the authorization code for Duke Energy API tokens
9
10 Prerequisites:
11 - Install the Chrome extension from ./chrome-extension/
12 - See ./chrome-extension/README.md for installation instructions
13
14 Usage:
15 python browser_auth.py
16 """
17
18 import asyncio
19 import json
20 import sys
21 import webbrowser
22
23 import aiohttp
24
25 from aiodukeenergy import Auth0Client, DukeEnergy, DukeEnergyAuth, DukeEnergyAuthError
26
27
28 async def main() -> None:
29 """Run the browser-based OAuth flow."""
30 print("=" * 60)
31 print("Duke Energy Browser OAuth Helper")
32 print("=" * 60)
33 print()
34 print("Prerequisites:")
35 print(" 1. Install the Chrome extension from ./chrome-extension/")
36 print(" 2. Load it as an unpacked extension in chrome://extensions/")
37 print()
38
39 async with aiohttp.ClientSession() as session:
40 # Create Auth0 client
41 auth0_client = Auth0Client(session)
42
43 # Step 1: Get authorization URL
44 print("Step 1: Generating authorization URL...")
45 auth_url, _state, code_verifier = auth0_client.get_authorization_url()
46
47 print()
48 print("Step 2: Opening browser for login...")
49 print()
50 print("If the browser doesn't open, manually visit this URL:")
51 print()
52 print(auth_url)
53 print()
54
55 # Try to open browser
56 webbrowser.open(auth_url)
57
58 print("-" * 60)
59 print("INSTRUCTIONS:")
60 print("-" * 60)
61 print()
62 print("1. Log in with your Duke Energy credentials")
63 print("2. Complete any MFA/verification steps")
64 print("3. After login, the Chrome extension will capture the code")
65 print("4. Copy the authorization code from the extension page")
66 print("5. Paste the code below")
67 print()
68 print("Enter the authorization code:")
69 code = input("> ").strip()
70
71 if not code:
72 print("Error: No code provided")
73 sys.exit(1)
74
75 print()
76 print("Step 3: Exchanging code for Duke Energy tokens...")
77
78 try:
79 # Create auth and authenticate
80 auth = DukeEnergyAuth(session, auth0_client)
81 await auth.authenticate_with_code(code, code_verifier)
82
83 # Get token dict for display/saving
84 token_data = auth.token
85 access_token = token_data.get("access_token", "") if token_data else ""
86 refresh_token = token_data.get("refresh_token", "") if token_data else ""
87 id_token = token_data.get("id_token", "") if token_data else ""
88
89 print()
90 print("=" * 60)
91 print("SUCCESS! Tokens obtained:")
92 print("=" * 60)
93 print()
94 print(f"User ID: {auth.internal_user_id}")
95 print(f"Email: {auth.email}")
96 print()
97 print(f"Access Token ({len(access_token)} chars):")
98 print(f" {access_token[:50]}...{access_token[-20:]}")
99 print()
100 if refresh_token:
101 print(f"Refresh Token ({len(refresh_token)} chars):")
102 print(f" {refresh_token[:50]}...{refresh_token[-20:]}")
103 print()
104
105 # Test fetching accounts
106 print("-" * 60)
107 print("Testing API access - fetching accounts...")
108 client = DukeEnergy(auth)
109 accounts = await client.get_accounts()
110 print(f"Found {len(accounts)} account(s)")
111 for account_num in accounts:
112 print(f" - {account_num}")
113 print()
114
115 # Offer to save tokens
116 print("=" * 60)
117 save = input("Save tokens to file? (y/n): ").strip().lower()
118 if save == "y":
119 filename = "duke_tokens.json"
120 with open(filename, "w") as f:
121 json.dump(token_data, f, indent=2)
122 print(f"Tokens saved to {filename}")
123
124 print()
125 print("Use these tokens with the library:")
126 print()
127 print("import aiohttp")
128 print("from aiodukeenergy import Auth0Client, DukeEnergy, DukeEnergyAuth")
129 print()
130 print("async with aiohttp.ClientSession() as session:")
131 print(" auth0_client = Auth0Client(session)")
132 print(" auth = DukeEnergyAuth(")
133 print(" session,")
134 print(" auth0_client,")
135 print(f' access_token="{access_token[:30]}...",')
136 print(f' refresh_token="{refresh_token[:30]}...",')
137 print(f' id_token="{id_token[:30]}...",')
138 print(" )")
139 print(" client = DukeEnergy(auth)")
140 print(" accounts = await client.get_accounts()")
141
142 except DukeEnergyAuthError as e:
143 print(f"Authentication error: {e}")
144 sys.exit(1)
145 except Exception as e:
146 print(f"Error: {e}")
147 import traceback
148
149 traceback.print_exc()
150 sys.exit(1)
151
152
153 if __name__ == "__main__":
154 asyncio.run(main())