corebase 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- corebase/__init__.py +108 -0
- corebase/_async/__init__.py +1 -0
- corebase/_async/auth_client.py +55 -0
- corebase/_async/client.py +398 -0
- corebase/_sync/__init__.py +1 -0
- corebase/_sync/auth_client.py +55 -0
- corebase/_sync/client.py +393 -0
- corebase/auth/__init__.py +20 -0
- corebase/auth/_async/__init__.py +1 -0
- corebase/auth/_async/gotrue_admin_api.py +356 -0
- corebase/auth/_async/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_async/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_async/gotrue_base_api.py +78 -0
- corebase/auth/_async/gotrue_client.py +1404 -0
- corebase/auth/_async/gotrue_mfa_api.py +94 -0
- corebase/auth/_async/storage.py +31 -0
- corebase/auth/_sync/__init__.py +1 -0
- corebase/auth/_sync/gotrue_admin_api.py +356 -0
- corebase/auth/_sync/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_sync/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_sync/gotrue_base_api.py +78 -0
- corebase/auth/_sync/gotrue_client.py +1394 -0
- corebase/auth/_sync/gotrue_mfa_api.py +94 -0
- corebase/auth/_sync/storage.py +31 -0
- corebase/auth/constants.py +15 -0
- corebase/auth/errors.py +259 -0
- corebase/auth/helpers.py +288 -0
- corebase/auth/py.typed +0 -0
- corebase/auth/timer.py +53 -0
- corebase/auth/types.py +1021 -0
- corebase/auth/version.py +1 -0
- corebase/client.py +12 -0
- corebase/functions/__init__.py +47 -0
- corebase/functions/_async/__init__.py +1 -0
- corebase/functions/_async/functions_client.py +218 -0
- corebase/functions/_sync/__init__.py +1 -0
- corebase/functions/_sync/functions_client.py +218 -0
- corebase/functions/errors.py +62 -0
- corebase/functions/py.typed +0 -0
- corebase/functions/utils.py +33 -0
- corebase/functions/version.py +1 -0
- corebase/lib/__init__.py +3 -0
- corebase/lib/client_options.py +189 -0
- corebase/migrate/__init__.py +374 -0
- corebase/migrate/__main__.py +7 -0
- corebase/postgrest/__init__.py +62 -0
- corebase/postgrest/_async/__init__.py +1 -0
- corebase/postgrest/_async/client.py +206 -0
- corebase/postgrest/_async/request_builder.py +503 -0
- corebase/postgrest/_sync/__init__.py +1 -0
- corebase/postgrest/_sync/client.py +206 -0
- corebase/postgrest/_sync/request_builder.py +503 -0
- corebase/postgrest/base_client.py +61 -0
- corebase/postgrest/base_request_builder.py +787 -0
- corebase/postgrest/constants.py +6 -0
- corebase/postgrest/exceptions.py +115 -0
- corebase/postgrest/py.typed +0 -0
- corebase/postgrest/types.py +72 -0
- corebase/postgrest/utils.py +91 -0
- corebase/postgrest/version.py +1 -0
- corebase/py.typed +0 -0
- corebase/realtime/__init__.py +17 -0
- corebase/realtime/_async/__init__.py +0 -0
- corebase/realtime/_async/channel.py +766 -0
- corebase/realtime/_async/client.py +498 -0
- corebase/realtime/_async/presence.py +185 -0
- corebase/realtime/_async/push.py +162 -0
- corebase/realtime/_async/timer.py +41 -0
- corebase/realtime/_sync/__init__.py +0 -0
- corebase/realtime/_sync/channel.py +30 -0
- corebase/realtime/_sync/client.py +71 -0
- corebase/realtime/_sync/presence.py +10 -0
- corebase/realtime/exceptions.py +38 -0
- corebase/realtime/message.py +176 -0
- corebase/realtime/py.typed +0 -0
- corebase/realtime/transformers.py +9 -0
- corebase/realtime/types.py +246 -0
- corebase/realtime/utils.py +5 -0
- corebase/realtime/version.py +1 -0
- corebase/storage/__init__.py +56 -0
- corebase/storage/_async/__init__.py +1 -0
- corebase/storage/_async/analytics.py +82 -0
- corebase/storage/_async/bucket.py +142 -0
- corebase/storage/_async/client.py +106 -0
- corebase/storage/_async/file_api.py +630 -0
- corebase/storage/_async/request.py +32 -0
- corebase/storage/_async/vectors.py +213 -0
- corebase/storage/_sync/__init__.py +1 -0
- corebase/storage/_sync/analytics.py +80 -0
- corebase/storage/_sync/bucket.py +142 -0
- corebase/storage/_sync/client.py +106 -0
- corebase/storage/_sync/file_api.py +630 -0
- corebase/storage/_sync/request.py +32 -0
- corebase/storage/_sync/vectors.py +199 -0
- corebase/storage/constants.py +16 -0
- corebase/storage/exceptions.py +84 -0
- corebase/storage/py.typed +0 -0
- corebase/storage/types.py +313 -0
- corebase/storage/utils.py +26 -0
- corebase/storage/version.py +1 -0
- corebase/types.py +8 -0
- corebase/version.py +1 -0
- corebase-1.0.0.dist-info/METADATA +78 -0
- corebase-1.0.0.dist-info/RECORD +106 -0
- corebase-1.0.0.dist-info/WHEEL +4 -0
- corebase-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1394 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import cast
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from httpx import Client, QueryParams, Response
|
|
10
|
+
from jwt import get_algorithm_by_name
|
|
11
|
+
|
|
12
|
+
from ..constants import (
|
|
13
|
+
EXPIRY_MARGIN,
|
|
14
|
+
GOTRUE_URL,
|
|
15
|
+
MAX_RETRIES,
|
|
16
|
+
STORAGE_KEY,
|
|
17
|
+
)
|
|
18
|
+
from ..errors import (
|
|
19
|
+
AuthApiError,
|
|
20
|
+
AuthImplicitGrantRedirectError,
|
|
21
|
+
AuthInvalidCredentialsError,
|
|
22
|
+
AuthInvalidJwtError,
|
|
23
|
+
AuthRetryableError,
|
|
24
|
+
AuthSessionMissingError,
|
|
25
|
+
UserDoesntExist,
|
|
26
|
+
)
|
|
27
|
+
from ..helpers import (
|
|
28
|
+
_parse_url_params,
|
|
29
|
+
decode_jwt,
|
|
30
|
+
generate_pkce_challenge,
|
|
31
|
+
generate_pkce_verifier,
|
|
32
|
+
parse_auth_otp_response,
|
|
33
|
+
parse_auth_response,
|
|
34
|
+
parse_jwks,
|
|
35
|
+
parse_link_identity_response,
|
|
36
|
+
parse_sso_response,
|
|
37
|
+
parse_user_response,
|
|
38
|
+
validate_exp,
|
|
39
|
+
)
|
|
40
|
+
from ..timer import Timer
|
|
41
|
+
from ..types import (
|
|
42
|
+
JWK,
|
|
43
|
+
AMREntry,
|
|
44
|
+
AuthChangeEvent,
|
|
45
|
+
AuthFlowType,
|
|
46
|
+
AuthMFAChallengeResponse,
|
|
47
|
+
AuthMFAEnrollResponse,
|
|
48
|
+
AuthMFAGetAuthenticatorAssuranceLevelResponse,
|
|
49
|
+
AuthMFAListFactorsResponse,
|
|
50
|
+
AuthMFAUnenrollResponse,
|
|
51
|
+
AuthMFAVerifyResponse,
|
|
52
|
+
AuthOtpResponse,
|
|
53
|
+
AuthResponse,
|
|
54
|
+
ClaimsResponse,
|
|
55
|
+
CodeExchangeParams,
|
|
56
|
+
IdentitiesResponse,
|
|
57
|
+
JWKSet,
|
|
58
|
+
MFAChallengeAndVerifyParams,
|
|
59
|
+
MFAChallengeParams,
|
|
60
|
+
MFAEnrollParams,
|
|
61
|
+
MFAUnenrollParams,
|
|
62
|
+
MFAVerifyParams,
|
|
63
|
+
OAuthResponse,
|
|
64
|
+
Options,
|
|
65
|
+
Provider,
|
|
66
|
+
ResendCredentials,
|
|
67
|
+
Session,
|
|
68
|
+
SignInAnonymouslyCredentials,
|
|
69
|
+
SignInWithEmailAndPasswordlessCredentialsOptions,
|
|
70
|
+
SignInWithIdTokenCredentials,
|
|
71
|
+
SignInWithOAuthCredentials,
|
|
72
|
+
SignInWithPasswordCredentials,
|
|
73
|
+
SignInWithPasswordlessCredentials,
|
|
74
|
+
SignInWithPhoneAndPasswordlessCredentialsOptions,
|
|
75
|
+
SignInWithSSOCredentials,
|
|
76
|
+
SignOutOptions,
|
|
77
|
+
SignUpWithEmailAndPasswordCredentialsOptions,
|
|
78
|
+
SignUpWithPasswordCredentials,
|
|
79
|
+
SignUpWithPhoneAndPasswordCredentialsOptions,
|
|
80
|
+
SSOResponse,
|
|
81
|
+
Subscription,
|
|
82
|
+
UpdateUserOptions,
|
|
83
|
+
UserAttributes,
|
|
84
|
+
UserIdentity,
|
|
85
|
+
UserResponse,
|
|
86
|
+
VerifyOtpParams,
|
|
87
|
+
)
|
|
88
|
+
from ..version import __version__
|
|
89
|
+
from .gotrue_admin_api import SyncGoTrueAdminAPI
|
|
90
|
+
from .gotrue_base_api import SyncGoTrueBaseAPI
|
|
91
|
+
from .gotrue_mfa_api import SyncGoTrueMFAAPI
|
|
92
|
+
from .storage import SyncMemoryStorage, SyncSupportedStorage
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _is_signed_out_error(error: Exception) -> bool:
|
|
96
|
+
# The session is already gone server side (expired or invalid JWT, or the
|
|
97
|
+
# user was deleted), so the sign out has the effect the caller asked for.
|
|
98
|
+
return isinstance(error, AuthSessionMissingError) or (
|
|
99
|
+
isinstance(error, AuthApiError) and error.status in (401, 403, 404)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class SyncGoTrueClient(SyncGoTrueBaseAPI):
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
*,
|
|
107
|
+
url: str | None = None,
|
|
108
|
+
headers: dict[str, str] | None = None,
|
|
109
|
+
storage_key: str | None = None,
|
|
110
|
+
auto_refresh_token: bool = True,
|
|
111
|
+
persist_session: bool = True,
|
|
112
|
+
storage: SyncSupportedStorage | None = None,
|
|
113
|
+
http_client: Client | None = None,
|
|
114
|
+
flow_type: AuthFlowType = "implicit",
|
|
115
|
+
verify: bool = True,
|
|
116
|
+
proxy: str | None = None,
|
|
117
|
+
) -> None:
|
|
118
|
+
extra_headers = {
|
|
119
|
+
"X-Client-Info": (
|
|
120
|
+
f"corebase-py/supabase_auth v{__version__}"
|
|
121
|
+
f"; platform={platform.system()}"
|
|
122
|
+
f"; platform-version={platform.release()}"
|
|
123
|
+
f"; runtime=python"
|
|
124
|
+
f"; runtime-version={platform.python_version()}"
|
|
125
|
+
),
|
|
126
|
+
}
|
|
127
|
+
if headers:
|
|
128
|
+
extra_headers.update(headers)
|
|
129
|
+
|
|
130
|
+
SyncGoTrueBaseAPI.__init__(
|
|
131
|
+
self,
|
|
132
|
+
url=url or GOTRUE_URL,
|
|
133
|
+
headers=extra_headers,
|
|
134
|
+
http_client=http_client,
|
|
135
|
+
verify=verify,
|
|
136
|
+
proxy=proxy,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
self._jwks: JWKSet = {"keys": []}
|
|
140
|
+
self._jwks_ttl: float = 600 # 10 minutes
|
|
141
|
+
self._jwks_cached_at: float | None = None
|
|
142
|
+
|
|
143
|
+
self._storage_key = storage_key or STORAGE_KEY
|
|
144
|
+
self._auto_refresh_token = auto_refresh_token
|
|
145
|
+
self._persist_session = persist_session
|
|
146
|
+
self._storage = storage or SyncMemoryStorage()
|
|
147
|
+
self._in_memory_session: Session | None = None
|
|
148
|
+
self._refresh_token_timer: Timer | None = None
|
|
149
|
+
self._network_retries = 0
|
|
150
|
+
self._state_change_emitters: dict[str, Subscription] = {}
|
|
151
|
+
self._flow_type = flow_type
|
|
152
|
+
|
|
153
|
+
self.admin = SyncGoTrueAdminAPI(
|
|
154
|
+
url=self._url,
|
|
155
|
+
headers=self._headers,
|
|
156
|
+
http_client=self._http_client,
|
|
157
|
+
)
|
|
158
|
+
# TODO(@o-santi): why is it like this?
|
|
159
|
+
self.mfa = SyncGoTrueMFAAPI()
|
|
160
|
+
self.mfa.challenge = self._challenge # type: ignore[method-assign]
|
|
161
|
+
self.mfa.challenge_and_verify = self._challenge_and_verify # type: ignore[method-assign]
|
|
162
|
+
self.mfa.enroll = self._enroll # type: ignore[method-assign]
|
|
163
|
+
self.mfa.get_authenticator_assurance_level = ( # type: ignore[method-assign]
|
|
164
|
+
self._get_authenticator_assurance_level
|
|
165
|
+
)
|
|
166
|
+
self.mfa.list_factors = self._list_factors # type: ignore[method-assign]
|
|
167
|
+
self.mfa.unenroll = self._unenroll # type: ignore[method-assign]
|
|
168
|
+
self.mfa.verify = self._verify # type: ignore[method-assign]
|
|
169
|
+
|
|
170
|
+
# Initializations
|
|
171
|
+
|
|
172
|
+
def initialize(self, *, url: str | None = None) -> None:
|
|
173
|
+
if url and self._is_implicit_grant_flow(url):
|
|
174
|
+
self.initialize_from_url(url)
|
|
175
|
+
else:
|
|
176
|
+
self.initialize_from_storage()
|
|
177
|
+
|
|
178
|
+
def initialize_from_storage(self) -> None:
|
|
179
|
+
return self._recover_and_refresh()
|
|
180
|
+
|
|
181
|
+
def initialize_from_url(self, url: str) -> None:
|
|
182
|
+
try:
|
|
183
|
+
if self._is_implicit_grant_flow(url):
|
|
184
|
+
session, redirect_type = self._get_session_from_url(url)
|
|
185
|
+
self._save_session(session)
|
|
186
|
+
self._notify_all_subscribers("SIGNED_IN", session)
|
|
187
|
+
if redirect_type == "recovery":
|
|
188
|
+
self._notify_all_subscribers("PASSWORD_RECOVERY", session)
|
|
189
|
+
except Exception as e:
|
|
190
|
+
self._remove_session()
|
|
191
|
+
raise e
|
|
192
|
+
|
|
193
|
+
# Public methods
|
|
194
|
+
|
|
195
|
+
def sign_in_anonymously(
|
|
196
|
+
self, credentials: SignInAnonymouslyCredentials | None = None
|
|
197
|
+
) -> AuthResponse:
|
|
198
|
+
"""
|
|
199
|
+
Creates a new anonymous user.
|
|
200
|
+
"""
|
|
201
|
+
if credentials is None:
|
|
202
|
+
credentials = {"options": {}}
|
|
203
|
+
options = credentials.get("options", {})
|
|
204
|
+
data = options.get("data") or {}
|
|
205
|
+
captcha_token = options.get("captcha_token")
|
|
206
|
+
response = self._request(
|
|
207
|
+
"POST",
|
|
208
|
+
"signup",
|
|
209
|
+
body={
|
|
210
|
+
"data": data,
|
|
211
|
+
"gotrue_meta_security": {
|
|
212
|
+
"captcha_token": captcha_token,
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
)
|
|
216
|
+
auth_response = parse_auth_response(response)
|
|
217
|
+
if auth_response.session:
|
|
218
|
+
self._save_session(auth_response.session)
|
|
219
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
220
|
+
return auth_response
|
|
221
|
+
|
|
222
|
+
def sign_up(
|
|
223
|
+
self,
|
|
224
|
+
credentials: SignUpWithPasswordCredentials,
|
|
225
|
+
) -> AuthResponse:
|
|
226
|
+
"""
|
|
227
|
+
Creates a new user.
|
|
228
|
+
"""
|
|
229
|
+
email = credentials.get("email")
|
|
230
|
+
phone = credentials.get("phone")
|
|
231
|
+
password = credentials.get("password")
|
|
232
|
+
# TODO(@o-santi): this is horrible, but it is the easiest way to satisfy mypy
|
|
233
|
+
# it should have been a builder pattern instead, and with proper classes
|
|
234
|
+
if email and password:
|
|
235
|
+
email_options = cast(
|
|
236
|
+
SignUpWithEmailAndPasswordCredentialsOptions,
|
|
237
|
+
credentials.get("options", {}),
|
|
238
|
+
)
|
|
239
|
+
data = email_options.get("data") or {}
|
|
240
|
+
channel = email_options.get("channel", "sms")
|
|
241
|
+
captcha_token = email_options.get("captcha_token")
|
|
242
|
+
redirect_to = email_options.get("email_redirect_to")
|
|
243
|
+
response = self._request(
|
|
244
|
+
"POST",
|
|
245
|
+
"signup",
|
|
246
|
+
body=self._with_pkce_challenge(
|
|
247
|
+
{
|
|
248
|
+
"email": email,
|
|
249
|
+
"password": password,
|
|
250
|
+
"data": data,
|
|
251
|
+
"gotrue_meta_security": {
|
|
252
|
+
"captcha_token": captcha_token,
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
),
|
|
256
|
+
redirect_to=redirect_to,
|
|
257
|
+
)
|
|
258
|
+
elif phone and password:
|
|
259
|
+
phone_options = cast(
|
|
260
|
+
SignUpWithPhoneAndPasswordCredentialsOptions,
|
|
261
|
+
credentials.get("options", {}),
|
|
262
|
+
)
|
|
263
|
+
data = phone_options.get("data") or {}
|
|
264
|
+
channel = phone_options.get("channel", "sms")
|
|
265
|
+
captcha_token = phone_options.get("captcha_token")
|
|
266
|
+
response = self._request(
|
|
267
|
+
"POST",
|
|
268
|
+
"signup",
|
|
269
|
+
body={
|
|
270
|
+
"phone": phone,
|
|
271
|
+
"password": password,
|
|
272
|
+
"data": data,
|
|
273
|
+
"channel": channel,
|
|
274
|
+
"gotrue_meta_security": {
|
|
275
|
+
"captcha_token": captcha_token,
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
)
|
|
279
|
+
else:
|
|
280
|
+
raise AuthInvalidCredentialsError(
|
|
281
|
+
"You must provide either an email or phone number and a password"
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
auth_response = parse_auth_response(response)
|
|
285
|
+
if auth_response.session:
|
|
286
|
+
self._save_session(auth_response.session)
|
|
287
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
288
|
+
return auth_response
|
|
289
|
+
|
|
290
|
+
def sign_in_with_password(
|
|
291
|
+
self,
|
|
292
|
+
credentials: SignInWithPasswordCredentials,
|
|
293
|
+
) -> AuthResponse:
|
|
294
|
+
"""
|
|
295
|
+
Log in an existing user with an email or phone and password.
|
|
296
|
+
"""
|
|
297
|
+
email = credentials.get("email")
|
|
298
|
+
phone = credentials.get("phone")
|
|
299
|
+
password = credentials.get("password")
|
|
300
|
+
options = credentials.get("options", {})
|
|
301
|
+
data = options.get("data") or {}
|
|
302
|
+
captcha_token = options.get("captcha_token")
|
|
303
|
+
if email and password:
|
|
304
|
+
response = self._request(
|
|
305
|
+
"POST",
|
|
306
|
+
"token",
|
|
307
|
+
body={
|
|
308
|
+
"email": email,
|
|
309
|
+
"password": password,
|
|
310
|
+
"data": data,
|
|
311
|
+
"gotrue_meta_security": {
|
|
312
|
+
"captcha_token": captcha_token,
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
query=QueryParams(grant_type="password"),
|
|
316
|
+
)
|
|
317
|
+
elif phone and password:
|
|
318
|
+
response = self._request(
|
|
319
|
+
"POST",
|
|
320
|
+
"token",
|
|
321
|
+
body={
|
|
322
|
+
"phone": phone,
|
|
323
|
+
"password": password,
|
|
324
|
+
"data": data,
|
|
325
|
+
"gotrue_meta_security": {
|
|
326
|
+
"captcha_token": captcha_token,
|
|
327
|
+
},
|
|
328
|
+
},
|
|
329
|
+
query=QueryParams(grant_type="password"),
|
|
330
|
+
)
|
|
331
|
+
else:
|
|
332
|
+
raise AuthInvalidCredentialsError(
|
|
333
|
+
"You must provide either an email or phone number and a password"
|
|
334
|
+
)
|
|
335
|
+
auth_response = parse_auth_response(response)
|
|
336
|
+
if auth_response.session:
|
|
337
|
+
self._save_session(auth_response.session)
|
|
338
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
339
|
+
return auth_response
|
|
340
|
+
|
|
341
|
+
def sign_in_with_id_token(
|
|
342
|
+
self,
|
|
343
|
+
credentials: SignInWithIdTokenCredentials,
|
|
344
|
+
) -> AuthResponse:
|
|
345
|
+
"""
|
|
346
|
+
Allows signing in with an OIDC ID token. The authentication provider used should be enabled and configured.
|
|
347
|
+
"""
|
|
348
|
+
provider = credentials["provider"]
|
|
349
|
+
token = credentials["token"]
|
|
350
|
+
access_token = credentials.get("access_token")
|
|
351
|
+
nonce = credentials.get("nonce")
|
|
352
|
+
options = credentials.get("options", {})
|
|
353
|
+
captcha_token = options.get("captcha_token")
|
|
354
|
+
|
|
355
|
+
response = self._request(
|
|
356
|
+
"POST",
|
|
357
|
+
"token",
|
|
358
|
+
body={
|
|
359
|
+
"provider": provider,
|
|
360
|
+
"id_token": token,
|
|
361
|
+
"access_token": access_token,
|
|
362
|
+
"nonce": nonce,
|
|
363
|
+
"gotrue_meta_security": {
|
|
364
|
+
"captcha_token": captcha_token,
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
query=QueryParams(grant_type="id_token"),
|
|
368
|
+
)
|
|
369
|
+
auth_response = parse_auth_response(response)
|
|
370
|
+
if auth_response.session:
|
|
371
|
+
self._save_session(auth_response.session)
|
|
372
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
373
|
+
return auth_response
|
|
374
|
+
|
|
375
|
+
def sign_in_with_sso(self, credentials: SignInWithSSOCredentials) -> SSOResponse:
|
|
376
|
+
"""
|
|
377
|
+
Attempts a single-sign on using an enterprise Identity Provider. A
|
|
378
|
+
successful SSO attempt will redirect the current page to the identity
|
|
379
|
+
provider authorization page. The redirect URL is implementation and SSO
|
|
380
|
+
protocol specific.
|
|
381
|
+
|
|
382
|
+
You can use it by providing a SSO domain. Typically you can extract this
|
|
383
|
+
domain by asking users for their email address. If this domain is
|
|
384
|
+
registered on the Auth instance the redirect will use that organization's
|
|
385
|
+
currently active SSO Identity Provider for the login.
|
|
386
|
+
If you have built an organization-specific login page, you can use the
|
|
387
|
+
organization's SSO Identity Provider UUID directly instead.
|
|
388
|
+
"""
|
|
389
|
+
provider_id = credentials.get("provider_id")
|
|
390
|
+
domain = credentials.get("domain")
|
|
391
|
+
options = credentials.get("options", {})
|
|
392
|
+
redirect_to = options.get("redirect_to")
|
|
393
|
+
captcha_token = options.get("captcha_token")
|
|
394
|
+
# HTTPX currently does not follow redirects: https://www.python-httpx.org/compatibility/
|
|
395
|
+
# Additionally, unlike the JS client, Python is a server side language and it's not possible
|
|
396
|
+
# to automatically redirect in browser for the user
|
|
397
|
+
skip_http_redirect = options.get("skip_http_redirect", True)
|
|
398
|
+
|
|
399
|
+
if domain:
|
|
400
|
+
response = self._request(
|
|
401
|
+
"POST",
|
|
402
|
+
"sso",
|
|
403
|
+
body=self._with_pkce_challenge(
|
|
404
|
+
{
|
|
405
|
+
"domain": domain,
|
|
406
|
+
"skip_http_redirect": skip_http_redirect,
|
|
407
|
+
"gotrue_meta_security": {
|
|
408
|
+
"captcha_token": captcha_token,
|
|
409
|
+
},
|
|
410
|
+
"redirect_to": redirect_to,
|
|
411
|
+
}
|
|
412
|
+
),
|
|
413
|
+
)
|
|
414
|
+
return parse_sso_response(response)
|
|
415
|
+
if provider_id:
|
|
416
|
+
response = self._request(
|
|
417
|
+
"POST",
|
|
418
|
+
"sso",
|
|
419
|
+
body=self._with_pkce_challenge(
|
|
420
|
+
{
|
|
421
|
+
"provider_id": provider_id,
|
|
422
|
+
"skip_http_redirect": skip_http_redirect,
|
|
423
|
+
"gotrue_meta_security": {
|
|
424
|
+
"captcha_token": captcha_token,
|
|
425
|
+
},
|
|
426
|
+
"redirect_to": redirect_to,
|
|
427
|
+
}
|
|
428
|
+
),
|
|
429
|
+
)
|
|
430
|
+
return parse_sso_response(response)
|
|
431
|
+
raise AuthInvalidCredentialsError(
|
|
432
|
+
"You must provide either a domain or provider_id"
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
def sign_in_with_oauth(
|
|
436
|
+
self,
|
|
437
|
+
credentials: SignInWithOAuthCredentials,
|
|
438
|
+
) -> OAuthResponse:
|
|
439
|
+
"""
|
|
440
|
+
Log in an existing user via a third-party provider.
|
|
441
|
+
"""
|
|
442
|
+
provider = credentials["provider"]
|
|
443
|
+
options = credentials.get("options", {})
|
|
444
|
+
redirect_to = options.get("redirect_to")
|
|
445
|
+
scopes = options.get("scopes")
|
|
446
|
+
params = {**options.get("query_params", {})}
|
|
447
|
+
if redirect_to:
|
|
448
|
+
params["redirect_to"] = redirect_to
|
|
449
|
+
if scopes:
|
|
450
|
+
params["scopes"] = scopes
|
|
451
|
+
url_with_qs, _ = self._get_url_for_provider(
|
|
452
|
+
f"{self._url}/authorize", provider, params
|
|
453
|
+
)
|
|
454
|
+
return OAuthResponse(provider=provider, url=url_with_qs)
|
|
455
|
+
|
|
456
|
+
def link_identity(self, credentials: SignInWithOAuthCredentials) -> OAuthResponse:
|
|
457
|
+
provider = credentials["provider"]
|
|
458
|
+
options = credentials.get("options", {})
|
|
459
|
+
redirect_to = options.get("redirect_to")
|
|
460
|
+
scopes = options.get("scopes")
|
|
461
|
+
params = {**options.get("query_params", {})}
|
|
462
|
+
if redirect_to:
|
|
463
|
+
params["redirect_to"] = redirect_to
|
|
464
|
+
if scopes:
|
|
465
|
+
params["scopes"] = scopes
|
|
466
|
+
params["skip_http_redirect"] = "true"
|
|
467
|
+
url = "user/identities/authorize"
|
|
468
|
+
_, query = self._get_url_for_provider(url, provider, params)
|
|
469
|
+
|
|
470
|
+
session = self.get_session()
|
|
471
|
+
if not session:
|
|
472
|
+
raise AuthSessionMissingError()
|
|
473
|
+
|
|
474
|
+
response = self._request(
|
|
475
|
+
method="GET",
|
|
476
|
+
path=url,
|
|
477
|
+
query=query,
|
|
478
|
+
jwt=session.access_token,
|
|
479
|
+
)
|
|
480
|
+
link_identity = parse_link_identity_response(response)
|
|
481
|
+
return OAuthResponse(provider=provider, url=link_identity.url)
|
|
482
|
+
|
|
483
|
+
def get_user_identities(self) -> IdentitiesResponse:
|
|
484
|
+
response = self.get_user()
|
|
485
|
+
if response:
|
|
486
|
+
return IdentitiesResponse(identities=response.user.identities or [])
|
|
487
|
+
raise AuthSessionMissingError()
|
|
488
|
+
|
|
489
|
+
def unlink_identity(self, identity: UserIdentity) -> Response:
|
|
490
|
+
session = self.get_session()
|
|
491
|
+
if not session:
|
|
492
|
+
raise AuthSessionMissingError()
|
|
493
|
+
|
|
494
|
+
return self._request(
|
|
495
|
+
"DELETE",
|
|
496
|
+
f"user/identities/{identity.identity_id}",
|
|
497
|
+
jwt=session.access_token,
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
def sign_in_with_otp(
|
|
501
|
+
self,
|
|
502
|
+
credentials: SignInWithPasswordlessCredentials,
|
|
503
|
+
) -> AuthOtpResponse:
|
|
504
|
+
"""
|
|
505
|
+
Log in a user using magiclink or a one-time password (OTP).
|
|
506
|
+
|
|
507
|
+
If the `{{ .ConfirmationURL }}` variable is specified in
|
|
508
|
+
the email template, a magiclink will be sent.
|
|
509
|
+
|
|
510
|
+
If the `{{ .Token }}` variable is specified in the email
|
|
511
|
+
template, an OTP will be sent.
|
|
512
|
+
|
|
513
|
+
If you're using phone sign-ins, only an OTP will be sent.
|
|
514
|
+
You won't be able to send a magiclink for phone sign-ins.
|
|
515
|
+
"""
|
|
516
|
+
email = credentials.get("email")
|
|
517
|
+
phone = credentials.get("phone")
|
|
518
|
+
# TODO(@o-santi): this is horrible, but it is the easiest way to satisfy mypy
|
|
519
|
+
# it should have been a builder pattern instead, and with proper classes
|
|
520
|
+
if email:
|
|
521
|
+
email_options = cast(
|
|
522
|
+
SignInWithEmailAndPasswordlessCredentialsOptions,
|
|
523
|
+
credentials.get("options", {}),
|
|
524
|
+
)
|
|
525
|
+
email_redirect_to = email_options.get("email_redirect_to")
|
|
526
|
+
should_create_user = email_options.get("should_create_user", True)
|
|
527
|
+
data = email_options.get("data")
|
|
528
|
+
channel = email_options.get("channel", "sms")
|
|
529
|
+
captcha_token = email_options.get("captcha_token")
|
|
530
|
+
response = self._request(
|
|
531
|
+
"POST",
|
|
532
|
+
"otp",
|
|
533
|
+
body=self._with_pkce_challenge(
|
|
534
|
+
{
|
|
535
|
+
"email": email,
|
|
536
|
+
"data": data,
|
|
537
|
+
"create_user": should_create_user,
|
|
538
|
+
"gotrue_meta_security": {
|
|
539
|
+
"captcha_token": captcha_token,
|
|
540
|
+
},
|
|
541
|
+
}
|
|
542
|
+
),
|
|
543
|
+
redirect_to=email_redirect_to,
|
|
544
|
+
)
|
|
545
|
+
return parse_auth_otp_response(response)
|
|
546
|
+
if phone:
|
|
547
|
+
phone_options = cast(
|
|
548
|
+
SignInWithPhoneAndPasswordlessCredentialsOptions,
|
|
549
|
+
credentials.get("options", {}),
|
|
550
|
+
)
|
|
551
|
+
should_create_user = phone_options.get("should_create_user", True)
|
|
552
|
+
data = phone_options.get("data")
|
|
553
|
+
channel = phone_options.get("channel", "sms")
|
|
554
|
+
captcha_token = phone_options.get("captcha_token")
|
|
555
|
+
response = self._request(
|
|
556
|
+
"POST",
|
|
557
|
+
"otp",
|
|
558
|
+
body={
|
|
559
|
+
"phone": phone,
|
|
560
|
+
"data": data,
|
|
561
|
+
"create_user": should_create_user,
|
|
562
|
+
"channel": channel,
|
|
563
|
+
"gotrue_meta_security": {
|
|
564
|
+
"captcha_token": captcha_token,
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
)
|
|
568
|
+
return parse_auth_otp_response(response)
|
|
569
|
+
raise AuthInvalidCredentialsError(
|
|
570
|
+
"You must provide either an email or phone number"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
def resend(
|
|
574
|
+
self,
|
|
575
|
+
credentials: ResendCredentials,
|
|
576
|
+
) -> AuthOtpResponse:
|
|
577
|
+
"""
|
|
578
|
+
Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
|
|
579
|
+
"""
|
|
580
|
+
email = credentials.get("email")
|
|
581
|
+
phone = credentials.get("phone")
|
|
582
|
+
type = credentials.get("type")
|
|
583
|
+
options = credentials.get("options", {})
|
|
584
|
+
email_redirect_to: str | None = options.get("email_redirect_to") # type: ignore[assignment]
|
|
585
|
+
captcha_token = options.get("captcha_token")
|
|
586
|
+
body: dict[str, object] = { # improve later
|
|
587
|
+
"type": type,
|
|
588
|
+
"gotrue_meta_security": {
|
|
589
|
+
"captcha_token": captcha_token,
|
|
590
|
+
},
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if email is None and phone is None:
|
|
594
|
+
raise AuthInvalidCredentialsError(
|
|
595
|
+
"You must provide either an email or phone number"
|
|
596
|
+
)
|
|
597
|
+
|
|
598
|
+
body.update({"email": email} if email else {"phone": phone})
|
|
599
|
+
|
|
600
|
+
response = self._request(
|
|
601
|
+
"POST",
|
|
602
|
+
"resend",
|
|
603
|
+
body=body,
|
|
604
|
+
redirect_to=email_redirect_to if email else None,
|
|
605
|
+
)
|
|
606
|
+
return parse_auth_otp_response(response)
|
|
607
|
+
|
|
608
|
+
def verify_otp(self, params: VerifyOtpParams) -> AuthResponse:
|
|
609
|
+
"""
|
|
610
|
+
Log in a user given a User supplied OTP received via mobile.
|
|
611
|
+
"""
|
|
612
|
+
response = self._request(
|
|
613
|
+
"POST",
|
|
614
|
+
"verify",
|
|
615
|
+
body={
|
|
616
|
+
"gotrue_meta_security": {
|
|
617
|
+
"captcha_token": params.get("options", {}).get("captcha_token"),
|
|
618
|
+
},
|
|
619
|
+
**params,
|
|
620
|
+
},
|
|
621
|
+
redirect_to=params.get("options", {}).get("redirect_to"),
|
|
622
|
+
)
|
|
623
|
+
if params["type"] == "email_change":
|
|
624
|
+
try:
|
|
625
|
+
data = response.json()
|
|
626
|
+
except ValueError:
|
|
627
|
+
data = None
|
|
628
|
+
if isinstance(data, dict) and data.get("code") == "200":
|
|
629
|
+
return AuthResponse()
|
|
630
|
+
auth_response = parse_auth_response(response)
|
|
631
|
+
if auth_response.session:
|
|
632
|
+
self._save_session(auth_response.session)
|
|
633
|
+
event: AuthChangeEvent = (
|
|
634
|
+
"PASSWORD_RECOVERY" if params.get("type") == "recovery" else "SIGNED_IN"
|
|
635
|
+
)
|
|
636
|
+
self._notify_all_subscribers(event, auth_response.session)
|
|
637
|
+
return auth_response
|
|
638
|
+
|
|
639
|
+
def reauthenticate(self) -> AuthResponse:
|
|
640
|
+
session = self.get_session()
|
|
641
|
+
if not session:
|
|
642
|
+
raise AuthSessionMissingError()
|
|
643
|
+
|
|
644
|
+
self._request(
|
|
645
|
+
"GET",
|
|
646
|
+
"reauthenticate",
|
|
647
|
+
jwt=session.access_token,
|
|
648
|
+
)
|
|
649
|
+
return AuthResponse(user=None, session=None)
|
|
650
|
+
|
|
651
|
+
def get_session(self) -> Session | None:
|
|
652
|
+
"""
|
|
653
|
+
Returns the session, refreshing it if necessary.
|
|
654
|
+
|
|
655
|
+
The session returned can be null if the session is not detected which
|
|
656
|
+
can happen in the event a user is not signed-in or has logged out.
|
|
657
|
+
"""
|
|
658
|
+
current_session = self._load_session()
|
|
659
|
+
if not current_session:
|
|
660
|
+
return None
|
|
661
|
+
time_now = round(time.time())
|
|
662
|
+
has_expired = (
|
|
663
|
+
current_session.expires_at <= time_now + EXPIRY_MARGIN
|
|
664
|
+
if current_session.expires_at
|
|
665
|
+
else False
|
|
666
|
+
)
|
|
667
|
+
return (
|
|
668
|
+
self._call_refresh_token(current_session.refresh_token)
|
|
669
|
+
if has_expired
|
|
670
|
+
else current_session
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
def get_user(self, jwt: str | None = None) -> UserResponse | None:
|
|
674
|
+
"""
|
|
675
|
+
Gets the current user details if there is an existing session.
|
|
676
|
+
|
|
677
|
+
Takes in an optional access token `jwt`. If no `jwt` is provided,
|
|
678
|
+
`get_user()` will attempt to get the `jwt` from the current session.
|
|
679
|
+
|
|
680
|
+
Returns `None` if no `jwt` is provided and there is no active
|
|
681
|
+
session to retrieve one from.
|
|
682
|
+
"""
|
|
683
|
+
if not jwt:
|
|
684
|
+
session = self.get_session()
|
|
685
|
+
if session:
|
|
686
|
+
jwt = session.access_token
|
|
687
|
+
else:
|
|
688
|
+
return None
|
|
689
|
+
return parse_user_response(self._request("GET", "user", jwt=jwt))
|
|
690
|
+
|
|
691
|
+
def update_user(
|
|
692
|
+
self, attributes: UserAttributes, options: UpdateUserOptions | None = None
|
|
693
|
+
) -> UserResponse:
|
|
694
|
+
"""
|
|
695
|
+
Updates user data, if there is a logged in user.
|
|
696
|
+
"""
|
|
697
|
+
session = self.get_session()
|
|
698
|
+
if not session:
|
|
699
|
+
raise AuthSessionMissingError()
|
|
700
|
+
update_options = options or {}
|
|
701
|
+
body = dict(attributes)
|
|
702
|
+
if attributes.get("email") is not None:
|
|
703
|
+
self._with_pkce_challenge(body)
|
|
704
|
+
response = self._request(
|
|
705
|
+
"PUT",
|
|
706
|
+
"user",
|
|
707
|
+
body=body,
|
|
708
|
+
redirect_to=update_options.get("email_redirect_to"),
|
|
709
|
+
jwt=session.access_token,
|
|
710
|
+
)
|
|
711
|
+
user_response = parse_user_response(response)
|
|
712
|
+
session.user = user_response.user
|
|
713
|
+
self._save_session(session)
|
|
714
|
+
self._notify_all_subscribers("USER_UPDATED", session)
|
|
715
|
+
return user_response
|
|
716
|
+
|
|
717
|
+
def set_session(self, access_token: str, refresh_token: str) -> AuthResponse:
|
|
718
|
+
"""
|
|
719
|
+
Sets the session data from the current session. If the current session
|
|
720
|
+
is expired, `set_session` will take care of refreshing it to obtain a
|
|
721
|
+
new session.
|
|
722
|
+
|
|
723
|
+
If the refresh token in the current session is invalid and the current
|
|
724
|
+
session has expired, an error will be thrown.
|
|
725
|
+
|
|
726
|
+
If the current session does not contain at `expires_at` field,
|
|
727
|
+
`set_session` will use the exp claim defined in the access token.
|
|
728
|
+
|
|
729
|
+
The current session that minimally contains an access token,
|
|
730
|
+
refresh token and a user.
|
|
731
|
+
"""
|
|
732
|
+
time_now = round(time.time())
|
|
733
|
+
expires_at = time_now
|
|
734
|
+
has_expired = True
|
|
735
|
+
session: Session | None = None
|
|
736
|
+
if access_token:
|
|
737
|
+
payload = decode_jwt(access_token)["payload"]
|
|
738
|
+
exp = payload.get("exp")
|
|
739
|
+
if exp:
|
|
740
|
+
expires_at = int(exp)
|
|
741
|
+
has_expired = expires_at <= time_now
|
|
742
|
+
if has_expired:
|
|
743
|
+
if not refresh_token:
|
|
744
|
+
raise AuthSessionMissingError()
|
|
745
|
+
response = self._refresh_access_token(refresh_token)
|
|
746
|
+
if not response.session:
|
|
747
|
+
return AuthResponse()
|
|
748
|
+
session = response.session
|
|
749
|
+
else:
|
|
750
|
+
user_response = self.get_user(access_token)
|
|
751
|
+
if user_response is None:
|
|
752
|
+
raise UserDoesntExist()
|
|
753
|
+
session = Session(
|
|
754
|
+
access_token=access_token,
|
|
755
|
+
refresh_token=refresh_token,
|
|
756
|
+
user=user_response.user,
|
|
757
|
+
token_type="bearer",
|
|
758
|
+
expires_in=expires_at - time_now,
|
|
759
|
+
expires_at=expires_at,
|
|
760
|
+
)
|
|
761
|
+
self._save_session(session)
|
|
762
|
+
# A still-valid token is a sign-in. TOKEN_REFRESHED is only for a refresh.
|
|
763
|
+
event: AuthChangeEvent = "TOKEN_REFRESHED" if has_expired else "SIGNED_IN"
|
|
764
|
+
self._notify_all_subscribers(event, session)
|
|
765
|
+
return AuthResponse(session=session, user=session.user)
|
|
766
|
+
|
|
767
|
+
def refresh_session(self, refresh_token: str | None = None) -> AuthResponse:
|
|
768
|
+
"""
|
|
769
|
+
Returns a new session, regardless of expiry status.
|
|
770
|
+
|
|
771
|
+
Takes in an optional current session. If not passed in, then refreshSession()
|
|
772
|
+
will attempt to retrieve it from getSession(). If the current session's
|
|
773
|
+
refresh token is invalid, an error will be thrown.
|
|
774
|
+
"""
|
|
775
|
+
if not refresh_token:
|
|
776
|
+
session = self.get_session()
|
|
777
|
+
if session:
|
|
778
|
+
refresh_token = session.refresh_token
|
|
779
|
+
if not refresh_token:
|
|
780
|
+
raise AuthSessionMissingError()
|
|
781
|
+
session = self._call_refresh_token(refresh_token)
|
|
782
|
+
return AuthResponse(session=session, user=session.user)
|
|
783
|
+
|
|
784
|
+
def sign_out(self, options: SignOutOptions | None = None) -> None:
|
|
785
|
+
"""
|
|
786
|
+
`sign_out` will remove the logged in user from the
|
|
787
|
+
current session and log them out - removing all items from storage and then trigger a `"SIGNED_OUT"` event.
|
|
788
|
+
|
|
789
|
+
For advanced use cases, you can revoke all refresh tokens for a user by passing a user's JWT through to `admin.sign_out`.
|
|
790
|
+
|
|
791
|
+
There is no way to revoke a user's access token jwt until it expires.
|
|
792
|
+
It is recommended to set a shorter expiry on the jwt for this reason.
|
|
793
|
+
|
|
794
|
+
`sign_out` behavior depends on the scope:
|
|
795
|
+
|
|
796
|
+
- `global` (the default): the session is removed and `"SIGNED_OUT"` is
|
|
797
|
+
emitted only after the server revokes all of the user's sessions. If
|
|
798
|
+
the request fails, the error is raised and the session is kept, so the
|
|
799
|
+
call can be retried or replaced with a `local` sign out.
|
|
800
|
+
- `local`: the session is removed and `"SIGNED_OUT"` is emitted first,
|
|
801
|
+
then the request to revoke it on the server is sent. If the request
|
|
802
|
+
fails, the error is raised.
|
|
803
|
+
- `others`: the session is never removed. If the request fails, the
|
|
804
|
+
error is raised.
|
|
805
|
+
|
|
806
|
+
A 401, 403 or 404 response counts as already signed out.
|
|
807
|
+
"""
|
|
808
|
+
scope = (options or {}).get("scope", "global")
|
|
809
|
+
try:
|
|
810
|
+
session = self.get_session()
|
|
811
|
+
except AuthSessionMissingError:
|
|
812
|
+
session = None
|
|
813
|
+
except AuthApiError:
|
|
814
|
+
# The refresh was rejected, so there is no session left to revoke.
|
|
815
|
+
# The other sessions could not be revoked either.
|
|
816
|
+
if scope == "others":
|
|
817
|
+
raise
|
|
818
|
+
session = None
|
|
819
|
+
except Exception:
|
|
820
|
+
# The access token expired and could not be refreshed, so there is
|
|
821
|
+
# nothing to revoke with. `local` still signs out this device.
|
|
822
|
+
if scope == "local":
|
|
823
|
+
self._remove_session()
|
|
824
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
825
|
+
raise
|
|
826
|
+
access_token = session.access_token if session else None
|
|
827
|
+
|
|
828
|
+
teardown_error: Exception | None = None
|
|
829
|
+
if scope == "local":
|
|
830
|
+
# A failing `"SIGNED_OUT"` subscriber must not skip the request, so
|
|
831
|
+
# its error is raised once the request has been sent.
|
|
832
|
+
try:
|
|
833
|
+
self._remove_session()
|
|
834
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
835
|
+
except Exception as e:
|
|
836
|
+
teardown_error = e
|
|
837
|
+
|
|
838
|
+
error: Exception | None = None
|
|
839
|
+
if access_token:
|
|
840
|
+
try:
|
|
841
|
+
self.admin.sign_out(access_token, scope)
|
|
842
|
+
except Exception as e:
|
|
843
|
+
if not _is_signed_out_error(e):
|
|
844
|
+
error = e
|
|
845
|
+
|
|
846
|
+
if teardown_error is not None:
|
|
847
|
+
raise teardown_error
|
|
848
|
+
if error is not None:
|
|
849
|
+
raise error
|
|
850
|
+
|
|
851
|
+
if scope == "global":
|
|
852
|
+
self._remove_session()
|
|
853
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
854
|
+
|
|
855
|
+
def on_auth_state_change(
|
|
856
|
+
self,
|
|
857
|
+
callback: Callable[[AuthChangeEvent, Session | None], None],
|
|
858
|
+
) -> Subscription:
|
|
859
|
+
"""
|
|
860
|
+
Receive a notification every time an auth event happens.
|
|
861
|
+
"""
|
|
862
|
+
unique_id = str(uuid4())
|
|
863
|
+
|
|
864
|
+
def _unsubscribe() -> None:
|
|
865
|
+
self._state_change_emitters.pop(unique_id)
|
|
866
|
+
|
|
867
|
+
subscription = Subscription(
|
|
868
|
+
id=unique_id,
|
|
869
|
+
callback=callback,
|
|
870
|
+
unsubscribe=_unsubscribe,
|
|
871
|
+
)
|
|
872
|
+
self._state_change_emitters[unique_id] = subscription
|
|
873
|
+
return subscription
|
|
874
|
+
|
|
875
|
+
def reset_password_for_email(
|
|
876
|
+
self, email: str, options: Options | None = None
|
|
877
|
+
) -> None:
|
|
878
|
+
"""
|
|
879
|
+
Sends a password reset request to an email address.
|
|
880
|
+
"""
|
|
881
|
+
reset_options = options or {}
|
|
882
|
+
self._request(
|
|
883
|
+
"POST",
|
|
884
|
+
"recover",
|
|
885
|
+
body=self._with_pkce_challenge(
|
|
886
|
+
{
|
|
887
|
+
"email": email,
|
|
888
|
+
"gotrue_meta_security": {
|
|
889
|
+
"captcha_token": reset_options.get("captcha_token"),
|
|
890
|
+
},
|
|
891
|
+
},
|
|
892
|
+
password_recovery=True,
|
|
893
|
+
),
|
|
894
|
+
redirect_to=reset_options.get("redirect_to"),
|
|
895
|
+
)
|
|
896
|
+
|
|
897
|
+
def reset_password_email(
|
|
898
|
+
self,
|
|
899
|
+
email: str,
|
|
900
|
+
options: Options | None = None,
|
|
901
|
+
) -> None:
|
|
902
|
+
"""
|
|
903
|
+
Sends a password reset request to an email address.
|
|
904
|
+
"""
|
|
905
|
+
|
|
906
|
+
self.reset_password_for_email(email, options or {})
|
|
907
|
+
|
|
908
|
+
# MFA methods
|
|
909
|
+
|
|
910
|
+
def _enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse:
|
|
911
|
+
session = self.get_session()
|
|
912
|
+
if not session:
|
|
913
|
+
raise AuthSessionMissingError()
|
|
914
|
+
|
|
915
|
+
body = {
|
|
916
|
+
"friendly_name": params.get("friendly_name"),
|
|
917
|
+
"factor_type": params.get("factor_type"),
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
if params["factor_type"] == "phone":
|
|
921
|
+
body["phone"] = params.get("phone")
|
|
922
|
+
else:
|
|
923
|
+
body["issuer"] = params.get("issuer")
|
|
924
|
+
|
|
925
|
+
response = self._request(
|
|
926
|
+
"POST",
|
|
927
|
+
"factors",
|
|
928
|
+
body=body,
|
|
929
|
+
jwt=session.access_token,
|
|
930
|
+
)
|
|
931
|
+
auth_response = AuthMFAEnrollResponse.model_validate_json(response.content)
|
|
932
|
+
if params["factor_type"] == "totp" and auth_response.totp:
|
|
933
|
+
auth_response.totp.qr_code = (
|
|
934
|
+
f"data:image/svg+xml;utf-8,{auth_response.totp.qr_code}"
|
|
935
|
+
)
|
|
936
|
+
return auth_response
|
|
937
|
+
|
|
938
|
+
def _challenge(self, params: MFAChallengeParams) -> AuthMFAChallengeResponse:
|
|
939
|
+
session = self.get_session()
|
|
940
|
+
if not session:
|
|
941
|
+
raise AuthSessionMissingError()
|
|
942
|
+
response = self._request(
|
|
943
|
+
"POST",
|
|
944
|
+
f"factors/{params.get('factor_id')}/challenge",
|
|
945
|
+
body={"channel": params.get("channel")},
|
|
946
|
+
jwt=session.access_token,
|
|
947
|
+
)
|
|
948
|
+
return AuthMFAChallengeResponse.model_validate_json(response.content)
|
|
949
|
+
|
|
950
|
+
def _challenge_and_verify(
|
|
951
|
+
self,
|
|
952
|
+
params: MFAChallengeAndVerifyParams,
|
|
953
|
+
) -> AuthMFAVerifyResponse:
|
|
954
|
+
response = self._challenge(
|
|
955
|
+
{
|
|
956
|
+
"factor_id": params["factor_id"],
|
|
957
|
+
}
|
|
958
|
+
)
|
|
959
|
+
return self._verify(
|
|
960
|
+
{
|
|
961
|
+
"factor_id": params["factor_id"],
|
|
962
|
+
"challenge_id": response.id,
|
|
963
|
+
"code": params["code"],
|
|
964
|
+
}
|
|
965
|
+
)
|
|
966
|
+
|
|
967
|
+
def _verify(self, params: MFAVerifyParams) -> AuthMFAVerifyResponse:
|
|
968
|
+
session = self.get_session()
|
|
969
|
+
if not session:
|
|
970
|
+
raise AuthSessionMissingError()
|
|
971
|
+
response = self._request(
|
|
972
|
+
"POST",
|
|
973
|
+
f"factors/{params.get('factor_id')}/verify",
|
|
974
|
+
body=params,
|
|
975
|
+
jwt=session.access_token,
|
|
976
|
+
)
|
|
977
|
+
auth_response = AuthMFAVerifyResponse.model_validate_json(response.content)
|
|
978
|
+
session = Session.model_validate_json(response.content)
|
|
979
|
+
self._save_session(session)
|
|
980
|
+
self._notify_all_subscribers("MFA_CHALLENGE_VERIFIED", session)
|
|
981
|
+
return auth_response
|
|
982
|
+
|
|
983
|
+
def _unenroll(self, params: MFAUnenrollParams) -> AuthMFAUnenrollResponse:
|
|
984
|
+
session = self.get_session()
|
|
985
|
+
if not session:
|
|
986
|
+
raise AuthSessionMissingError()
|
|
987
|
+
response = self._request(
|
|
988
|
+
"DELETE",
|
|
989
|
+
f"factors/{params.get('factor_id')}",
|
|
990
|
+
jwt=session.access_token,
|
|
991
|
+
)
|
|
992
|
+
return AuthMFAUnenrollResponse.model_validate_json(response.content)
|
|
993
|
+
|
|
994
|
+
def _list_factors(self) -> AuthMFAListFactorsResponse:
|
|
995
|
+
response = self.get_user()
|
|
996
|
+
factors = response.user.factors or [] if response else []
|
|
997
|
+
totp = [
|
|
998
|
+
f for f in factors if f.factor_type == "totp" and f.status == "verified"
|
|
999
|
+
]
|
|
1000
|
+
phone = [
|
|
1001
|
+
f for f in factors if f.factor_type == "phone" and f.status == "verified"
|
|
1002
|
+
]
|
|
1003
|
+
return AuthMFAListFactorsResponse(all=factors, totp=totp, phone=phone)
|
|
1004
|
+
|
|
1005
|
+
def _get_authenticator_assurance_level(
|
|
1006
|
+
self,
|
|
1007
|
+
) -> AuthMFAGetAuthenticatorAssuranceLevelResponse:
|
|
1008
|
+
session = self.get_session()
|
|
1009
|
+
if not session:
|
|
1010
|
+
return AuthMFAGetAuthenticatorAssuranceLevelResponse(
|
|
1011
|
+
current_level=None,
|
|
1012
|
+
next_level=None,
|
|
1013
|
+
current_authentication_methods=[],
|
|
1014
|
+
)
|
|
1015
|
+
payload = decode_jwt(session.access_token)["payload"]
|
|
1016
|
+
current_level = payload.get("aal")
|
|
1017
|
+
verified_factors = [
|
|
1018
|
+
f for f in session.user.factors or [] if f.status == "verified"
|
|
1019
|
+
]
|
|
1020
|
+
next_level = "aal2" if verified_factors else current_level
|
|
1021
|
+
amr_dict_list = payload.get("amr") or []
|
|
1022
|
+
current_authentication_methods = [
|
|
1023
|
+
AMREntry.model_validate(amr) for amr in amr_dict_list
|
|
1024
|
+
]
|
|
1025
|
+
return AuthMFAGetAuthenticatorAssuranceLevelResponse(
|
|
1026
|
+
current_level=current_level,
|
|
1027
|
+
next_level=next_level,
|
|
1028
|
+
current_authentication_methods=current_authentication_methods,
|
|
1029
|
+
)
|
|
1030
|
+
|
|
1031
|
+
# Private methods
|
|
1032
|
+
|
|
1033
|
+
def _load_session(self) -> Session | None:
|
|
1034
|
+
if not self._persist_session:
|
|
1035
|
+
return self._in_memory_session
|
|
1036
|
+
maybe_session = self._storage.get_item(self._storage_key)
|
|
1037
|
+
current_session = self._get_valid_session(maybe_session)
|
|
1038
|
+
if not current_session:
|
|
1039
|
+
self._remove_session()
|
|
1040
|
+
return current_session
|
|
1041
|
+
|
|
1042
|
+
def _remove_session(self) -> None:
|
|
1043
|
+
if self._persist_session:
|
|
1044
|
+
self._storage.remove_item(self._storage_key)
|
|
1045
|
+
else:
|
|
1046
|
+
self._in_memory_session = None
|
|
1047
|
+
if self._refresh_token_timer:
|
|
1048
|
+
self._refresh_token_timer.cancel()
|
|
1049
|
+
self._refresh_token_timer = None
|
|
1050
|
+
|
|
1051
|
+
def _get_session_from_url(
|
|
1052
|
+
self,
|
|
1053
|
+
url: str,
|
|
1054
|
+
) -> tuple[Session, str | None]:
|
|
1055
|
+
if not self._is_implicit_grant_flow(url):
|
|
1056
|
+
raise AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.")
|
|
1057
|
+
params = _parse_url_params(url)
|
|
1058
|
+
error_description = self._get_param(params, "error_description")
|
|
1059
|
+
if error_description:
|
|
1060
|
+
error_code = self._get_param(params, "error_code")
|
|
1061
|
+
error = self._get_param(params, "error")
|
|
1062
|
+
if not error_code:
|
|
1063
|
+
raise AuthImplicitGrantRedirectError("No error_code detected.")
|
|
1064
|
+
if not error:
|
|
1065
|
+
raise AuthImplicitGrantRedirectError("No error detected.")
|
|
1066
|
+
raise AuthImplicitGrantRedirectError(
|
|
1067
|
+
error_description,
|
|
1068
|
+
{"code": error_code, "error": error},
|
|
1069
|
+
)
|
|
1070
|
+
provider_token = self._get_param(params, "provider_token")
|
|
1071
|
+
provider_refresh_token = self._get_param(params, "provider_refresh_token")
|
|
1072
|
+
access_token = self._get_param(params, "access_token")
|
|
1073
|
+
if not access_token:
|
|
1074
|
+
raise AuthImplicitGrantRedirectError("No access_token detected.")
|
|
1075
|
+
expires_in = self._get_param(params, "expires_in")
|
|
1076
|
+
if not expires_in:
|
|
1077
|
+
raise AuthImplicitGrantRedirectError("No expires_in detected.")
|
|
1078
|
+
refresh_token = self._get_param(params, "refresh_token")
|
|
1079
|
+
if not refresh_token:
|
|
1080
|
+
raise AuthImplicitGrantRedirectError("No refresh_token detected.")
|
|
1081
|
+
token_type = self._get_param(params, "token_type")
|
|
1082
|
+
if not token_type:
|
|
1083
|
+
raise AuthImplicitGrantRedirectError("No token_type detected.")
|
|
1084
|
+
time_now = round(time.time())
|
|
1085
|
+
expires_at = time_now + int(expires_in)
|
|
1086
|
+
user = self.get_user(access_token)
|
|
1087
|
+
if user is None:
|
|
1088
|
+
raise UserDoesntExist()
|
|
1089
|
+
session = Session(
|
|
1090
|
+
provider_token=provider_token,
|
|
1091
|
+
provider_refresh_token=provider_refresh_token,
|
|
1092
|
+
access_token=access_token,
|
|
1093
|
+
expires_in=int(expires_in),
|
|
1094
|
+
expires_at=expires_at,
|
|
1095
|
+
refresh_token=refresh_token,
|
|
1096
|
+
token_type=token_type,
|
|
1097
|
+
user=user.user,
|
|
1098
|
+
)
|
|
1099
|
+
redirect_type = self._get_param(params, "type")
|
|
1100
|
+
return session, redirect_type
|
|
1101
|
+
|
|
1102
|
+
def _recover_and_refresh(self) -> None:
|
|
1103
|
+
raw_session = self._storage.get_item(self._storage_key)
|
|
1104
|
+
current_session = self._get_valid_session(raw_session)
|
|
1105
|
+
if not current_session:
|
|
1106
|
+
if raw_session:
|
|
1107
|
+
self._remove_session()
|
|
1108
|
+
return
|
|
1109
|
+
time_now = round(time.time())
|
|
1110
|
+
expires_at = current_session.expires_at
|
|
1111
|
+
if expires_at and expires_at < time_now + EXPIRY_MARGIN:
|
|
1112
|
+
refresh_token = current_session.refresh_token
|
|
1113
|
+
if not refresh_token:
|
|
1114
|
+
self._remove_session()
|
|
1115
|
+
return
|
|
1116
|
+
if not self._auto_refresh_token:
|
|
1117
|
+
return
|
|
1118
|
+
self._network_retries += 1
|
|
1119
|
+
try:
|
|
1120
|
+
self._call_refresh_token(refresh_token)
|
|
1121
|
+
self._network_retries = 0
|
|
1122
|
+
return
|
|
1123
|
+
except Exception as e:
|
|
1124
|
+
if (
|
|
1125
|
+
isinstance(e, AuthRetryableError)
|
|
1126
|
+
and self._network_retries < MAX_RETRIES
|
|
1127
|
+
):
|
|
1128
|
+
if self._refresh_token_timer:
|
|
1129
|
+
self._refresh_token_timer.cancel()
|
|
1130
|
+
self._refresh_token_timer = Timer(
|
|
1131
|
+
(200 * (2 ** (self._network_retries - 1))),
|
|
1132
|
+
self._recover_and_refresh,
|
|
1133
|
+
)
|
|
1134
|
+
self._refresh_token_timer.start()
|
|
1135
|
+
return
|
|
1136
|
+
self._remove_session()
|
|
1137
|
+
return
|
|
1138
|
+
if self._persist_session:
|
|
1139
|
+
self._save_session(current_session)
|
|
1140
|
+
self._notify_all_subscribers("SIGNED_IN", current_session)
|
|
1141
|
+
|
|
1142
|
+
def _call_refresh_token(self, refresh_token: str) -> Session:
|
|
1143
|
+
if not refresh_token:
|
|
1144
|
+
raise AuthSessionMissingError()
|
|
1145
|
+
response = self._refresh_access_token(refresh_token)
|
|
1146
|
+
if not response.session:
|
|
1147
|
+
raise AuthSessionMissingError()
|
|
1148
|
+
self._save_session(response.session)
|
|
1149
|
+
self._notify_all_subscribers("TOKEN_REFRESHED", response.session)
|
|
1150
|
+
return response.session
|
|
1151
|
+
|
|
1152
|
+
def _refresh_access_token(self, refresh_token: str) -> AuthResponse:
|
|
1153
|
+
response = self._request(
|
|
1154
|
+
"POST",
|
|
1155
|
+
"token",
|
|
1156
|
+
query=QueryParams(grant_type="refresh_token"),
|
|
1157
|
+
body={"refresh_token": refresh_token},
|
|
1158
|
+
)
|
|
1159
|
+
return parse_auth_response(response)
|
|
1160
|
+
|
|
1161
|
+
def _save_session(self, session: Session) -> None:
|
|
1162
|
+
if not self._persist_session:
|
|
1163
|
+
self._in_memory_session = session
|
|
1164
|
+
expire_at = session.expires_at
|
|
1165
|
+
if expire_at:
|
|
1166
|
+
time_now = round(time.time())
|
|
1167
|
+
expire_in = expire_at - time_now
|
|
1168
|
+
refresh_duration_before_expires = (
|
|
1169
|
+
EXPIRY_MARGIN if expire_in > EXPIRY_MARGIN else 0.5
|
|
1170
|
+
)
|
|
1171
|
+
value = (expire_in - refresh_duration_before_expires) * 1000
|
|
1172
|
+
self._start_auto_refresh_token(value)
|
|
1173
|
+
if self._persist_session and session.expires_at:
|
|
1174
|
+
self._storage.set_item(self._storage_key, session.model_dump_json())
|
|
1175
|
+
|
|
1176
|
+
def _start_auto_refresh_token(self, value: float) -> None:
|
|
1177
|
+
if self._refresh_token_timer:
|
|
1178
|
+
self._refresh_token_timer.cancel()
|
|
1179
|
+
self._refresh_token_timer = None
|
|
1180
|
+
if value <= 0 or not self._auto_refresh_token:
|
|
1181
|
+
return
|
|
1182
|
+
|
|
1183
|
+
def refresh_token_function() -> None:
|
|
1184
|
+
self._network_retries += 1
|
|
1185
|
+
try:
|
|
1186
|
+
# get_session() would refresh too: the timer fires inside EXPIRY_MARGIN.
|
|
1187
|
+
session = self._load_session()
|
|
1188
|
+
if session:
|
|
1189
|
+
self._call_refresh_token(session.refresh_token)
|
|
1190
|
+
self._network_retries = 0
|
|
1191
|
+
except Exception as e:
|
|
1192
|
+
if (
|
|
1193
|
+
isinstance(e, AuthRetryableError)
|
|
1194
|
+
and self._network_retries < MAX_RETRIES
|
|
1195
|
+
):
|
|
1196
|
+
self._start_auto_refresh_token(
|
|
1197
|
+
200 * (2 ** (self._network_retries - 1))
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
self._refresh_token_timer = Timer(value, refresh_token_function)
|
|
1201
|
+
self._refresh_token_timer.start()
|
|
1202
|
+
|
|
1203
|
+
def _notify_all_subscribers(
|
|
1204
|
+
self,
|
|
1205
|
+
event: AuthChangeEvent,
|
|
1206
|
+
session: Session | None,
|
|
1207
|
+
) -> None:
|
|
1208
|
+
for subscription in list(self._state_change_emitters.values()):
|
|
1209
|
+
subscription.callback(event, session)
|
|
1210
|
+
|
|
1211
|
+
def _get_valid_session(
|
|
1212
|
+
self,
|
|
1213
|
+
raw_session: str | None,
|
|
1214
|
+
) -> Session | None:
|
|
1215
|
+
if not raw_session:
|
|
1216
|
+
return None
|
|
1217
|
+
try:
|
|
1218
|
+
session = Session.model_validate_json(raw_session)
|
|
1219
|
+
if session.expires_at is None:
|
|
1220
|
+
return None
|
|
1221
|
+
return session
|
|
1222
|
+
except Exception:
|
|
1223
|
+
return None
|
|
1224
|
+
|
|
1225
|
+
def _get_param(
|
|
1226
|
+
self,
|
|
1227
|
+
query_params: dict[str, list[str]],
|
|
1228
|
+
name: str,
|
|
1229
|
+
) -> str | None:
|
|
1230
|
+
return query_params[name][0] if name in query_params else None
|
|
1231
|
+
|
|
1232
|
+
def _is_implicit_grant_flow(self, url: str) -> bool:
|
|
1233
|
+
params = _parse_url_params(url)
|
|
1234
|
+
return "access_token" in params or "error_description" in params
|
|
1235
|
+
|
|
1236
|
+
def _get_url_for_provider(
|
|
1237
|
+
self,
|
|
1238
|
+
url: str,
|
|
1239
|
+
provider: Provider,
|
|
1240
|
+
params: dict[str, str],
|
|
1241
|
+
) -> tuple[str, QueryParams]:
|
|
1242
|
+
query = QueryParams(params)
|
|
1243
|
+
prepared = self._prepare_pkce_challenge()
|
|
1244
|
+
if prepared:
|
|
1245
|
+
code_challenge, code_challenge_method = prepared
|
|
1246
|
+
query = query.set("code_challenge", code_challenge).set(
|
|
1247
|
+
"code_challenge_method", code_challenge_method
|
|
1248
|
+
)
|
|
1249
|
+
query = query.set("provider", provider)
|
|
1250
|
+
return f"{url}?{query}", query
|
|
1251
|
+
|
|
1252
|
+
def _prepare_pkce_challenge(
|
|
1253
|
+
self, *, password_recovery: bool = False
|
|
1254
|
+
) -> tuple[str, str] | None:
|
|
1255
|
+
if self._flow_type != "pkce":
|
|
1256
|
+
return None
|
|
1257
|
+
code_verifier = generate_pkce_verifier()
|
|
1258
|
+
stored_verifier = (
|
|
1259
|
+
f"{code_verifier}/PASSWORD_RECOVERY" if password_recovery else code_verifier
|
|
1260
|
+
)
|
|
1261
|
+
self._storage.set_item(f"{self._storage_key}-code-verifier", stored_verifier)
|
|
1262
|
+
code_challenge = generate_pkce_challenge(code_verifier)
|
|
1263
|
+
code_challenge_method = "plain" if code_verifier == code_challenge else "s256"
|
|
1264
|
+
return code_challenge, code_challenge_method
|
|
1265
|
+
|
|
1266
|
+
def _with_pkce_challenge(
|
|
1267
|
+
self, body: dict, *, password_recovery: bool = False
|
|
1268
|
+
) -> dict:
|
|
1269
|
+
prepared = self._prepare_pkce_challenge(password_recovery=password_recovery)
|
|
1270
|
+
if prepared:
|
|
1271
|
+
code_challenge, code_challenge_method = prepared
|
|
1272
|
+
body["code_challenge"] = code_challenge
|
|
1273
|
+
body["code_challenge_method"] = code_challenge_method
|
|
1274
|
+
return body
|
|
1275
|
+
|
|
1276
|
+
def exchange_code_for_session(self, params: CodeExchangeParams) -> AuthResponse:
|
|
1277
|
+
code_verifier = params.get("code_verifier") or None
|
|
1278
|
+
event: AuthChangeEvent = "SIGNED_IN"
|
|
1279
|
+
if not code_verifier:
|
|
1280
|
+
stored = self._storage.get_item(f"{self._storage_key}-code-verifier")
|
|
1281
|
+
if stored:
|
|
1282
|
+
code_verifier, _, redirect_type = stored.partition("/")
|
|
1283
|
+
if redirect_type == "PASSWORD_RECOVERY":
|
|
1284
|
+
event = "PASSWORD_RECOVERY"
|
|
1285
|
+
response = self._request(
|
|
1286
|
+
"POST",
|
|
1287
|
+
"token",
|
|
1288
|
+
query=QueryParams(grant_type="pkce"),
|
|
1289
|
+
body={
|
|
1290
|
+
"auth_code": params.get("auth_code"),
|
|
1291
|
+
"code_verifier": code_verifier,
|
|
1292
|
+
},
|
|
1293
|
+
redirect_to=params.get("redirect_to"),
|
|
1294
|
+
)
|
|
1295
|
+
auth_response = parse_auth_response(response)
|
|
1296
|
+
self._storage.remove_item(f"{self._storage_key}-code-verifier")
|
|
1297
|
+
if auth_response.session:
|
|
1298
|
+
self._save_session(auth_response.session)
|
|
1299
|
+
self._notify_all_subscribers(event, auth_response.session)
|
|
1300
|
+
return auth_response
|
|
1301
|
+
|
|
1302
|
+
def _fetch_jwks(self, kid: str, jwks: JWKSet) -> JWK:
|
|
1303
|
+
jwk: JWK | None = None
|
|
1304
|
+
|
|
1305
|
+
# try fetching from the suplied keys.
|
|
1306
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk.get("kid") == kid), None)
|
|
1307
|
+
|
|
1308
|
+
if jwk:
|
|
1309
|
+
return jwk
|
|
1310
|
+
|
|
1311
|
+
if self._jwks and (
|
|
1312
|
+
self._jwks_cached_at and time.time() - self._jwks_cached_at < self._jwks_ttl
|
|
1313
|
+
):
|
|
1314
|
+
# try fetching from the cache.
|
|
1315
|
+
jwk = next(
|
|
1316
|
+
(jwk for jwk in self._jwks["keys"] if jwk.get("kid") == kid),
|
|
1317
|
+
None,
|
|
1318
|
+
)
|
|
1319
|
+
if jwk:
|
|
1320
|
+
return jwk
|
|
1321
|
+
|
|
1322
|
+
# jwk isn't cached in memory so we need to fetch it from the well-known endpoint
|
|
1323
|
+
response = self._request("GET", ".well-known/jwks.json")
|
|
1324
|
+
jwks = parse_jwks(response)
|
|
1325
|
+
if response:
|
|
1326
|
+
self._jwks = jwks
|
|
1327
|
+
self._jwks_cached_at = time.time()
|
|
1328
|
+
|
|
1329
|
+
# find the signing key
|
|
1330
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk.get("kid") == kid), None)
|
|
1331
|
+
if not jwk:
|
|
1332
|
+
raise AuthInvalidJwtError("No matching signing key found in JWKS")
|
|
1333
|
+
|
|
1334
|
+
return jwk
|
|
1335
|
+
|
|
1336
|
+
raise AuthInvalidJwtError("JWT has no valid kid")
|
|
1337
|
+
|
|
1338
|
+
def get_claims(
|
|
1339
|
+
self, jwt: str | None = None, jwks: JWKSet | None = None
|
|
1340
|
+
) -> ClaimsResponse | None:
|
|
1341
|
+
token = jwt
|
|
1342
|
+
if not token:
|
|
1343
|
+
session = self.get_session()
|
|
1344
|
+
if not session:
|
|
1345
|
+
return None
|
|
1346
|
+
|
|
1347
|
+
token = session.access_token
|
|
1348
|
+
|
|
1349
|
+
decoded_jwt = decode_jwt(token)
|
|
1350
|
+
|
|
1351
|
+
payload, header, signature = (
|
|
1352
|
+
decoded_jwt["payload"],
|
|
1353
|
+
decoded_jwt["header"],
|
|
1354
|
+
decoded_jwt["signature"],
|
|
1355
|
+
)
|
|
1356
|
+
raw_header, raw_payload = (
|
|
1357
|
+
decoded_jwt["raw"]["header"],
|
|
1358
|
+
decoded_jwt["raw"]["payload"],
|
|
1359
|
+
)
|
|
1360
|
+
|
|
1361
|
+
validate_exp(payload.get("exp"))
|
|
1362
|
+
|
|
1363
|
+
# if symmetric algorithm, fallback to get_user
|
|
1364
|
+
if "kid" not in header or header["alg"] == "HS256":
|
|
1365
|
+
self.get_user(token)
|
|
1366
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1367
|
+
|
|
1368
|
+
algorithm = get_algorithm_by_name(header["alg"])
|
|
1369
|
+
jwk_set = self._fetch_jwks(header["kid"], jwks or {"keys": []})
|
|
1370
|
+
signing_key = algorithm.from_jwk(cast(dict[str, str], jwk_set))
|
|
1371
|
+
|
|
1372
|
+
# verify the signature
|
|
1373
|
+
is_valid = algorithm.verify(
|
|
1374
|
+
msg=f"{raw_header}.{raw_payload}".encode(), key=signing_key, sig=signature
|
|
1375
|
+
)
|
|
1376
|
+
|
|
1377
|
+
if not is_valid:
|
|
1378
|
+
raise AuthInvalidJwtError("Invalid JWT signature")
|
|
1379
|
+
|
|
1380
|
+
# If verification succeeds, decode and return claims
|
|
1381
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1382
|
+
|
|
1383
|
+
def __del__(self) -> None:
|
|
1384
|
+
"""Clean up resources when the client is destroyed."""
|
|
1385
|
+
if self._refresh_token_timer:
|
|
1386
|
+
try:
|
|
1387
|
+
# Try to cancel the timer
|
|
1388
|
+
self._refresh_token_timer.cancel()
|
|
1389
|
+
except Exception:
|
|
1390
|
+
# Ignore errors if event loop is closed or selector is not registered
|
|
1391
|
+
pass
|
|
1392
|
+
finally:
|
|
1393
|
+
# Always set to None to prevent further attempts
|
|
1394
|
+
self._refresh_token_timer = None
|