Skip to content

Commit 32501bd

Browse files
committed
fix: Self review
1 parent 065a616 commit 32501bd

File tree

7 files changed

+99
-136
lines changed

7 files changed

+99
-136
lines changed

supertokens_python/recipe/session/api/implementation.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ async def refresh_post(
4242
) -> SessionContainer:
4343
return await refresh_session_in_request(
4444
api_options.request,
45-
# api_options.response,
4645
user_context,
4746
api_options.config,
4847
api_options.recipe_implementation,
@@ -80,15 +79,13 @@ async def verify_session(
8079
if incoming_path.equals(refresh_token_path) and method == "post":
8180
return await refresh_session_in_request(
8281
api_options.request,
83-
# api_options.response,
8482
user_context,
8583
api_options.config,
8684
api_options.recipe_implementation,
8785
)
8886

89-
return await get_session_from_request( # FIXME:
87+
return await get_session_from_request(
9088
api_options.request,
91-
# api_options.response,
9289
api_options.config,
9390
api_options.recipe_implementation,
9491
user_context=user_context,

supertokens_python/recipe/session/api/signout.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ async def handle_signout_api(api_implementation: APIInterface, api_options: APIO
3939

4040
session = await get_session_from_request(
4141
api_options.request,
42-
# api_options.response,
4342
api_options.config,
4443
api_options.recipe_implementation,
4544
session_required=False,

supertokens_python/recipe/session/asyncio/__init__.py

Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,14 @@
2828
ClaimsValidationResult,
2929
JSONObject,
3030
GetClaimValueOkResult,
31-
GetSessionUnauthorizedResponse,
32-
GetSessionTryRefreshTokenErrorResponse,
33-
GetSessionClaimValidationErrorResponse,
31+
GetSessionUnauthorizedErrorResult,
32+
GetSessionTryRefreshTokenErrorResult,
33+
GetSessionClaimValidationErrorResult,
3434
CreateNewSessionResult,
35-
GetSessionOkResponse,
36-
RefreshSessionOkResponse,
37-
RefreshSessionUnauthorizedResponse,
38-
RefreshSessionTokenTheftErrorResponse,
35+
GetSessionOkResult,
36+
RefreshSessionOkResult,
37+
RefreshSessionUnauthorizedResult,
38+
RefreshSessionTokenTheftErrorResult,
3939
)
4040
from supertokens_python.recipe.session.recipe import SessionRecipe
4141
from supertokens_python.recipe.session.session_request_functions import (
@@ -57,8 +57,7 @@
5757

5858

5959
async def create_new_session(
60-
request: BaseRequest,
61-
# response: BaseResponse,
60+
request: Any,
6261
user_id: str,
6362
access_token_payload: Union[Dict[str, Any], None] = None,
6463
session_data_in_database: Union[Dict[str, Any], None] = None,
@@ -77,7 +76,6 @@ async def create_new_session(
7776

7877
return await create_new_session_in_request(
7978
request,
80-
# response,
8179
user_context,
8280
recipe_instance,
8381
access_token_payload,
@@ -280,7 +278,6 @@ async def remove_claim(
280278

281279
async def get_session(
282280
request: BaseRequest,
283-
# response: BaseResponse,
284281
session_required: Optional[bool] = None,
285282
anti_csrf_check: Optional[bool] = None,
286283
check_database: Optional[bool] = None,
@@ -301,7 +298,6 @@ async def get_session(
301298

302299
return await get_session_from_request(
303300
request,
304-
# response,
305301
config,
306302
recipe_interface_impl,
307303
session_required=session_required,
@@ -312,7 +308,6 @@ async def get_session(
312308
)
313309

314310

315-
# TODO: Add comments
316311
async def get_session_without_request_response(
317312
access_token: str,
318313
anti_csrf_token: Optional[str] = None,
@@ -326,11 +321,35 @@ async def get_session_without_request_response(
326321
] = None,
327322
user_context: Union[None, Dict[str, Any]] = None,
328323
) -> Union[
329-
GetSessionOkResponse,
330-
GetSessionUnauthorizedResponse,
331-
GetSessionTryRefreshTokenErrorResponse,
332-
GetSessionClaimValidationErrorResponse,
324+
GetSessionOkResult,
325+
GetSessionUnauthorizedErrorResult,
326+
GetSessionTryRefreshTokenErrorResult,
327+
GetSessionClaimValidationErrorResult,
333328
]:
329+
"""Tries to validate an access token and build a Session object from it.
330+
331+
Notes about anti-csrf checking:
332+
- if the `antiCsrf` is set to VIA_HEADER in the Session recipe config you have to handle anti-csrf checking before calling this function and set antiCsrfCheck to false in the options.
333+
- you can disable anti-csrf checks by setting antiCsrf to NONE in the Session recipe config. We only recommend this if you are always getting the access-token from the Authorization header.
334+
- if the antiCsrf check fails the returned status will be TRY_REFRESH_TOKEN_ERROR
335+
336+
args:
337+
- access_token: The access token extracted from the authorization header or cookies
338+
- anti_csrf_token: The anti-csrf token extracted from the authorization header or cookies. Can be undefined if antiCsrfCheck is false
339+
- anti_csrf_check: If true, anti-csrf checking will be done. If false, it will be skipped. Defaults behaviour to check.
340+
- check_database: If true, the session will be checked in the database. If false, it will be skipped. Defaults behaviour to skip.
341+
- override_global_claim_validators: Alter the
342+
- user_context: user context
343+
344+
Returned values:
345+
- GetSessionOkResult: The session was successfully validated, including claim validation
346+
- GetSessionClaimValidationErrorResult: While the access token is valid, one or more claim validators have failed. Our frontend SDKs expect a 403 response the contents matching the value returned from this function.
347+
- GetSessionTryRefreshTokenErrorResult: This means, that the access token structure was valid, but it didn't pass validation for some reason and the user should call the refresh API.
348+
- You can send a 401 response to trigger this behaviour if you are using our frontend SDKs
349+
- GetSessionUnauthorizedErrorResult: This means that the access token likely doesn't belong to a SuperTokens session. If this is unexpected, it's best handled by sending a 401 response.
350+
"""
351+
352+
334353
if user_context is None:
335354
user_context = {}
336355

@@ -345,23 +364,22 @@ async def get_session_without_request_response(
345364
user_context,
346365
)
347366

348-
if isinstance(res, GetSessionOkResponse):
367+
if isinstance(res, GetSessionOkResult):
349368
claim_validators = await get_required_claim_validators(
350369
res.session, override_global_claim_validators, user_context
351370
)
352371
try:
353372
await res.session.assert_claims(claim_validators, user_context)
354373
except SuperTokensError as e:
355374
if isinstance(e, InvalidClaimsError):
356-
return GetSessionClaimValidationErrorResponse(e) # FIXME
375+
return GetSessionClaimValidationErrorResult(e) # FIXME: is this correct?
357376
raise e
358377

359378
return res
360379

361380

362381
async def refresh_session(
363382
request: Any,
364-
# response: BaseResponse,
365383
user_context: Union[None, Dict[str, Any]] = None,
366384
) -> SessionContainer:
367385
if user_context is None:
@@ -372,15 +390,12 @@ async def refresh_session(
372390
SessionRecipe.get_instance().app_info.framework
373391
].wrap_request(request)
374392

375-
# TODO: wrap response if required
376-
377393
recipe_instance = SessionRecipe.get_instance()
378394
config = recipe_instance.config
379395
recipe_interface_impl = recipe_instance.recipe_implementation
380396

381397
return await refresh_session_in_request(
382398
request,
383-
# response,
384399
user_context,
385400
config,
386401
recipe_interface_impl,
@@ -393,9 +408,9 @@ async def refresh_session_without_request_response(
393408
anti_csrf_token: Optional[str] = None,
394409
user_context: Optional[Dict[str, Any]] = None,
395410
) -> Union[
396-
RefreshSessionOkResponse,
397-
RefreshSessionUnauthorizedResponse,
398-
RefreshSessionTokenTheftErrorResponse,
411+
RefreshSessionOkResult,
412+
RefreshSessionUnauthorizedResult,
413+
RefreshSessionTokenTheftErrorResult,
399414
]:
400415
if user_context is None:
401416
user_context = {}

supertokens_python/recipe/session/cookie_and_header.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -321,14 +321,14 @@ def access_token_mutator(
321321
def mutator(
322322
response: BaseResponse,
323323
):
324-
set_access_token_in_response(
324+
_set_access_token_in_response(
325325
response, access_token, front_token, config, transfer_method
326326
)
327327

328328
return mutator
329329

330330

331-
def set_access_token_in_response(
331+
def _set_access_token_in_response(
332332
res: BaseResponse,
333333
access_token: str,
334334
front_token: str,
@@ -361,10 +361,3 @@ def set_access_token_in_response(
361361
get_timestamp_ms() + HUNDRED_YEARS_IN_MS,
362362
"header",
363363
)
364-
365-
366-
def set_anti_csrf_token_in_header(res: BaseResponse, anti_csrf_token: str):
367-
set_header(res, ANTI_CSRF_HEADER_KEY, anti_csrf_token, allow_duplicate=False)
368-
set_header(
369-
res, ACCESS_CONTROL_EXPOSE_HEADERS, ANTI_CSRF_HEADER_KEY, allow_duplicate=True
370-
)

supertokens_python/recipe/session/interfaces.py

Lines changed: 18 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
from supertokens_python.types import APIResponse, GeneralErrorResponse, MaybeAwaitable
3131

3232
from ...utils import resolve
33-
from .exceptions import ClaimValidationError, UnauthorisedError, TokenTheftError
33+
from .exceptions import ClaimValidationError, UnauthorisedError, TokenTheftError, TryRefreshTokenError, \
34+
InvalidClaimsError
3435
from .utils import SessionConfig, TokenTransferMethod
3536

3637
if TYPE_CHECKING:
@@ -77,101 +78,63 @@ def __init__(
7778
self.time_created: int = time_created
7879

7980

80-
# class GetSessionOptions:
81-
# def __init__(
82-
# self,
83-
# anti_csrf_check: Optional[bool] = None,
84-
# check_database: Optional[bool] = None,
85-
# override_global_claim_validators: Optional[
86-
# Callable[
87-
# [List[SessionClaimValidator], SessionContainer, Dict[str, Any]],
88-
# MaybeAwaitable[List[SessionClaimValidator]],
89-
# ]
90-
# ] = None,
91-
# ):
92-
# self.anti_csrf_check = anti_csrf_check
93-
# self.check_database = check_database
94-
# self.override_global_claim_validators = override_global_claim_validators
95-
#
96-
97-
9881
class ReqResInfo:
9982
def __init__(self, request: BaseRequest, transfer_method: TokenTransferMethod):
10083
self.request = request
10184
self.transfer_method = transfer_method
10285

10386
self.response_mutators = [] # TODO: Use this everywhere!
10487

105-
106-
class VerifySessionOptions:
107-
def __init__(
108-
self,
109-
session_required: Optional[bool] = None,
110-
anti_csrf_check: Optional[bool] = None,
111-
check_database: Optional[bool] = None,
112-
override_global_claim_validators: Optional[
113-
Callable[
114-
[List[SessionClaimValidator], SessionContainer, Dict[str, Any]],
115-
MaybeAwaitable[List[SessionClaimValidator]],
116-
]
117-
] = None,
118-
):
119-
self.session_required = session_required
120-
self.anti_csrf_check = anti_csrf_check
121-
self.check_database = check_database
122-
self.override_global_claim_validators = override_global_claim_validators
123-
124-
12588
class CreateNewSessionResult:
12689
status = "OK"
12790

12891
def __init__(self, session: SessionContainer):
12992
self.session = session
13093

13194

132-
class GetSessionOkResponse:
95+
class GetSessionOkResult:
13396
status = "OK"
13497

13598
def __init__(self, session: SessionContainer):
13699
self.session = session
137100

138101

139-
class GetSessionUnauthorizedResponse:
102+
class GetSessionUnauthorizedErrorResult:
140103
status = "UNAUTHORISED"
141104

142-
def __init__(self, error: Exception):
105+
def __init__(self, error: UnauthorisedError):
143106
self.error = error
144107

145108

146-
class GetSessionTryRefreshTokenErrorResponse:
109+
class GetSessionTryRefreshTokenErrorResult:
147110
status = "TRY_REFRESH_TOKEN_ERROR"
148111

149-
def __init__(self, error: Exception):
112+
def __init__(self, error: TryRefreshTokenError):
150113
self.error = error
151114

152115

153-
class GetSessionClaimValidationErrorResponse:
116+
class GetSessionClaimValidationErrorResult:
154117
status = "CLAIM_VALIDATION_ERROR"
155118

156-
def __init__(self, error: Exception):
119+
def __init__(self, error: InvalidClaimsError):
157120
self.error = error
158121

159122

160-
class RefreshSessionOkResponse:
123+
class RefreshSessionOkResult:
161124
status = "OK"
162125

163126
def __init__(self, session: SessionContainer):
164127
self.session = session
165128

166129

167-
class RefreshSessionUnauthorizedResponse:
130+
class RefreshSessionUnauthorizedResult:
168131
status = "UNAUTHORISED"
169132

170133
def __init__(self, error: UnauthorisedError):
171134
self.error = error
172135

173136

174-
class RefreshSessionTokenTheftErrorResponse:
137+
class RefreshSessionTokenTheftErrorResult:
175138
status = "TOKEN_THEFT_ERROR"
176139

177140
def __init__(self, error: TokenTheftError):
@@ -245,9 +208,9 @@ async def get_session(
245208
] = None,
246209
user_context: Optional[Dict[str, Any]] = None,
247210
) -> Union[
248-
GetSessionOkResponse,
249-
GetSessionUnauthorizedResponse,
250-
GetSessionTryRefreshTokenErrorResponse,
211+
GetSessionOkResult,
212+
GetSessionUnauthorizedErrorResult,
213+
GetSessionTryRefreshTokenErrorResult,
251214
]:
252215
pass
253216

@@ -279,9 +242,9 @@ async def refresh_session(
279242
disable_anti_csrf: bool,
280243
user_context: Dict[str, Any],
281244
) -> Union[
282-
RefreshSessionOkResponse,
283-
RefreshSessionUnauthorizedResponse,
284-
RefreshSessionTokenTheftErrorResponse,
245+
RefreshSessionOkResult,
246+
RefreshSessionUnauthorizedResult,
247+
RefreshSessionTokenTheftErrorResult,
285248
]:
286249
pass
287250

0 commit comments

Comments
 (0)