-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_test.py
More file actions
148 lines (129 loc) · 4.85 KB
/
auth_test.py
File metadata and controls
148 lines (129 loc) · 4.85 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
"""Smoke test: authenticate to DXtrade and fetch account balance."""
import json
import os
import sys
from pathlib import Path
from urllib import request as urlrequest
from urllib.error import HTTPError, URLError
def load_env(path: Path) -> dict:
env = {}
for line in path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
env[k.strip()] = v.strip()
return env
def post_json(url: str, payload: dict, headers: dict | None = None) -> tuple[int, dict | str]:
body = json.dumps(payload).encode("utf-8")
hdrs = {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
}
if headers:
hdrs.update(headers)
req = urlrequest.Request(url, data=body, headers=hdrs, method="POST")
try:
with urlrequest.urlopen(req, timeout=30) as resp:
raw = resp.read().decode("utf-8")
try:
return resp.status, json.loads(raw)
except json.JSONDecodeError:
return resp.status, raw
except HTTPError as e:
raw = e.read().decode("utf-8", errors="replace")
try:
return e.code, json.loads(raw)
except json.JSONDecodeError:
return e.code, raw
except URLError as e:
return -1, f"URLError: {e.reason}"
def get_json(url: str, headers: dict) -> tuple[int, dict | str]:
hdrs = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
}
hdrs.update(headers)
req = urlrequest.Request(url, headers=hdrs, method="GET")
try:
with urlrequest.urlopen(req, timeout=30) as resp:
raw = resp.read().decode("utf-8")
try:
return resp.status, json.loads(raw)
except json.JSONDecodeError:
return resp.status, raw
except HTTPError as e:
raw = e.read().decode("utf-8", errors="replace")
try:
return e.code, json.loads(raw)
except json.JSONDecodeError:
return e.code, raw
except URLError as e:
return -1, f"URLError: {e.reason}"
def try_login(host: str, username: str, password: str, domain: str) -> tuple[int, dict | str]:
url = f"{host}/dxsca-web/login"
return post_json(url, {"username": username, "password": password, "domain": domain})
def main() -> int:
here = Path(__file__).parent
env = load_env(here / ".env")
host = env["DXTRADE_HOST"].rstrip("/")
username = env["DXTRADE_USERNAME"]
password = env["DXTRADE_PASSWORD"]
primary_domain = env.get("DXTRADE_DOMAIN", "default")
account = env.get("DXTRADE_ACCOUNT", "")
candidates = [primary_domain]
for fallback in ("default", "tradeifycrypto", "tradeify"):
if fallback not in candidates:
candidates.append(fallback)
token = None
used_domain = None
last_status = None
last_body = None
for d in candidates:
print(f"[login] trying domain={d!r} ...")
status, body = try_login(host, username, password, d)
last_status, last_body = status, body
print(f" -> HTTP {status}")
if status == 200 and isinstance(body, dict) and "sessionToken" in body:
token = body["sessionToken"]
used_domain = d
break
if status == 200 and isinstance(body, dict):
for k in ("token", "session", "access_token"):
if k in body:
token = body[k]
used_domain = d
break
if token:
break
print(f" body: {body}")
if not token:
print("\n[FAIL] could not obtain session token.")
print(f"last status: {last_status}")
print(f"last body: {last_body}")
return 1
print(f"\n[OK] logged in with domain={used_domain!r}")
print(f"token (first 16 chars): {str(token)[:16]}...")
auth_headers = {
"Authorization": f"DXAPI {token}",
"Accept": "application/json",
}
from urllib.parse import quote
a = quote(account, safe="")
for path in (
f"/dxsca-web/accounts/{a}/metrics",
f"/dxsca-web/accounts/{a}/positions",
f"/dxsca-web/accounts/{a}/orders",
f"/dxsca-web/accounts/{a}/balances",
):
url = f"{host}{path}"
print(f"\n[probe] GET {url}")
status, body = get_json(url, auth_headers)
print(f" -> HTTP {status}")
if isinstance(body, dict):
print(f" body: {json.dumps(body, indent=2)[:1500]}")
else:
print(f" body: {str(body)[:400]}")
return 0
if __name__ == "__main__":
sys.exit(main())