-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_token.py
91 lines (71 loc) · 2.75 KB
/
generate_token.py
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
from http.server import BaseHTTPRequestHandler, HTTPServer
import threading
import time
from urllib.parse import urlparse, parse_qs
import webbrowser
import re
SERVER: HTTPServer | None = None
GOT_TOKEN = False
class SimpleRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if not self.path.startswith("/auth"):
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Not found!")
return
if not "?" in self.path:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<script>let url = window.location.href.replace(\"#\",\"?\");"
b"window.location.replace(url);</script>")
url_parts = urlparse(self.path)
params = parse_qs(url_parts.query, errors="strict")
token = params.get("access_token", None)
if token is None:
self.send_response(400)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Missing OAUTH token!")
return
with open("auth.js") as fp:
lines = fp.readlines()
lines[4] = re.sub(r'oauth = ".*?"', f'oauth = "{token[0]}"', lines[4])
with open("auth.js", "w") as fp:
fp.writelines(lines)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Authorization successful. You can now close this tab.")
self.wfile.write(b"<script>window.close()</script>")
global GOT_TOKEN
GOT_TOKEN = True
def run_server(port=5000):
global SERVER
server_address = ('', port)
httpd = HTTPServer(server_address, SimpleRequestHandler)
SERVER = httpd
httpd.serve_forever()
def main():
server_thread = threading.Thread(target=run_server)
server_thread.start()
try:
with open("CLIENT_ID.txt") as fp:
CLIENT_ID = fp.read()
TWITCH_AUTH_LINK = ("https://id.twitch.tv/oauth2/authorize"
f"?client_id={CLIENT_ID}"
"&redirect_uri=http://localhost:5000/auth"
"&response_type=token"
"&scope=chat:read+chat:edit+channel:read:redemptions+user:read:email")
print("=" * 25)
print("Open this link in your browser, if one doesn't open automatically.")
print(TWITCH_AUTH_LINK)
print("=" * 25)
webbrowser.open_new_tab(TWITCH_AUTH_LINK)
while not GOT_TOKEN:
time.sleep(0.1)
finally:
SERVER.shutdown()
if __name__ == '__main__':
main()