pyh0n/pyhon/connection/auth.py

234 lines
9.0 KiB
Python
Raw Normal View History

2023-02-13 06:11:38 +05:30
import json
import logging
import re
import secrets
import urllib
2023-04-10 10:12:40 +05:30
from pprint import pformat
2023-02-13 06:11:38 +05:30
from urllib import parse
2023-04-12 05:39:41 +05:30
from urllib.parse import quote
2023-02-13 06:11:38 +05:30
2023-03-17 06:26:04 +05:30
from yarl import URL
2023-02-13 06:11:38 +05:30
2023-02-13 08:06:09 +05:30
from pyhon import const
from pyhon.exceptions import HonAuthenticationError
2023-02-13 06:11:38 +05:30
2023-04-11 00:01:55 +05:30
_LOGGER = logging.getLogger(__name__)
2023-02-13 06:11:38 +05:30
class HonAuth:
2023-04-09 21:43:50 +05:30
def __init__(self, session, email, password, device) -> None:
self._session = session
self._email = email
self._password = password
2023-03-17 06:26:04 +05:30
self._access_token = ""
self._refresh_token = ""
2023-02-13 06:11:38 +05:30
self._cognito_token = ""
self._id_token = ""
2023-04-09 21:43:50 +05:30
self._device = device
self._called_urls = []
2023-02-13 06:11:38 +05:30
@property
def cognito_token(self):
return self._cognito_token
@property
def id_token(self):
return self._id_token
2023-03-17 06:26:04 +05:30
@property
def access_token(self):
return self._access_token
@property
def refresh_token(self):
return self._refresh_token
async def _error_logger(self, response, fail=True):
result = "hOn Authentication Error\n"
for i, (status, url) in enumerate(self._called_urls):
result += f" {i + 1: 2d} {status} - {url}\n"
result += f"ERROR - {response.status} - {response.request_info.url}\n"
result += f"{15 * '='} Response {15 * '='}\n{await response.text()}\n{40 * '='}"
_LOGGER.error(result)
if fail:
raise HonAuthenticationError("Can't login")
2023-04-09 21:43:50 +05:30
async def _load_login(self):
2023-03-17 06:26:04 +05:30
nonce = secrets.token_hex(16)
nonce = f"{nonce[:8]}-{nonce[8:12]}-{nonce[12:16]}-{nonce[16:20]}-{nonce[20:]}"
params = {
"response_type": "token+id_token",
"client_id": const.CLIENT_ID,
2023-04-10 00:25:36 +05:30
"redirect_uri": urllib.parse.quote(
f"{const.APP}://mobilesdk/detect/oauth/done"
),
2023-03-17 06:26:04 +05:30
"display": "touch",
"scope": "api openid refresh_token web",
2023-04-10 00:25:36 +05:30
"nonce": nonce,
2023-03-17 06:26:04 +05:30
}
params = "&".join([f"{k}={v}" for k, v in params.items()])
2023-04-10 00:25:36 +05:30
async with self._session.get(
f"{const.AUTH_API}/services/oauth2/authorize/expid_Login?{params}"
2023-04-11 00:01:55 +05:30
) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-11 00:01:55 +05:30
if not (login_url := re.findall("url = '(.+?)'", await response.text())):
await self._error_logger(response)
2023-03-17 06:26:04 +05:30
return False
2023-04-09 21:43:50 +05:30
async with self._session.get(login_url[0], allow_redirects=False) as redirect1:
self._called_urls.append((redirect1.status, redirect1.request_info.url))
2023-03-17 06:26:04 +05:30
if not (url := redirect1.headers.get("Location")):
await self._error_logger(redirect1)
2023-03-17 06:26:04 +05:30
return False
2023-04-09 21:43:50 +05:30
async with self._session.get(url, allow_redirects=False) as redirect2:
self._called_urls.append((redirect2.status, redirect2.request_info.url))
2023-04-10 00:25:36 +05:30
if not (
url := redirect2.headers.get("Location")
+ "&System=IoT_Mobile_App&RegistrationSubChannel=hOn"
):
await self._error_logger(redirect2)
2023-03-17 06:26:04 +05:30
return False
2023-04-12 04:37:03 +05:30
async with self._session.get(
URL(url, encoded=True), headers={"user-agent": const.USER_AGENT}
) as login_screen:
self._called_urls.append(
(login_screen.status, login_screen.request_info.url)
)
2023-04-10 00:25:36 +05:30
if context := re.findall(
'"fwuid":"(.*?)","loaded":(\\{.*?})', await login_screen.text()
):
2023-03-17 06:26:04 +05:30
fw_uid, loaded_str = context[0]
loaded = json.loads(loaded_str)
2023-04-10 00:25:36 +05:30
login_url = login_url[0].replace(
"/".join(const.AUTH_API.split("/")[:-1]), ""
)
2023-03-17 06:26:04 +05:30
return fw_uid, loaded, login_url
await self._error_logger(login_screen)
2023-03-17 06:26:04 +05:30
return False
2023-04-09 21:43:50 +05:30
async def _login(self, fw_uid, loaded, login_url):
2023-02-13 06:11:38 +05:30
data = {
"message": {
"actions": [
{
"id": "79;a",
"descriptor": "apex://LightningLoginCustomController/ACTION$login",
"callingDescriptor": "markup://c:loginForm",
"params": {
2023-04-12 05:39:41 +05:30
"username": quote(self._email),
"password": quote(self._password),
2023-04-10 00:25:36 +05:30
"startUrl": parse.unquote(
login_url.split("startURL=")[-1]
).split("%3D")[0],
},
2023-02-13 06:11:38 +05:30
}
]
},
"aura.context": {
"mode": "PROD",
2023-03-17 06:26:04 +05:30
"fwuid": fw_uid,
2023-02-13 06:11:38 +05:30
"app": "siteforce:loginApp2",
2023-03-17 06:26:04 +05:30
"loaded": loaded,
2023-02-13 06:11:38 +05:30
"dn": [],
"globals": {},
2023-04-10 00:25:36 +05:30
"uad": False,
},
2023-03-17 06:26:04 +05:30
"aura.pageURI": login_url,
2023-04-10 00:25:36 +05:30
"aura.token": None,
}
2023-02-13 06:11:38 +05:30
params = {"r": 3, "other.LightningLoginCustom.login": 1}
2023-04-09 21:43:50 +05:30
async with self._session.post(
2023-04-10 00:25:36 +05:30
const.AUTH_API + "/s/sfsites/aura",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data="&".join(f"{k}={json.dumps(v)}" for k, v in data.items()),
params=params,
2023-02-13 06:11:38 +05:30
) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-03-17 06:26:04 +05:30
if response.status == 200:
try:
2023-04-10 10:12:40 +05:30
data = await response.json()
return data["events"][0]["attributes"]["values"]["url"]
2023-03-17 06:26:04 +05:30
except json.JSONDecodeError:
pass
2023-04-10 10:12:40 +05:30
except KeyError:
_LOGGER.error(
"Can't get login url - %s", pformat(await response.json())
)
await self._error_logger(response)
2023-03-17 06:26:04 +05:30
return ""
2023-02-13 06:11:38 +05:30
2023-04-09 21:43:50 +05:30
async def _get_token(self, url):
2023-04-11 00:01:55 +05:30
async with self._session.get(url) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-11 00:01:55 +05:30
if response.status != 200:
await self._error_logger(response)
2023-03-17 06:26:04 +05:30
return False
2023-04-11 00:01:55 +05:30
url = re.findall("href\\s*=\\s*[\"'](.+?)[\"']", await response.text())
if not url:
await self._error_logger(response)
return False
2023-04-11 00:01:55 +05:30
if "ProgressiveLogin" in url[0]:
async with self._session.get(url[0]) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-11 00:01:55 +05:30
if response.status != 200:
await self._error_logger(response)
2023-04-11 00:01:55 +05:30
return False
url = re.findall("href\\s*=\\s*[\"'](.*?)[\"']", await response.text())
url = "/".join(const.AUTH_API.split("/")[:-1]) + url[0]
async with self._session.get(url) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-11 00:01:55 +05:30
if response.status != 200:
await self._error_logger(response)
2023-02-13 06:11:38 +05:30
return False
2023-04-11 00:01:55 +05:30
text = await response.text()
2023-03-17 06:26:04 +05:30
if access_token := re.findall("access_token=(.*?)&", text):
self._access_token = access_token[0]
if refresh_token := re.findall("refresh_token=(.*?)&", text):
self._refresh_token = refresh_token[0]
if id_token := re.findall("id_token=(.*?)&", text):
self._id_token = id_token[0]
2023-02-13 06:11:38 +05:30
return True
2023-04-09 21:43:50 +05:30
async def authorize(self):
if login_site := await self._load_login():
fw_uid, loaded, login_url = login_site
else:
return False
if not (url := await self._login(fw_uid, loaded, login_url)):
return False
if not await self._get_token(url):
return False
2023-04-11 20:39:02 +05:30
return await self._api_auth()
2023-02-13 06:11:38 +05:30
2023-04-11 20:39:02 +05:30
async def _api_auth(self):
2023-04-09 22:13:57 +05:30
post_headers = {"id-token": self._id_token}
2023-04-09 21:43:50 +05:30
data = self._device.get()
2023-04-10 00:25:36 +05:30
async with self._session.post(
f"{const.API_URL}/auth/v1/login", headers=post_headers, json=data
2023-04-11 00:01:55 +05:30
) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-09 21:43:50 +05:30
try:
2023-04-11 00:01:55 +05:30
json_data = await response.json()
2023-04-09 21:43:50 +05:30
except json.JSONDecodeError:
await self._error_logger(response)
2023-04-09 21:43:50 +05:30
return False
self._cognito_token = json_data["cognitoUser"]["Token"]
2023-02-13 06:11:38 +05:30
return True
2023-04-09 22:13:57 +05:30
async def refresh(self):
params = {
"client_id": const.CLIENT_ID,
"refresh_token": self._refresh_token,
2023-04-10 00:25:36 +05:30
"grant_type": "refresh_token",
2023-04-09 22:13:57 +05:30
}
2023-04-10 00:25:36 +05:30
async with self._session.post(
f"{const.AUTH_API}/services/oauth2/token", params=params
2023-04-11 00:01:55 +05:30
) as response:
self._called_urls.append((response.status, response.request_info.url))
2023-04-11 00:01:55 +05:30
if response.status >= 400:
await self._error_logger(response, fail=False)
2023-04-09 22:13:57 +05:30
return False
2023-04-11 00:01:55 +05:30
data = await response.json()
2023-04-10 10:12:40 +05:30
self._id_token = data["id_token"]
self._access_token = data["access_token"]
2023-04-11 20:39:02 +05:30
return await self._api_auth()