Skip to content

Commit 282aebc

Browse files
committed
Remove unused code and other suggested changes
1 parent dfe9fba commit 282aebc

File tree

10 files changed

+59
-115
lines changed

10 files changed

+59
-115
lines changed

supertokens_python/recipe/session/access_token.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def get_info_from_access_token(
4747
verify_jwt(jwt_info, jwt_signing_public_key)
4848
payload = jwt_info.payload
4949

50-
validate_access_token_structure(payload, jwt_info.version)
50+
validate_access_token_structure(payload)
5151

5252
session_handle = sanitize_string(payload.get("sessionHandle"))
5353
user_id = sanitize_string(payload.get("userId"))
@@ -85,19 +85,7 @@ def get_info_from_access_token(
8585
raise_try_refresh_token_exception(e)
8686

8787

88-
def validate_access_token_structure(payload: Dict[str, Any], version: int) -> None:
89-
if version >= 3:
90-
if (
91-
not isinstance(payload.get("sub"), str)
92-
or not isinstance(payload.get("exp"), int)
93-
or not isinstance(payload.get("iat"), int)
94-
or not isinstance(payload.get("sessionHandle"), str)
95-
or not isinstance(payload.get("refreshTokenHash1"), str)
96-
):
97-
raise Exception(
98-
"Access token does not contain all the information. Maybe the structure has changed?"
99-
)
100-
88+
def validate_access_token_structure(payload: Dict[str, Any]) -> None:
10189
if (
10290
not isinstance(payload.get("sessionHandle"), str)
10391
or payload.get("userData") is None

supertokens_python/recipe/session/asyncio/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
GetSessionUnauthorizedErrorResult,
3232
GetSessionTryRefreshTokenErrorResult,
3333
GetSessionClaimValidationErrorResult,
34+
GetSessionClaimValidationErrorResponseObject,
3435
CreateNewSessionResult,
3536
GetSessionOkResult,
3637
RefreshSessionOkResult,
@@ -371,8 +372,11 @@ async def get_session_without_request_response(
371372
except SuperTokensError as e:
372373
if isinstance(e, InvalidClaimsError):
373374
return GetSessionClaimValidationErrorResult(
374-
e
375-
) # FIXME: is this correct?
375+
error=e,
376+
response=GetSessionClaimValidationErrorResponseObject(
377+
message="invalid claim", claim_validation_errors=e.payload
378+
),
379+
)
376380
raise e
377381

378382
return res

supertokens_python/recipe/session/cookie_and_header.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
available_token_transfer_methods,
3333
)
3434
from ...logger import log_debug_message
35+
from .utils import HUNDRED_YEARS_IN_MS
3536

3637
if TYPE_CHECKING:
3738
from supertokens_python.framework.request import BaseRequest
@@ -41,7 +42,6 @@
4142
TokenTransferMethod,
4243
TokenType,
4344
SessionConfig,
44-
HUNDRED_YEARS_IN_MS,
4545
)
4646

4747
from json import dumps
@@ -69,13 +69,6 @@ def _set_front_token_in_headers(
6969
)
7070

7171

72-
def front_token_response_mutator(front_token: str):
73-
def mutator(response: BaseResponse):
74-
return _set_front_token_in_headers(response, front_token)
75-
76-
return mutator
77-
78-
7972
def get_cors_allowed_headers():
8073
return [
8174
ANTI_CSRF_HEADER_KEY,

supertokens_python/recipe/session/interfaces.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,6 @@ def __init__(self, request: BaseRequest, transfer_method: TokenTransferMethod):
8888
self.request = request
8989
self.transfer_method = transfer_method
9090

91-
self.response_mutators = [] # TODO: Use this everywhere!
92-
9391

9492
class CreateNewSessionResult:
9593
status = "OK"
@@ -108,7 +106,7 @@ def __init__(self, session: SessionContainer):
108106
class GetSessionUnauthorizedErrorResult:
109107
status = "UNAUTHORISED"
110108

111-
def __init__(self, error: UnauthorisedError):
109+
def __init__(self, error: Exception):
112110
self.error = error
113111

114112

@@ -119,11 +117,24 @@ def __init__(self, error: TryRefreshTokenError):
119117
self.error = error
120118

121119

120+
class GetSessionClaimValidationErrorResponseObject:
121+
def __init__(
122+
self, message: str, claim_validation_errors: List[ClaimValidationError]
123+
):
124+
self.message = message
125+
self.claim_validation_errors = claim_validation_errors
126+
127+
122128
class GetSessionClaimValidationErrorResult:
123129
status = "CLAIM_VALIDATION_ERROR"
124130

125-
def __init__(self, error: InvalidClaimsError):
131+
def __init__(
132+
self,
133+
error: InvalidClaimsError,
134+
response: GetSessionClaimValidationErrorResponseObject,
135+
):
126136
self.error = error
137+
self.response = response
127138

128139

129140
class RefreshSessionOkResult:

supertokens_python/recipe/session/jwt.py

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,15 @@
1111
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
14-
import base64
15-
import json
1614
from base64 import b64decode
1715
from json import dumps, loads
1816
from textwrap import wrap
19-
from typing import Any, Dict, Optional
17+
from typing import Any, Dict
2018

2119
from Crypto.Hash import SHA256
2220
from Crypto.PublicKey import RSA
2321
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
22+
2423
from supertokens_python.utils import utf_base64decode, utf_base64encode
2524

2625
_key_start = "-----BEGIN PUBLIC KEY-----\n"
@@ -47,72 +46,39 @@
4746
class ParsedJWTInfo:
4847
def __init__(
4948
self,
50-
version: int,
5149
raw_token_string: str,
5250
raw_payload: str,
5351
header: str,
5452
payload: Dict[str, Any],
5553
signature: str,
56-
kid: Optional[str],
5754
) -> None:
58-
self.version = version
5955
self.raw_token_string = raw_token_string
6056
self.raw_payload = raw_payload
6157
self.header = header
6258
self.payload = payload
6359
self.signature = signature
64-
self.kid = kid
6560

6661

6762
def parse_jwt_without_signature_verification(jwt: str) -> ParsedJWTInfo:
6863
splitted_input = jwt.split(".")
6964
if len(splitted_input) != 3:
7065
raise Exception("invalid jwt")
7166

72-
# V1 and V2 are functionally identical, plus all legacy tokens should be V2 now.
73-
# So we can assume these defaults:
74-
version = 2
75-
kid = None
76-
# V2 or older tokens didn't save the key id
7767
header, payload, signature = splitted_input
78-
# checking the header
7968
if header not in _allowed_headers:
80-
parsed_header = json.loads(base64.b64decode(header.encode()))
81-
header_version = parsed_header.get("version")
82-
83-
# We have to ensure version is a string, otherwise Number.parseInt can have unexpected results
84-
if not isinstance(header_version, str):
85-
raise Exception("JWT header mismatch")
86-
87-
try:
88-
version = int(header_version)
89-
except ValueError:
90-
version = None
91-
92-
kid = parsed_header.get("kid")
93-
# Number.isInteger returns false for Number.NaN (if it fails to parse the version)
94-
if (
95-
parsed_header["typ"] != "JWT"
96-
or not isinstance(version, int)
97-
or version < 3
98-
or kid is None
99-
):
100-
raise Exception("JWT header mismatch")
69+
raise Exception("jwt header mismatch")
10170

10271
return ParsedJWTInfo(
103-
version=version,
10472
raw_token_string=jwt,
10573
raw_payload=payload,
10674
header=header,
10775
# Ideally we would only parse this after the signature verification is done
10876
# We do this at the start, since we want to check if a token can be a supertokens access token or not.
10977
payload=loads(utf_base64decode(payload)),
11078
signature=signature,
111-
kid=kid, # TODO: How can ever be None since we are checking for it in the above code?
11279
)
11380

11481

115-
# TODO: Should remove
11682
def verify_jwt(info: ParsedJWTInfo, jwt_signing_public_key: str):
11783
public_key = RSA.import_key(
11884
_key_start + "\n".join(wrap(jwt_signing_public_key, width=64)) + _key_end

supertokens_python/recipe/session/recipe.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def __init__(
140140
recipe_id,
141141
app_info,
142142
None,
143-
None, # FIXME
143+
None,
144144
openid_feature_override,
145145
)
146146
recipe_implementation = RecipeImplementation(

supertokens_python/recipe/session/recipe_implementation.py

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,6 @@ def get_jwt_signing_public_key_list(self) -> List[Dict[str, Any]]:
102102
]
103103

104104

105-
LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME = "sIdRefreshToken"
106-
107-
108105
class RecipeImplementation(RecipeInterface): # pylint: disable=too-many-public-methods
109106
def __init__(self, querier: Querier, config: SessionConfig, app_info: AppInfo):
110107
super().__init__()
@@ -296,16 +293,12 @@ async def get_session(
296293
access_token_obj: Optional[ParsedJWTInfo] = None
297294
try:
298295
access_token_obj = parse_jwt_without_signature_verification(access_token)
299-
validate_access_token_structure(
300-
access_token_obj.payload, access_token_obj.version
301-
)
296+
validate_access_token_structure(access_token_obj.payload)
302297
except Exception as e:
303298
log_debug_message(
304299
"getSession: Returning UNAUTHORISED because parsing failed"
305300
)
306-
return GetSessionUnauthorizedErrorResult(
307-
UnauthorisedError(str(e), False)
308-
) # FIXME: Is this correct?
301+
return GetSessionUnauthorizedErrorResult(e)
309302

310303
try:
311304
response = await session_functions.get_session(
@@ -320,14 +313,12 @@ async def get_session(
320313
log_debug_message(
321314
"getSession: Returning TRY_REFRESH_TOKEN_ERROR because of an exception during get_session"
322315
)
323-
return GetSessionUnauthorizedErrorResult(e) # FIXME: Is this correct?
316+
return GetSessionUnauthorizedErrorResult(e)
324317

325318
log_debug_message(
326319
"getSession: Returning UNAUTHORISED because of an exception during get_session"
327320
)
328-
return GetSessionUnauthorizedErrorResult(
329-
UnauthorisedError(str(e), False)
330-
) # FIXME: Is this correct?
321+
return GetSessionUnauthorizedErrorResult(e)
331322

332323
log_debug_message("getSession: Success!")
333324

@@ -340,9 +331,7 @@ async def get_session(
340331
access_token_updated = True
341332
else:
342333
payload = access_token_obj.payload
343-
access_token_str = (
344-
access_token_obj.raw_token_string
345-
) # FIXME: Is this correct?
334+
access_token_str = access_token
346335
expiry_time = response["session"]["expiryTime"]
347336
access_token_updated = False
348337

@@ -384,7 +373,7 @@ async def refresh_session(
384373
log_debug_message("refreshSession: Started")
385374

386375
try:
387-
response = await session_functions.refresh_session( # FIXME: Update the real definition
376+
response = await session_functions.refresh_session(
388377
self,
389378
refresh_token,
390379
anti_csrf_token,
@@ -419,13 +408,12 @@ async def refresh_session(
419408
if isinstance(e, SuperTokensError):
420409
if isinstance(e, TokenTheftError):
421410
return RefreshSessionTokenTheftErrorResult(e)
422-
# FIXME: Is this correct?
423411
if isinstance(e, UnauthorisedError):
424412
return RefreshSessionUnauthorizedResult(e)
425413

426414
return RefreshSessionUnauthorizedResult(
427-
UnauthorisedError("UNAUTHORIZED", clear_tokens=True)
428-
) # FIXME: Is this correct?
415+
UnauthorisedError(str(e), clear_tokens=False)
416+
)
429417

430418
async def revoke_session(
431419
self, session_handle: str, user_context: Dict[str, Any]

supertokens_python/recipe/session/session_class.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
14-
from typing import Any, Dict, List, TypeVar, Union
14+
from typing import Any, Dict, List, TypeVar, Union, Optional
15+
from typing_extensions import TypedDict
1516

1617
from supertokens_python.recipe.session.exceptions import (
1718
raise_invalid_claims_exception,
@@ -31,13 +32,20 @@
3132
SessionClaimValidator,
3233
SessionContainer,
3334
)
34-
from .jwt import parse_jwt_without_signature_verification
3535
from .recipe_implementation import protected_props
3636
from ...framework import BaseRequest
3737

3838
_T = TypeVar("_T")
3939

4040

41+
class GetSessionTokensDangerouslyDict(TypedDict):
42+
accessToken: str
43+
accessAndFrontTokenUpdated: bool
44+
refreshToken: Optional[str]
45+
frontToken: str
46+
antiCsrfToken: Optional[str]
47+
48+
4149
class Session(SessionContainer):
4250
async def attach_to_request_response(
4351
self, request: BaseRequest, transfer_method: TokenTransferMethod
@@ -129,11 +137,13 @@ def get_handle(self, user_context: Union[Dict[str, Any], None] = None) -> str:
129137
def get_access_token(self, user_context: Union[Dict[str, Any], None] = None) -> str:
130138
return self.access_token
131139

132-
def get_all_session_tokens_dangerously(self) -> Dict[str, Any]:
140+
def get_all_session_tokens_dangerously(self) -> GetSessionTokensDangerouslyDict:
133141
return {
134142
"accessToken": self.access_token,
135143
"accessAndFrontTokenUpdated": self.access_token_updated,
136-
"refreshToken": self.refresh_token,
144+
"refreshToken": None
145+
if self.refresh_token is None
146+
else self.refresh_token.token,
137147
"frontToken": self.front_token,
138148
"antiCsrfToken": self.anti_csrf_token,
139149
}
@@ -263,14 +273,7 @@ async def merge_into_access_token_payload(
263273
raise_unauthorised_exception("Session does not exist anymore.")
264274

265275
if response.access_token is not None:
266-
resp_token = parse_jwt_without_signature_verification(
267-
response.access_token.token
268-
)
269-
payload = (
270-
response.session.user_data_in_jwt
271-
if resp_token.version < 3
272-
else resp_token.payload
273-
)
276+
payload = response.session.user_data_in_jwt
274277
self.user_data_in_access_token = payload
275278
self.access_token = response.access_token.token
276279
self.front_token = build_front_token(

supertokens_python/recipe/session/session_functions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ async def get_session(
149149

150150
if (
151151
access_token_info is not None
152-
and not handshake_info.access_token_blacklisting_enabled
152+
and not always_check_core
153153
and access_token_info["parentRefreshTokenHash1"] is None
154154
):
155155
return {

0 commit comments

Comments
 (0)