|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from datetime import datetime, timezone |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import secrets |
| 10 | +from typing import TYPE_CHECKING |
| 11 | + |
| 12 | +from aiohttp.hdrs import METH_GET, METH_POST |
| 13 | +import pkce |
| 14 | +from yarl import URL |
| 15 | + |
| 16 | +from podme_api.auth.client import PodMeDefaultAuthClient |
| 17 | +from podme_api.auth.models import SchibstedCredentials |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from podme_api.auth.models import PodMeUserCredentials |
| 21 | + |
| 22 | +_LOGGER = logging.getLogger(__name__) |
| 23 | + |
| 24 | +CLIENT_ID = "62557b19f552881812b7431c" |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class PodMeMobileAuthClient(PodMeDefaultAuthClient): |
| 29 | + """Default authentication client for PodMe. |
| 30 | +
|
| 31 | + This class handles authentication using Schibsted credentials for the PodMe service. |
| 32 | + """ |
| 33 | + |
| 34 | + device_data = { |
| 35 | + "platform": "Android", |
| 36 | + "userAgent": "Chrome", |
| 37 | + "userAgentVersion": "128.0.0.0", |
| 38 | + "hasLiedOs": "0", |
| 39 | + "hasLiedBrowser": "0", |
| 40 | + "fonts": [ |
| 41 | + "Arial", |
| 42 | + "Courier", |
| 43 | + "Courier New", |
| 44 | + "Georgia", |
| 45 | + "Helvetica", |
| 46 | + "Monaco", |
| 47 | + "Palatino", |
| 48 | + "Tahoma", |
| 49 | + "Times", |
| 50 | + "Times New Roman", |
| 51 | + "Verdana", |
| 52 | + ], |
| 53 | + "plugins": [], |
| 54 | + } |
| 55 | + """Device information for authentication.""" |
| 56 | + |
| 57 | + async def authorize(self, user_credentials: PodMeUserCredentials) -> SchibstedCredentials: |
| 58 | + code_verifier, code_challenge = pkce.generate_pkce_pair() |
| 59 | + response = await self._request( |
| 60 | + "oauth/authorize", |
| 61 | + params={ |
| 62 | + "client_id": CLIENT_ID, |
| 63 | + "redirect_uri": f"pme.podme.{CLIENT_ID}:/login", |
| 64 | + "response_type": "code", |
| 65 | + "scope": "openid offline_access", |
| 66 | + "state": hashlib.sha256(os.urandom(1024)).hexdigest(), |
| 67 | + "nonce": secrets.token_urlsafe(), |
| 68 | + "code_challenge": code_challenge, |
| 69 | + "code_challenge_method": "S256", |
| 70 | + "prompt": "select_account", |
| 71 | + }, |
| 72 | + allow_redirects=False, |
| 73 | + ) |
| 74 | + # Login: step 1/3 |
| 75 | + await self._request("", METH_GET, response.headers.get("Location")) |
| 76 | + # Login: step 2/4 |
| 77 | + response = await self._request( |
| 78 | + "authn/api/settings/csrf", |
| 79 | + params={"client_id": CLIENT_ID}, |
| 80 | + ) |
| 81 | + csrf_token = (await response.json())["data"]["attributes"]["csrfToken"] |
| 82 | + |
| 83 | + # Login: step 3/4 |
| 84 | + response = await self._request( |
| 85 | + "authn/api/identity/email-status", |
| 86 | + method=METH_POST, |
| 87 | + params={"client_id": CLIENT_ID}, |
| 88 | + headers={ |
| 89 | + "X-CSRF-Token": csrf_token, |
| 90 | + "Accept": "application/json", |
| 91 | + }, |
| 92 | + data={ |
| 93 | + "email": user_credentials.email, |
| 94 | + "deviceData": json.dumps(self.device_data), |
| 95 | + }, |
| 96 | + ) |
| 97 | + email_status = await response.json() |
| 98 | + _LOGGER.debug(f"Email status: {email_status}") |
| 99 | + |
| 100 | + # Login: step 4/4 |
| 101 | + response = await self._request( |
| 102 | + "authn/api/identity/login/", |
| 103 | + method=METH_POST, |
| 104 | + params={"client_id": CLIENT_ID}, |
| 105 | + headers={ |
| 106 | + "X-CSRF-Token": csrf_token, |
| 107 | + "Accept": "application/json", |
| 108 | + }, |
| 109 | + data={ |
| 110 | + "username": user_credentials.email, |
| 111 | + "password": user_credentials.password, |
| 112 | + "remember": "true", |
| 113 | + "deviceData": json.dumps(self.device_data), |
| 114 | + }, |
| 115 | + ) |
| 116 | + login_response = await response.json() |
| 117 | + _LOGGER.debug(f"Login response: {login_response}") |
| 118 | + |
| 119 | + # Finalize login |
| 120 | + response = await self._request( |
| 121 | + "authn/identity/finish/", |
| 122 | + method=METH_POST, |
| 123 | + params={"client_id": CLIENT_ID}, |
| 124 | + headers={ |
| 125 | + "Content-Type": "application/x-www-form-urlencoded", |
| 126 | + }, |
| 127 | + data={ |
| 128 | + "deviceData": json.dumps(self.device_data), |
| 129 | + "remember": "true", |
| 130 | + "_csrf": csrf_token, |
| 131 | + "redirectToAccountPage": "", |
| 132 | + }, |
| 133 | + allow_redirects=False, |
| 134 | + ) |
| 135 | + |
| 136 | + # Follow redirect manually |
| 137 | + response = await self._request("", METH_GET, response.headers.get("Location"), allow_redirects=False) |
| 138 | + code = URL(response.headers.get("Location")).query.get("code") |
| 139 | + |
| 140 | + # Request tokens with authorization code |
| 141 | + response = await self._request( |
| 142 | + "oauth/token", |
| 143 | + method=METH_POST, |
| 144 | + headers={ |
| 145 | + "X-OIDC": "v1", |
| 146 | + "X-Region": "NO", # @TODO: Support multiple regions. |
| 147 | + }, |
| 148 | + data={ |
| 149 | + "client_id": CLIENT_ID, |
| 150 | + "grant_type": "authorization_code", |
| 151 | + "code": code, |
| 152 | + "redirect_uri": f"pme.podme.{CLIENT_ID}:/login", |
| 153 | + "code_verifier": code_verifier, |
| 154 | + }, |
| 155 | + allow_redirects=False, |
| 156 | + ) |
| 157 | + |
| 158 | + jwt_cred = await response.json() |
| 159 | + jwt_cred["expiration_time"] = int(datetime.now(tz=timezone.utc).timestamp() + jwt_cred["expires_in"]) |
| 160 | + self.set_credentials(jwt_cred) |
| 161 | + |
| 162 | + _LOGGER.debug("Login successful") |
| 163 | + |
| 164 | + await self.close() |
| 165 | + |
| 166 | + return self._credentials |
| 167 | + |
| 168 | + async def refresh_token(self, credentials: SchibstedCredentials | None = None): |
| 169 | + if credentials is None: |
| 170 | + credentials = self._credentials |
| 171 | + |
| 172 | + response = await self._request( |
| 173 | + "oauth/token", |
| 174 | + method=METH_POST, |
| 175 | + headers={ |
| 176 | + "Host": "payment.schibsted.no", |
| 177 | + "Content-Type": "application/x-www-form-urlencoded", |
| 178 | + "User-Agent": "AccountSDKAndroidWeb/6.4.0 (Linux; Android 15; API 35; Google; sdk_gphone64_arm64)", |
| 179 | + "X-OIDC": "v1", |
| 180 | + "X-Region": "NO", # @TODO: Support multiple regions. |
| 181 | + }, |
| 182 | + data={ |
| 183 | + "client_id": CLIENT_ID, |
| 184 | + "grant_type": "refresh_token", |
| 185 | + "refresh_token": credentials.refresh_token, |
| 186 | + }, |
| 187 | + allow_redirects=False, |
| 188 | + ) |
| 189 | + |
| 190 | + refreshed_credentials = await response.json() |
| 191 | + refreshed_credentials["expiration_time"] = int( |
| 192 | + datetime.now(tz=timezone.utc).timestamp() + refreshed_credentials["expires_in"] |
| 193 | + ) |
| 194 | + self.set_credentials( |
| 195 | + SchibstedCredentials.from_dict( |
| 196 | + { |
| 197 | + **credentials.to_dict(), |
| 198 | + **refreshed_credentials, |
| 199 | + } |
| 200 | + ) |
| 201 | + ) |
| 202 | + |
| 203 | + _LOGGER.debug(f"Refreshed credentials: {self.get_credentials()}") |
| 204 | + |
| 205 | + await self.close() |
| 206 | + |
| 207 | + return self._credentials |
| 208 | + |
| 209 | + def credentials_filename(self): |
| 210 | + return "credentials_mobile.json" |
0 commit comments