-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathauthenticator.py
427 lines (329 loc) · 19.4 KB
/
authenticator.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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from __future__ import annotations
import time
import uuid
from functools import wraps
from typing import TYPE_CHECKING, Callable, Optional, TypedDict, TypeVar, cast
from urllib.parse import parse_qs, urlparse
from requests import Response
from typing_extensions import NotRequired, ParamSpec, Unpack
from psnawp_api.core.psnawp_exceptions import PSNAWPAuthenticationError
from psnawp_api.core.request_builder import RequestBuilder
from psnawp_api.utils import API_PATH, BASE_PATH
if TYPE_CHECKING:
from psnawp_api.core.request_builder import RequestBuilderHeaders, RequestOptions
PT = ParamSpec("PT")
RT = TypeVar("RT")
def pre_request_processing(method: Callable[PT, RT]) -> Callable[PT, RT]:
@wraps(method)
def _impl(*method_args: PT.args, **method_kwargs: PT.kwargs) -> RT:
authenticator_obj = cast(Authenticator, method_args[0])
if authenticator_obj.token_response is None:
authorization_code = authenticator_obj.get_authorization_code()
authenticator_obj.fetch_access_token_from_authorization(authorization_code)
else:
authenticator_obj.fetch_access_token_from_refresh()
method_out = method(*method_args, **method_kwargs)
return method_out
return _impl
class TokenResponse(TypedDict):
access_token_expires_at: NotRequired[float]
access_token: str
expires_in: int
id_token: str
refresh_token_expires_at: NotRequired[float]
refresh_token_expires_in: int
refresh_token: str
scope: str
token_type: str
class Authenticator:
"""Provides an interface for PSN Authentication and API"""
__CONSTANTS = {
"CLIENT_ID": "09515159-7237-4370-9b40-3806e67c0891",
"SCOPE": "psn:mobile.v2.core psn:clientapp",
"REDIRECT_URI": "com.scee.psxandroid.scecompcall://redirect",
}
__AUTH_HEADER = {"Authorization": "Basic MDk1MTUxNTktNzIzNy00MzcwLTliNDAtMzgwNmU2N2MwODkxOnVjUGprYTV0bnRCMktxc1A="}
def __init__(
self,
npsso_cookie: str,
common_headers: RequestBuilderHeaders,
):
"""Represents a single authentication to PSN API.
:param npsso_cookie: npsso cookie obtained from PSN website.
:param common_headers: Common headers that will be added to all HTTP request.
"""
self.npsso_token = npsso_cookie
self.common_headers = common_headers
self.request_builder = RequestBuilder(common_headers)
self.token_response: Optional[TokenResponse] = None
self.cid = str(uuid.UUID(int=uuid.getnode()))
@property
def access_token_expiration_time(self) -> float:
"""Get the access token expiration time.
If the ``token_response`` is not available or ``access_token_expires_at``, returns current time.
:returns: The expiration time of the access token as a Unix timestamp.
"""
if self.token_response is None:
return time.time()
return self.token_response.get("access_token_expires_at", time.time())
@property
def refresh_token_expiration_time(self) -> float:
"""Get the refresh token expiration time.
If the ``token_response`` is not available or ``refresh_token_expires_at``, returns current time.
:returns: The expiration time of the refresh token as a Unix timestamp.
"""
if self.token_response is None:
return time.time()
return self.token_response.get("refresh_token_expires_at", time.time())
@property
def access_token_expiration_in(self) -> int:
"""Get the time until the access token expires.
If the ``token_response`` is not available or ``expires_in``, returns 0.
:returns: The number of seconds until the access token expires.
"""
if self.token_response is None:
return 0
return self.token_response.get("expires_in", 0)
@property
def refresh_token_expiration_in(self) -> int:
"""Get the time until the refresh token expires.
If the ``token_response`` is not available or ``refresh_token_expires_in``, returns 0.
:returns: The number of seconds until the refresh token expires.
"""
if self.token_response is None:
return 0
return self.token_response.get("refresh_token_expires_in", 0)
def fetch_access_token_from_refresh(self) -> None:
"""Updates the access token using refresh token."""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to obtain access_token using refresh token when refresh token is missing.")
if self.access_token_expiration_time > time.time():
return None
header = type(self).__AUTH_HEADER | {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "com.sony.snei.np.android.sso.share.oauth.versa.USER_AGENT",
}
data = {
"refresh_token": self.token_response["refresh_token"],
"grant_type": "refresh_token",
"scope": type(self).__CONSTANTS["SCOPE"],
"token_format": "jwt",
}
response = self.request_builder.post(
url=f"{BASE_PATH['base_uri']}{API_PATH['access_token']}",
headers=header,
data=data,
)
self.token_response = cast(TokenResponse, response.json())
self.token_response["access_token_expires_at"] = self.token_response["expires_in"] + time.time()
self.token_response["refresh_token_expires_at"] = self.token_response["refresh_token_expires_in"] + time.time()
def fetch_access_token_from_authorization(self, authorization_code: str) -> None:
"""Obtain the access token using authorization code for the first time, after this the access token is obtained via refresh token.
:param code: Code obtained using npsso code.
"""
header = type(self).__AUTH_HEADER | {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "com.sony.snei.np.android.sso.share.oauth.versa.USER_AGENT",
"X-Psn-Correlation-Id": self.cid,
}
data = {
"cid": self.cid,
"code": authorization_code,
"grant_type": "authorization_code",
"redirect_uri": type(self).__CONSTANTS["REDIRECT_URI"],
"scope": type(self).__CONSTANTS["SCOPE"],
"token_format": "jwt",
}
response = self.request_builder.post(
url=f"{BASE_PATH['base_uri']}{API_PATH['access_token']}",
headers=header,
data=data,
)
self.token_response = cast(TokenResponse, response.json())
self.token_response["access_token_expires_at"] = self.token_response["expires_in"] + time.time()
self.token_response["refresh_token_expires_at"] = self.token_response["refresh_token_expires_in"] + time.time()
def get_authorization_code(self) -> str:
"""Obtains the authorization code for PSN authentication.
Obtains the access code and the refresh code. Access code lasts about 1 hour. While the refresh code lasts about 2 months. After 2 months a new npsso
code is needed.
:raises PSNAWPAuthenticationError: If authorization is not successful.
"""
headers = {
"Cookie": f"npsso={self.npsso_token}",
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "com.scee.psxandroid",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "same-site",
"Sec-Fetch-User": "?1",
}
params = {
"access_type": "offline",
"cid": self.cid,
"client_id": type(self).__CONSTANTS["CLIENT_ID"],
"device_base_font_size": "10",
"device_profile": "mobile",
"elements_visibility": "no_aclink",
"enable_scheme_error_code": "true",
"no_captcha": "true",
"PlatformPrivacyWs1": "minimal",
"redirect_uri": type(self).__CONSTANTS["REDIRECT_URI"],
"response_type": "code",
"scope": type(self).__CONSTANTS["SCOPE"],
"service_entity": "urn:service-entity:psn",
"service_logo": "ps",
"smcid": "psapp:signin",
"support_scheme": "sneiprls",
"turnOnTrustedBrowser": "true",
"ui": "pr",
}
response = self.request_builder.get(
url=f"{BASE_PATH['base_uri']}{API_PATH['oauth_code']}",
headers=headers,
params=params,
allow_redirects=False,
)
location_url = response.headers["location"]
parsed_url = urlparse(location_url)
parsed_query = parse_qs(parsed_url.query)
if "error" in parsed_query.keys():
if "4165" in parsed_query["error_code"]:
raise PSNAWPAuthenticationError("Your npsso code has expired or is incorrect. Please generate a new code!")
else:
raise PSNAWPAuthenticationError("Something went wrong while authenticating")
return parsed_query["code"][0]
@pre_request_processing
def get(self, **kwargs: Unpack[RequestOptions]) -> Response:
"""Make a GET request with automatic Bearer token authorization.
This method simplifies making GET requests by automatically adding the necessary Authorization header with a Bearer token. You can pass any additional
arguments or keyword arguments, which will be forwarded to the underlying request builder's ``get`` method.
:param kwargs: Additional arguments to be forwarded to the ``get`` method of the request builder.
:returns: The response from the GET request.
:raises PSNAWPAuthenticationError: If the ``token_response`` is ``None``, indicating that an attempt to make an HTTP request was made without an access
token.
:raises PSNAWPBadRequest: If the HTTP response status code is 400.
:raises PSNAWPUnauthorized: If the HTTP response status code is 401.
:raises PSNAWPForbidden: If the HTTP response status code is 403.
:raises PSNAWPNotFound: If the HTTP response status code is 404.
:raises PSNAWPNotAllowed: If the HTTP response status code is 405.
:raises PSNAWPTooManyRequests: If the HTTP response status code is 429.
:raises PSNAWPClientError: If the HTTP response status code is in the 4xx range (excluding those listed above).
:raises PSNAWPServerError: If the HTTP response status code is 500 or above.
.. note::
The ``pre_request_processing`` decorator ensures that ``token_response`` is usually set correctly. The check for ``self.token_response is None`` is
a safeguard in case of unexpected issues.
"""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to make HTTP Request without access_token.")
if "headers" not in kwargs:
kwargs["headers"] = {}
kwargs["headers"]["Authorization"] = f"Bearer {self.token_response['access_token']}"
return self.request_builder.get(**kwargs)
@pre_request_processing
def post(self, **kwargs: Unpack[RequestOptions]) -> Response:
"""Make a POST request with automatic Bearer token authorization.
This method simplifies making POST requests by automatically adding the necessary Authorization header with a Bearer token. You can pass any additional
arguments or keyword arguments, which will be forwarded to the underlying request builder's ``post`` method.
:param kwargs: Additional arguments to be forwarded to the ``post`` method of the request builder.
:returns: The response from the POST request.
:raises PSNAWPAuthenticationError: If the ``token_response`` is ``None``, indicating that an attempt to make an HTTP request was made without an access
token.
:raises PSNAWPBadRequest: If the HTTP response status code is 400.
:raises PSNAWPUnauthorized: If the HTTP response status code is 401.
:raises PSNAWPForbidden: If the HTTP response status code is 403.
:raises PSNAWPNotFound: If the HTTP response status code is 404.
:raises PSNAWPNotAllowed: If the HTTP response status code is 405.
:raises PSNAWPTooManyRequests: If the HTTP response status code is 429.
:raises PSNAWPClientError: If the HTTP response status code is in the 4xx range (excluding those listed above).
:raises PSNAWPServerError: If the HTTP response status code is 500 or above.
.. note::
The ``pre_request_processing`` decorator ensures that ``token_response`` is usually set correctly. The check for ``self.token_response is None`` is
a safeguard in case of unexpected issues.
"""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to make HTTP Request without access_token.")
if "headers" not in kwargs:
kwargs["headers"] = {}
kwargs["headers"]["Authorization"] = f"Bearer {self.token_response['access_token']}"
return self.request_builder.post(**kwargs)
@pre_request_processing
def patch(self, **kwargs: Unpack[RequestOptions]) -> Response:
"""Make a PATCH request with automatic Bearer token authorization.
This method simplifies making POST requests by automatically adding the necessary Authorization header with a Bearer token. You can pass any additional
arguments or keyword arguments, which will be forwarded to the underlying request builder's ``patch`` method.
:param kwargs: Additional arguments to be forwarded to the ``patch`` method of the request builder.
:returns: The response from the POST request.
:raises PSNAWPAuthenticationError: If the ``token_response`` is ``None``, indicating that an attempt to make an HTTP request was made without an access
token.
:raises PSNAWPBadRequest: If the HTTP response status code is 400.
:raises PSNAWPUnauthorized: If the HTTP response status code is 401.
:raises PSNAWPForbidden: If the HTTP response status code is 403.
:raises PSNAWPNotFound: If the HTTP response status code is 404.
:raises PSNAWPNotAllowed: If the HTTP response status code is 405.
:raises PSNAWPTooManyRequests: If the HTTP response status code is 429.
:raises PSNAWPClientError: If the HTTP response status code is in the 4xx range (excluding those listed above).
:raises PSNAWPServerError: If the HTTP response status code is 500 or above.
.. note::
The ``pre_request_processing`` decorator ensures that ``token_response`` is usually set correctly. The check for ``self.token_response is None`` is
a safeguard in case of unexpected issues.
"""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to make HTTP Request without access_token.")
if "headers" not in kwargs:
kwargs["headers"] = {}
kwargs["headers"]["Authorization"] = f"Bearer {self.token_response['access_token']}"
return self.request_builder.patch(**kwargs)
@pre_request_processing
def delete(self, **kwargs: Unpack[RequestOptions]) -> Response:
"""Make a DELETE request with automatic Bearer token authorization.
This method simplifies making POST requests by automatically adding the necessary Authorization header with a Bearer token. You can pass any additional
arguments or keyword arguments, which will be forwarded to the underlying request builder's ``delete`` method.
:param kwargs: Additional arguments to be forwarded to the ``delete`` method of the request builder.
:returns: The response from the POST request.
:raises PSNAWPAuthenticationError: If the ``token_response`` is ``None``, indicating that an attempt to make an HTTP request was made without an access
token.
:raises PSNAWPBadRequest: If the HTTP response status code is 400.
:raises PSNAWPUnauthorized: If the HTTP response status code is 401.
:raises PSNAWPForbidden: If the HTTP response status code is 403.
:raises PSNAWPNotFound: If the HTTP response status code is 404.
:raises PSNAWPNotAllowed: If the HTTP response status code is 405.
:raises PSNAWPTooManyRequests: If the HTTP response status code is 429.
:raises PSNAWPClientError: If the HTTP response status code is in the 4xx range (excluding those listed above).
:raises PSNAWPServerError: If the HTTP response status code is 500 or above.
.. note::
The ``pre_request_processing`` decorator ensures that ``token_response`` is usually set correctly. The check for ``self.token_response is None`` is
a safeguard in case of unexpected issues.
"""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to make HTTP Request without access_token.")
if "headers" not in kwargs:
kwargs["headers"] = {}
kwargs["headers"]["Authorization"] = f"Bearer {self.token_response['access_token']}"
return self.request_builder.delete(**kwargs)
@pre_request_processing
def put(self, **kwargs: Unpack[RequestOptions]) -> Response:
"""Make a PUT request with automatic Bearer token authorization.
This method simplifies making PUT requests by automatically adding the necessary Authorization header with a Bearer token. You can pass any additional
arguments or keyword arguments, which will be forwarded to the underlying request builder's ``put`` method.
:param kwargs: Additional arguments to be forwarded to the ``put`` method of the request builder.
:returns: The response from the PUT request.
:raises PSNAWPAuthenticationError: If the ``token_response`` is ``None``, indicating that an attempt to make an HTTP request was made without an access
token.
:raises PSNAWPBadRequest: If the HTTP response status code is 400.
:raises PSNAWPUnauthorized: If the HTTP response status code is 401.
:raises PSNAWPForbidden: If the HTTP response status code is 403.
:raises PSNAWPNotFound: If the HTTP response status code is 404.
:raises PSNAWPNotAllowed: If the HTTP response status code is 405.
:raises PSNAWPTooManyRequests: If the HTTP response status code is 429.
:raises PSNAWPClientError: If the HTTP response status code is in the 4xx range (excluding those listed above).
:raises PSNAWPServerError: If the HTTP response status code is 500 or above.
.. note::
The ``pre_request_processing`` decorator ensures that ``token_response`` is usually set correctly. The check for ``self.token_response is None`` is
a safeguard in case of unexpected issues.
"""
if self.token_response is None:
raise PSNAWPAuthenticationError("Attempt to make HTTP Request without access_token.")
if "headers" not in kwargs:
kwargs["headers"] = {}
kwargs["headers"]["Authorization"] = f"Bearer {self.token_response['access_token']}"
return self.request_builder.put(**kwargs)