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,1404 @@
|
|
|
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 AsyncClient, 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 AsyncGoTrueAdminAPI
|
|
90
|
+
from .gotrue_base_api import AsyncGoTrueBaseAPI
|
|
91
|
+
from .gotrue_mfa_api import AsyncGoTrueMFAAPI
|
|
92
|
+
from .storage import AsyncMemoryStorage, AsyncSupportedStorage
|
|
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 AsyncGoTrueClient(AsyncGoTrueBaseAPI):
|
|
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: AsyncSupportedStorage | None = None,
|
|
113
|
+
http_client: AsyncClient | 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
|
+
AsyncGoTrueBaseAPI.__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 AsyncMemoryStorage()
|
|
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 = AsyncGoTrueAdminAPI(
|
|
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 = AsyncGoTrueMFAAPI()
|
|
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
|
+
async def initialize(self, *, url: str | None = None) -> None:
|
|
173
|
+
if url and self._is_implicit_grant_flow(url):
|
|
174
|
+
await self.initialize_from_url(url)
|
|
175
|
+
else:
|
|
176
|
+
await self.initialize_from_storage()
|
|
177
|
+
|
|
178
|
+
async def initialize_from_storage(self) -> None:
|
|
179
|
+
return await self._recover_and_refresh()
|
|
180
|
+
|
|
181
|
+
async def initialize_from_url(self, url: str) -> None:
|
|
182
|
+
try:
|
|
183
|
+
if self._is_implicit_grant_flow(url):
|
|
184
|
+
session, redirect_type = await self._get_session_from_url(url)
|
|
185
|
+
await 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
|
+
await self._remove_session()
|
|
191
|
+
raise e
|
|
192
|
+
|
|
193
|
+
# Public methods
|
|
194
|
+
|
|
195
|
+
async 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 = await 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
|
+
await self._save_session(auth_response.session)
|
|
219
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
220
|
+
return auth_response
|
|
221
|
+
|
|
222
|
+
async 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 = await self._request(
|
|
244
|
+
"POST",
|
|
245
|
+
"signup",
|
|
246
|
+
body=await 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 = await 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
|
+
await self._save_session(auth_response.session)
|
|
287
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
288
|
+
return auth_response
|
|
289
|
+
|
|
290
|
+
async 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 = await 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 = await 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
|
+
await self._save_session(auth_response.session)
|
|
338
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
339
|
+
return auth_response
|
|
340
|
+
|
|
341
|
+
async 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 = await 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
|
+
await self._save_session(auth_response.session)
|
|
372
|
+
self._notify_all_subscribers("SIGNED_IN", auth_response.session)
|
|
373
|
+
return auth_response
|
|
374
|
+
|
|
375
|
+
async def sign_in_with_sso(
|
|
376
|
+
self, credentials: SignInWithSSOCredentials
|
|
377
|
+
) -> SSOResponse:
|
|
378
|
+
"""
|
|
379
|
+
Attempts a single-sign on using an enterprise Identity Provider. A
|
|
380
|
+
successful SSO attempt will redirect the current page to the identity
|
|
381
|
+
provider authorization page. The redirect URL is implementation and SSO
|
|
382
|
+
protocol specific.
|
|
383
|
+
|
|
384
|
+
You can use it by providing a SSO domain. Typically you can extract this
|
|
385
|
+
domain by asking users for their email address. If this domain is
|
|
386
|
+
registered on the Auth instance the redirect will use that organization's
|
|
387
|
+
currently active SSO Identity Provider for the login.
|
|
388
|
+
If you have built an organization-specific login page, you can use the
|
|
389
|
+
organization's SSO Identity Provider UUID directly instead.
|
|
390
|
+
"""
|
|
391
|
+
provider_id = credentials.get("provider_id")
|
|
392
|
+
domain = credentials.get("domain")
|
|
393
|
+
options = credentials.get("options", {})
|
|
394
|
+
redirect_to = options.get("redirect_to")
|
|
395
|
+
captcha_token = options.get("captcha_token")
|
|
396
|
+
# HTTPX currently does not follow redirects: https://www.python-httpx.org/compatibility/
|
|
397
|
+
# Additionally, unlike the JS client, Python is a server side language and it's not possible
|
|
398
|
+
# to automatically redirect in browser for the user
|
|
399
|
+
skip_http_redirect = options.get("skip_http_redirect", True)
|
|
400
|
+
|
|
401
|
+
if domain:
|
|
402
|
+
response = await self._request(
|
|
403
|
+
"POST",
|
|
404
|
+
"sso",
|
|
405
|
+
body=await self._with_pkce_challenge(
|
|
406
|
+
{
|
|
407
|
+
"domain": domain,
|
|
408
|
+
"skip_http_redirect": skip_http_redirect,
|
|
409
|
+
"gotrue_meta_security": {
|
|
410
|
+
"captcha_token": captcha_token,
|
|
411
|
+
},
|
|
412
|
+
"redirect_to": redirect_to,
|
|
413
|
+
}
|
|
414
|
+
),
|
|
415
|
+
)
|
|
416
|
+
return parse_sso_response(response)
|
|
417
|
+
if provider_id:
|
|
418
|
+
response = await self._request(
|
|
419
|
+
"POST",
|
|
420
|
+
"sso",
|
|
421
|
+
body=await self._with_pkce_challenge(
|
|
422
|
+
{
|
|
423
|
+
"provider_id": provider_id,
|
|
424
|
+
"skip_http_redirect": skip_http_redirect,
|
|
425
|
+
"gotrue_meta_security": {
|
|
426
|
+
"captcha_token": captcha_token,
|
|
427
|
+
},
|
|
428
|
+
"redirect_to": redirect_to,
|
|
429
|
+
}
|
|
430
|
+
),
|
|
431
|
+
)
|
|
432
|
+
return parse_sso_response(response)
|
|
433
|
+
raise AuthInvalidCredentialsError(
|
|
434
|
+
"You must provide either a domain or provider_id"
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
async def sign_in_with_oauth(
|
|
438
|
+
self,
|
|
439
|
+
credentials: SignInWithOAuthCredentials,
|
|
440
|
+
) -> OAuthResponse:
|
|
441
|
+
"""
|
|
442
|
+
Log in an existing user via a third-party provider.
|
|
443
|
+
"""
|
|
444
|
+
provider = credentials["provider"]
|
|
445
|
+
options = credentials.get("options", {})
|
|
446
|
+
redirect_to = options.get("redirect_to")
|
|
447
|
+
scopes = options.get("scopes")
|
|
448
|
+
params = {**options.get("query_params", {})}
|
|
449
|
+
if redirect_to:
|
|
450
|
+
params["redirect_to"] = redirect_to
|
|
451
|
+
if scopes:
|
|
452
|
+
params["scopes"] = scopes
|
|
453
|
+
url_with_qs, _ = await self._get_url_for_provider(
|
|
454
|
+
f"{self._url}/authorize", provider, params
|
|
455
|
+
)
|
|
456
|
+
return OAuthResponse(provider=provider, url=url_with_qs)
|
|
457
|
+
|
|
458
|
+
async def link_identity(
|
|
459
|
+
self, credentials: SignInWithOAuthCredentials
|
|
460
|
+
) -> OAuthResponse:
|
|
461
|
+
provider = credentials["provider"]
|
|
462
|
+
options = credentials.get("options", {})
|
|
463
|
+
redirect_to = options.get("redirect_to")
|
|
464
|
+
scopes = options.get("scopes")
|
|
465
|
+
params = {**options.get("query_params", {})}
|
|
466
|
+
if redirect_to:
|
|
467
|
+
params["redirect_to"] = redirect_to
|
|
468
|
+
if scopes:
|
|
469
|
+
params["scopes"] = scopes
|
|
470
|
+
params["skip_http_redirect"] = "true"
|
|
471
|
+
url = "user/identities/authorize"
|
|
472
|
+
_, query = await self._get_url_for_provider(url, provider, params)
|
|
473
|
+
|
|
474
|
+
session = await self.get_session()
|
|
475
|
+
if not session:
|
|
476
|
+
raise AuthSessionMissingError()
|
|
477
|
+
|
|
478
|
+
response = await self._request(
|
|
479
|
+
method="GET",
|
|
480
|
+
path=url,
|
|
481
|
+
query=query,
|
|
482
|
+
jwt=session.access_token,
|
|
483
|
+
)
|
|
484
|
+
link_identity = parse_link_identity_response(response)
|
|
485
|
+
return OAuthResponse(provider=provider, url=link_identity.url)
|
|
486
|
+
|
|
487
|
+
async def get_user_identities(self) -> IdentitiesResponse:
|
|
488
|
+
response = await self.get_user()
|
|
489
|
+
if response:
|
|
490
|
+
return IdentitiesResponse(identities=response.user.identities or [])
|
|
491
|
+
raise AuthSessionMissingError()
|
|
492
|
+
|
|
493
|
+
async def unlink_identity(self, identity: UserIdentity) -> Response:
|
|
494
|
+
session = await self.get_session()
|
|
495
|
+
if not session:
|
|
496
|
+
raise AuthSessionMissingError()
|
|
497
|
+
|
|
498
|
+
return await self._request(
|
|
499
|
+
"DELETE",
|
|
500
|
+
f"user/identities/{identity.identity_id}",
|
|
501
|
+
jwt=session.access_token,
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
async def sign_in_with_otp(
|
|
505
|
+
self,
|
|
506
|
+
credentials: SignInWithPasswordlessCredentials,
|
|
507
|
+
) -> AuthOtpResponse:
|
|
508
|
+
"""
|
|
509
|
+
Log in a user using magiclink or a one-time password (OTP).
|
|
510
|
+
|
|
511
|
+
If the `{{ .ConfirmationURL }}` variable is specified in
|
|
512
|
+
the email template, a magiclink will be sent.
|
|
513
|
+
|
|
514
|
+
If the `{{ .Token }}` variable is specified in the email
|
|
515
|
+
template, an OTP will be sent.
|
|
516
|
+
|
|
517
|
+
If you're using phone sign-ins, only an OTP will be sent.
|
|
518
|
+
You won't be able to send a magiclink for phone sign-ins.
|
|
519
|
+
"""
|
|
520
|
+
email = credentials.get("email")
|
|
521
|
+
phone = credentials.get("phone")
|
|
522
|
+
# TODO(@o-santi): this is horrible, but it is the easiest way to satisfy mypy
|
|
523
|
+
# it should have been a builder pattern instead, and with proper classes
|
|
524
|
+
if email:
|
|
525
|
+
email_options = cast(
|
|
526
|
+
SignInWithEmailAndPasswordlessCredentialsOptions,
|
|
527
|
+
credentials.get("options", {}),
|
|
528
|
+
)
|
|
529
|
+
email_redirect_to = email_options.get("email_redirect_to")
|
|
530
|
+
should_create_user = email_options.get("should_create_user", True)
|
|
531
|
+
data = email_options.get("data")
|
|
532
|
+
channel = email_options.get("channel", "sms")
|
|
533
|
+
captcha_token = email_options.get("captcha_token")
|
|
534
|
+
response = await self._request(
|
|
535
|
+
"POST",
|
|
536
|
+
"otp",
|
|
537
|
+
body=await self._with_pkce_challenge(
|
|
538
|
+
{
|
|
539
|
+
"email": email,
|
|
540
|
+
"data": data,
|
|
541
|
+
"create_user": should_create_user,
|
|
542
|
+
"gotrue_meta_security": {
|
|
543
|
+
"captcha_token": captcha_token,
|
|
544
|
+
},
|
|
545
|
+
}
|
|
546
|
+
),
|
|
547
|
+
redirect_to=email_redirect_to,
|
|
548
|
+
)
|
|
549
|
+
return parse_auth_otp_response(response)
|
|
550
|
+
if phone:
|
|
551
|
+
phone_options = cast(
|
|
552
|
+
SignInWithPhoneAndPasswordlessCredentialsOptions,
|
|
553
|
+
credentials.get("options", {}),
|
|
554
|
+
)
|
|
555
|
+
should_create_user = phone_options.get("should_create_user", True)
|
|
556
|
+
data = phone_options.get("data")
|
|
557
|
+
channel = phone_options.get("channel", "sms")
|
|
558
|
+
captcha_token = phone_options.get("captcha_token")
|
|
559
|
+
response = await self._request(
|
|
560
|
+
"POST",
|
|
561
|
+
"otp",
|
|
562
|
+
body={
|
|
563
|
+
"phone": phone,
|
|
564
|
+
"data": data,
|
|
565
|
+
"create_user": should_create_user,
|
|
566
|
+
"channel": channel,
|
|
567
|
+
"gotrue_meta_security": {
|
|
568
|
+
"captcha_token": captcha_token,
|
|
569
|
+
},
|
|
570
|
+
},
|
|
571
|
+
)
|
|
572
|
+
return parse_auth_otp_response(response)
|
|
573
|
+
raise AuthInvalidCredentialsError(
|
|
574
|
+
"You must provide either an email or phone number"
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
async def resend(
|
|
578
|
+
self,
|
|
579
|
+
credentials: ResendCredentials,
|
|
580
|
+
) -> AuthOtpResponse:
|
|
581
|
+
"""
|
|
582
|
+
Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
|
|
583
|
+
"""
|
|
584
|
+
email = credentials.get("email")
|
|
585
|
+
phone = credentials.get("phone")
|
|
586
|
+
type = credentials.get("type")
|
|
587
|
+
options = credentials.get("options", {})
|
|
588
|
+
email_redirect_to: str | None = options.get("email_redirect_to") # type: ignore[assignment]
|
|
589
|
+
captcha_token = options.get("captcha_token")
|
|
590
|
+
body: dict[str, object] = { # improve later
|
|
591
|
+
"type": type,
|
|
592
|
+
"gotrue_meta_security": {
|
|
593
|
+
"captcha_token": captcha_token,
|
|
594
|
+
},
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if email is None and phone is None:
|
|
598
|
+
raise AuthInvalidCredentialsError(
|
|
599
|
+
"You must provide either an email or phone number"
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
body.update({"email": email} if email else {"phone": phone})
|
|
603
|
+
|
|
604
|
+
response = await self._request(
|
|
605
|
+
"POST",
|
|
606
|
+
"resend",
|
|
607
|
+
body=body,
|
|
608
|
+
redirect_to=email_redirect_to if email else None,
|
|
609
|
+
)
|
|
610
|
+
return parse_auth_otp_response(response)
|
|
611
|
+
|
|
612
|
+
async def verify_otp(self, params: VerifyOtpParams) -> AuthResponse:
|
|
613
|
+
"""
|
|
614
|
+
Log in a user given a User supplied OTP received via mobile.
|
|
615
|
+
"""
|
|
616
|
+
response = await self._request(
|
|
617
|
+
"POST",
|
|
618
|
+
"verify",
|
|
619
|
+
body={
|
|
620
|
+
"gotrue_meta_security": {
|
|
621
|
+
"captcha_token": params.get("options", {}).get("captcha_token"),
|
|
622
|
+
},
|
|
623
|
+
**params,
|
|
624
|
+
},
|
|
625
|
+
redirect_to=params.get("options", {}).get("redirect_to"),
|
|
626
|
+
)
|
|
627
|
+
if params["type"] == "email_change":
|
|
628
|
+
try:
|
|
629
|
+
data = response.json()
|
|
630
|
+
except ValueError:
|
|
631
|
+
data = None
|
|
632
|
+
if isinstance(data, dict) and data.get("code") == "200":
|
|
633
|
+
return AuthResponse()
|
|
634
|
+
auth_response = parse_auth_response(response)
|
|
635
|
+
if auth_response.session:
|
|
636
|
+
await self._save_session(auth_response.session)
|
|
637
|
+
event: AuthChangeEvent = (
|
|
638
|
+
"PASSWORD_RECOVERY" if params.get("type") == "recovery" else "SIGNED_IN"
|
|
639
|
+
)
|
|
640
|
+
self._notify_all_subscribers(event, auth_response.session)
|
|
641
|
+
return auth_response
|
|
642
|
+
|
|
643
|
+
async def reauthenticate(self) -> AuthResponse:
|
|
644
|
+
session = await self.get_session()
|
|
645
|
+
if not session:
|
|
646
|
+
raise AuthSessionMissingError()
|
|
647
|
+
|
|
648
|
+
await self._request(
|
|
649
|
+
"GET",
|
|
650
|
+
"reauthenticate",
|
|
651
|
+
jwt=session.access_token,
|
|
652
|
+
)
|
|
653
|
+
return AuthResponse(user=None, session=None)
|
|
654
|
+
|
|
655
|
+
async def get_session(self) -> Session | None:
|
|
656
|
+
"""
|
|
657
|
+
Returns the session, refreshing it if necessary.
|
|
658
|
+
|
|
659
|
+
The session returned can be null if the session is not detected which
|
|
660
|
+
can happen in the event a user is not signed-in or has logged out.
|
|
661
|
+
"""
|
|
662
|
+
current_session = await self._load_session()
|
|
663
|
+
if not current_session:
|
|
664
|
+
return None
|
|
665
|
+
time_now = round(time.time())
|
|
666
|
+
has_expired = (
|
|
667
|
+
current_session.expires_at <= time_now + EXPIRY_MARGIN
|
|
668
|
+
if current_session.expires_at
|
|
669
|
+
else False
|
|
670
|
+
)
|
|
671
|
+
return (
|
|
672
|
+
await self._call_refresh_token(current_session.refresh_token)
|
|
673
|
+
if has_expired
|
|
674
|
+
else current_session
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
async def get_user(self, jwt: str | None = None) -> UserResponse | None:
|
|
678
|
+
"""
|
|
679
|
+
Gets the current user details if there is an existing session.
|
|
680
|
+
|
|
681
|
+
Takes in an optional access token `jwt`. If no `jwt` is provided,
|
|
682
|
+
`get_user()` will attempt to get the `jwt` from the current session.
|
|
683
|
+
|
|
684
|
+
Returns `None` if no `jwt` is provided and there is no active
|
|
685
|
+
session to retrieve one from.
|
|
686
|
+
"""
|
|
687
|
+
if not jwt:
|
|
688
|
+
session = await self.get_session()
|
|
689
|
+
if session:
|
|
690
|
+
jwt = session.access_token
|
|
691
|
+
else:
|
|
692
|
+
return None
|
|
693
|
+
return parse_user_response(await self._request("GET", "user", jwt=jwt))
|
|
694
|
+
|
|
695
|
+
async def update_user(
|
|
696
|
+
self, attributes: UserAttributes, options: UpdateUserOptions | None = None
|
|
697
|
+
) -> UserResponse:
|
|
698
|
+
"""
|
|
699
|
+
Updates user data, if there is a logged in user.
|
|
700
|
+
"""
|
|
701
|
+
session = await self.get_session()
|
|
702
|
+
if not session:
|
|
703
|
+
raise AuthSessionMissingError()
|
|
704
|
+
update_options = options or {}
|
|
705
|
+
body = dict(attributes)
|
|
706
|
+
if attributes.get("email") is not None:
|
|
707
|
+
await self._with_pkce_challenge(body)
|
|
708
|
+
response = await self._request(
|
|
709
|
+
"PUT",
|
|
710
|
+
"user",
|
|
711
|
+
body=body,
|
|
712
|
+
redirect_to=update_options.get("email_redirect_to"),
|
|
713
|
+
jwt=session.access_token,
|
|
714
|
+
)
|
|
715
|
+
user_response = parse_user_response(response)
|
|
716
|
+
session.user = user_response.user
|
|
717
|
+
await self._save_session(session)
|
|
718
|
+
self._notify_all_subscribers("USER_UPDATED", session)
|
|
719
|
+
return user_response
|
|
720
|
+
|
|
721
|
+
async def set_session(self, access_token: str, refresh_token: str) -> AuthResponse:
|
|
722
|
+
"""
|
|
723
|
+
Sets the session data from the current session. If the current session
|
|
724
|
+
is expired, `set_session` will take care of refreshing it to obtain a
|
|
725
|
+
new session.
|
|
726
|
+
|
|
727
|
+
If the refresh token in the current session is invalid and the current
|
|
728
|
+
session has expired, an error will be thrown.
|
|
729
|
+
|
|
730
|
+
If the current session does not contain at `expires_at` field,
|
|
731
|
+
`set_session` will use the exp claim defined in the access token.
|
|
732
|
+
|
|
733
|
+
The current session that minimally contains an access token,
|
|
734
|
+
refresh token and a user.
|
|
735
|
+
"""
|
|
736
|
+
time_now = round(time.time())
|
|
737
|
+
expires_at = time_now
|
|
738
|
+
has_expired = True
|
|
739
|
+
session: Session | None = None
|
|
740
|
+
if access_token:
|
|
741
|
+
payload = decode_jwt(access_token)["payload"]
|
|
742
|
+
exp = payload.get("exp")
|
|
743
|
+
if exp:
|
|
744
|
+
expires_at = int(exp)
|
|
745
|
+
has_expired = expires_at <= time_now
|
|
746
|
+
if has_expired:
|
|
747
|
+
if not refresh_token:
|
|
748
|
+
raise AuthSessionMissingError()
|
|
749
|
+
response = await self._refresh_access_token(refresh_token)
|
|
750
|
+
if not response.session:
|
|
751
|
+
return AuthResponse()
|
|
752
|
+
session = response.session
|
|
753
|
+
else:
|
|
754
|
+
user_response = await self.get_user(access_token)
|
|
755
|
+
if user_response is None:
|
|
756
|
+
raise UserDoesntExist()
|
|
757
|
+
session = Session(
|
|
758
|
+
access_token=access_token,
|
|
759
|
+
refresh_token=refresh_token,
|
|
760
|
+
user=user_response.user,
|
|
761
|
+
token_type="bearer",
|
|
762
|
+
expires_in=expires_at - time_now,
|
|
763
|
+
expires_at=expires_at,
|
|
764
|
+
)
|
|
765
|
+
await self._save_session(session)
|
|
766
|
+
# A still-valid token is a sign-in. TOKEN_REFRESHED is only for a refresh.
|
|
767
|
+
event: AuthChangeEvent = "TOKEN_REFRESHED" if has_expired else "SIGNED_IN"
|
|
768
|
+
self._notify_all_subscribers(event, session)
|
|
769
|
+
return AuthResponse(session=session, user=session.user)
|
|
770
|
+
|
|
771
|
+
async def refresh_session(self, refresh_token: str | None = None) -> AuthResponse:
|
|
772
|
+
"""
|
|
773
|
+
Returns a new session, regardless of expiry status.
|
|
774
|
+
|
|
775
|
+
Takes in an optional current session. If not passed in, then refreshSession()
|
|
776
|
+
will attempt to retrieve it from getSession(). If the current session's
|
|
777
|
+
refresh token is invalid, an error will be thrown.
|
|
778
|
+
"""
|
|
779
|
+
if not refresh_token:
|
|
780
|
+
session = await self.get_session()
|
|
781
|
+
if session:
|
|
782
|
+
refresh_token = session.refresh_token
|
|
783
|
+
if not refresh_token:
|
|
784
|
+
raise AuthSessionMissingError()
|
|
785
|
+
session = await self._call_refresh_token(refresh_token)
|
|
786
|
+
return AuthResponse(session=session, user=session.user)
|
|
787
|
+
|
|
788
|
+
async def sign_out(self, options: SignOutOptions | None = None) -> None:
|
|
789
|
+
"""
|
|
790
|
+
`sign_out` will remove the logged in user from the
|
|
791
|
+
current session and log them out - removing all items from storage and then trigger a `"SIGNED_OUT"` event.
|
|
792
|
+
|
|
793
|
+
For advanced use cases, you can revoke all refresh tokens for a user by passing a user's JWT through to `admin.sign_out`.
|
|
794
|
+
|
|
795
|
+
There is no way to revoke a user's access token jwt until it expires.
|
|
796
|
+
It is recommended to set a shorter expiry on the jwt for this reason.
|
|
797
|
+
|
|
798
|
+
`sign_out` behavior depends on the scope:
|
|
799
|
+
|
|
800
|
+
- `global` (the default): the session is removed and `"SIGNED_OUT"` is
|
|
801
|
+
emitted only after the server revokes all of the user's sessions. If
|
|
802
|
+
the request fails, the error is raised and the session is kept, so the
|
|
803
|
+
call can be retried or replaced with a `local` sign out.
|
|
804
|
+
- `local`: the session is removed and `"SIGNED_OUT"` is emitted first,
|
|
805
|
+
then the request to revoke it on the server is sent. If the request
|
|
806
|
+
fails, the error is raised.
|
|
807
|
+
- `others`: the session is never removed. If the request fails, the
|
|
808
|
+
error is raised.
|
|
809
|
+
|
|
810
|
+
A 401, 403 or 404 response counts as already signed out.
|
|
811
|
+
"""
|
|
812
|
+
scope = (options or {}).get("scope", "global")
|
|
813
|
+
try:
|
|
814
|
+
session = await self.get_session()
|
|
815
|
+
except AuthSessionMissingError:
|
|
816
|
+
session = None
|
|
817
|
+
except AuthApiError:
|
|
818
|
+
# The refresh was rejected, so there is no session left to revoke.
|
|
819
|
+
# The other sessions could not be revoked either.
|
|
820
|
+
if scope == "others":
|
|
821
|
+
raise
|
|
822
|
+
session = None
|
|
823
|
+
except Exception:
|
|
824
|
+
# The access token expired and could not be refreshed, so there is
|
|
825
|
+
# nothing to revoke with. `local` still signs out this device.
|
|
826
|
+
if scope == "local":
|
|
827
|
+
await self._remove_session()
|
|
828
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
829
|
+
raise
|
|
830
|
+
access_token = session.access_token if session else None
|
|
831
|
+
|
|
832
|
+
teardown_error: Exception | None = None
|
|
833
|
+
if scope == "local":
|
|
834
|
+
# A failing `"SIGNED_OUT"` subscriber must not skip the request, so
|
|
835
|
+
# its error is raised once the request has been sent.
|
|
836
|
+
try:
|
|
837
|
+
await self._remove_session()
|
|
838
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
839
|
+
except Exception as e:
|
|
840
|
+
teardown_error = e
|
|
841
|
+
|
|
842
|
+
error: Exception | None = None
|
|
843
|
+
if access_token:
|
|
844
|
+
try:
|
|
845
|
+
await self.admin.sign_out(access_token, scope)
|
|
846
|
+
except Exception as e:
|
|
847
|
+
if not _is_signed_out_error(e):
|
|
848
|
+
error = e
|
|
849
|
+
|
|
850
|
+
if teardown_error is not None:
|
|
851
|
+
raise teardown_error
|
|
852
|
+
if error is not None:
|
|
853
|
+
raise error
|
|
854
|
+
|
|
855
|
+
if scope == "global":
|
|
856
|
+
await self._remove_session()
|
|
857
|
+
self._notify_all_subscribers("SIGNED_OUT", None)
|
|
858
|
+
|
|
859
|
+
def on_auth_state_change(
|
|
860
|
+
self,
|
|
861
|
+
callback: Callable[[AuthChangeEvent, Session | None], None],
|
|
862
|
+
) -> Subscription:
|
|
863
|
+
"""
|
|
864
|
+
Receive a notification every time an auth event happens.
|
|
865
|
+
"""
|
|
866
|
+
unique_id = str(uuid4())
|
|
867
|
+
|
|
868
|
+
def _unsubscribe() -> None:
|
|
869
|
+
self._state_change_emitters.pop(unique_id)
|
|
870
|
+
|
|
871
|
+
subscription = Subscription(
|
|
872
|
+
id=unique_id,
|
|
873
|
+
callback=callback,
|
|
874
|
+
unsubscribe=_unsubscribe,
|
|
875
|
+
)
|
|
876
|
+
self._state_change_emitters[unique_id] = subscription
|
|
877
|
+
return subscription
|
|
878
|
+
|
|
879
|
+
async def reset_password_for_email(
|
|
880
|
+
self, email: str, options: Options | None = None
|
|
881
|
+
) -> None:
|
|
882
|
+
"""
|
|
883
|
+
Sends a password reset request to an email address.
|
|
884
|
+
"""
|
|
885
|
+
reset_options = options or {}
|
|
886
|
+
await self._request(
|
|
887
|
+
"POST",
|
|
888
|
+
"recover",
|
|
889
|
+
body=await self._with_pkce_challenge(
|
|
890
|
+
{
|
|
891
|
+
"email": email,
|
|
892
|
+
"gotrue_meta_security": {
|
|
893
|
+
"captcha_token": reset_options.get("captcha_token"),
|
|
894
|
+
},
|
|
895
|
+
},
|
|
896
|
+
password_recovery=True,
|
|
897
|
+
),
|
|
898
|
+
redirect_to=reset_options.get("redirect_to"),
|
|
899
|
+
)
|
|
900
|
+
|
|
901
|
+
async def reset_password_email(
|
|
902
|
+
self,
|
|
903
|
+
email: str,
|
|
904
|
+
options: Options | None = None,
|
|
905
|
+
) -> None:
|
|
906
|
+
"""
|
|
907
|
+
Sends a password reset request to an email address.
|
|
908
|
+
"""
|
|
909
|
+
|
|
910
|
+
await self.reset_password_for_email(email, options or {})
|
|
911
|
+
|
|
912
|
+
# MFA methods
|
|
913
|
+
|
|
914
|
+
async def _enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse:
|
|
915
|
+
session = await self.get_session()
|
|
916
|
+
if not session:
|
|
917
|
+
raise AuthSessionMissingError()
|
|
918
|
+
|
|
919
|
+
body = {
|
|
920
|
+
"friendly_name": params.get("friendly_name"),
|
|
921
|
+
"factor_type": params.get("factor_type"),
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
if params["factor_type"] == "phone":
|
|
925
|
+
body["phone"] = params.get("phone")
|
|
926
|
+
else:
|
|
927
|
+
body["issuer"] = params.get("issuer")
|
|
928
|
+
|
|
929
|
+
response = await self._request(
|
|
930
|
+
"POST",
|
|
931
|
+
"factors",
|
|
932
|
+
body=body,
|
|
933
|
+
jwt=session.access_token,
|
|
934
|
+
)
|
|
935
|
+
auth_response = AuthMFAEnrollResponse.model_validate_json(response.content)
|
|
936
|
+
if params["factor_type"] == "totp" and auth_response.totp:
|
|
937
|
+
auth_response.totp.qr_code = (
|
|
938
|
+
f"data:image/svg+xml;utf-8,{auth_response.totp.qr_code}"
|
|
939
|
+
)
|
|
940
|
+
return auth_response
|
|
941
|
+
|
|
942
|
+
async def _challenge(self, params: MFAChallengeParams) -> AuthMFAChallengeResponse:
|
|
943
|
+
session = await self.get_session()
|
|
944
|
+
if not session:
|
|
945
|
+
raise AuthSessionMissingError()
|
|
946
|
+
response = await self._request(
|
|
947
|
+
"POST",
|
|
948
|
+
f"factors/{params.get('factor_id')}/challenge",
|
|
949
|
+
body={"channel": params.get("channel")},
|
|
950
|
+
jwt=session.access_token,
|
|
951
|
+
)
|
|
952
|
+
return AuthMFAChallengeResponse.model_validate_json(response.content)
|
|
953
|
+
|
|
954
|
+
async def _challenge_and_verify(
|
|
955
|
+
self,
|
|
956
|
+
params: MFAChallengeAndVerifyParams,
|
|
957
|
+
) -> AuthMFAVerifyResponse:
|
|
958
|
+
response = await self._challenge(
|
|
959
|
+
{
|
|
960
|
+
"factor_id": params["factor_id"],
|
|
961
|
+
}
|
|
962
|
+
)
|
|
963
|
+
return await self._verify(
|
|
964
|
+
{
|
|
965
|
+
"factor_id": params["factor_id"],
|
|
966
|
+
"challenge_id": response.id,
|
|
967
|
+
"code": params["code"],
|
|
968
|
+
}
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
async def _verify(self, params: MFAVerifyParams) -> AuthMFAVerifyResponse:
|
|
972
|
+
session = await self.get_session()
|
|
973
|
+
if not session:
|
|
974
|
+
raise AuthSessionMissingError()
|
|
975
|
+
response = await self._request(
|
|
976
|
+
"POST",
|
|
977
|
+
f"factors/{params.get('factor_id')}/verify",
|
|
978
|
+
body=params,
|
|
979
|
+
jwt=session.access_token,
|
|
980
|
+
)
|
|
981
|
+
auth_response = AuthMFAVerifyResponse.model_validate_json(response.content)
|
|
982
|
+
session = Session.model_validate_json(response.content)
|
|
983
|
+
await self._save_session(session)
|
|
984
|
+
self._notify_all_subscribers("MFA_CHALLENGE_VERIFIED", session)
|
|
985
|
+
return auth_response
|
|
986
|
+
|
|
987
|
+
async def _unenroll(self, params: MFAUnenrollParams) -> AuthMFAUnenrollResponse:
|
|
988
|
+
session = await self.get_session()
|
|
989
|
+
if not session:
|
|
990
|
+
raise AuthSessionMissingError()
|
|
991
|
+
response = await self._request(
|
|
992
|
+
"DELETE",
|
|
993
|
+
f"factors/{params.get('factor_id')}",
|
|
994
|
+
jwt=session.access_token,
|
|
995
|
+
)
|
|
996
|
+
return AuthMFAUnenrollResponse.model_validate_json(response.content)
|
|
997
|
+
|
|
998
|
+
async def _list_factors(self) -> AuthMFAListFactorsResponse:
|
|
999
|
+
response = await self.get_user()
|
|
1000
|
+
factors = response.user.factors or [] if response else []
|
|
1001
|
+
totp = [
|
|
1002
|
+
f for f in factors if f.factor_type == "totp" and f.status == "verified"
|
|
1003
|
+
]
|
|
1004
|
+
phone = [
|
|
1005
|
+
f for f in factors if f.factor_type == "phone" and f.status == "verified"
|
|
1006
|
+
]
|
|
1007
|
+
return AuthMFAListFactorsResponse(all=factors, totp=totp, phone=phone)
|
|
1008
|
+
|
|
1009
|
+
async def _get_authenticator_assurance_level(
|
|
1010
|
+
self,
|
|
1011
|
+
) -> AuthMFAGetAuthenticatorAssuranceLevelResponse:
|
|
1012
|
+
session = await self.get_session()
|
|
1013
|
+
if not session:
|
|
1014
|
+
return AuthMFAGetAuthenticatorAssuranceLevelResponse(
|
|
1015
|
+
current_level=None,
|
|
1016
|
+
next_level=None,
|
|
1017
|
+
current_authentication_methods=[],
|
|
1018
|
+
)
|
|
1019
|
+
payload = decode_jwt(session.access_token)["payload"]
|
|
1020
|
+
current_level = payload.get("aal")
|
|
1021
|
+
verified_factors = [
|
|
1022
|
+
f for f in session.user.factors or [] if f.status == "verified"
|
|
1023
|
+
]
|
|
1024
|
+
next_level = "aal2" if verified_factors else current_level
|
|
1025
|
+
amr_dict_list = payload.get("amr") or []
|
|
1026
|
+
current_authentication_methods = [
|
|
1027
|
+
AMREntry.model_validate(amr) for amr in amr_dict_list
|
|
1028
|
+
]
|
|
1029
|
+
return AuthMFAGetAuthenticatorAssuranceLevelResponse(
|
|
1030
|
+
current_level=current_level,
|
|
1031
|
+
next_level=next_level,
|
|
1032
|
+
current_authentication_methods=current_authentication_methods,
|
|
1033
|
+
)
|
|
1034
|
+
|
|
1035
|
+
# Private methods
|
|
1036
|
+
|
|
1037
|
+
async def _load_session(self) -> Session | None:
|
|
1038
|
+
if not self._persist_session:
|
|
1039
|
+
return self._in_memory_session
|
|
1040
|
+
maybe_session = await self._storage.get_item(self._storage_key)
|
|
1041
|
+
current_session = self._get_valid_session(maybe_session)
|
|
1042
|
+
if not current_session:
|
|
1043
|
+
await self._remove_session()
|
|
1044
|
+
return current_session
|
|
1045
|
+
|
|
1046
|
+
async def _remove_session(self) -> None:
|
|
1047
|
+
if self._persist_session:
|
|
1048
|
+
await self._storage.remove_item(self._storage_key)
|
|
1049
|
+
else:
|
|
1050
|
+
self._in_memory_session = None
|
|
1051
|
+
if self._refresh_token_timer:
|
|
1052
|
+
self._refresh_token_timer.cancel()
|
|
1053
|
+
self._refresh_token_timer = None
|
|
1054
|
+
|
|
1055
|
+
async def _get_session_from_url(
|
|
1056
|
+
self,
|
|
1057
|
+
url: str,
|
|
1058
|
+
) -> tuple[Session, str | None]:
|
|
1059
|
+
if not self._is_implicit_grant_flow(url):
|
|
1060
|
+
raise AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.")
|
|
1061
|
+
params = _parse_url_params(url)
|
|
1062
|
+
error_description = self._get_param(params, "error_description")
|
|
1063
|
+
if error_description:
|
|
1064
|
+
error_code = self._get_param(params, "error_code")
|
|
1065
|
+
error = self._get_param(params, "error")
|
|
1066
|
+
if not error_code:
|
|
1067
|
+
raise AuthImplicitGrantRedirectError("No error_code detected.")
|
|
1068
|
+
if not error:
|
|
1069
|
+
raise AuthImplicitGrantRedirectError("No error detected.")
|
|
1070
|
+
raise AuthImplicitGrantRedirectError(
|
|
1071
|
+
error_description,
|
|
1072
|
+
{"code": error_code, "error": error},
|
|
1073
|
+
)
|
|
1074
|
+
provider_token = self._get_param(params, "provider_token")
|
|
1075
|
+
provider_refresh_token = self._get_param(params, "provider_refresh_token")
|
|
1076
|
+
access_token = self._get_param(params, "access_token")
|
|
1077
|
+
if not access_token:
|
|
1078
|
+
raise AuthImplicitGrantRedirectError("No access_token detected.")
|
|
1079
|
+
expires_in = self._get_param(params, "expires_in")
|
|
1080
|
+
if not expires_in:
|
|
1081
|
+
raise AuthImplicitGrantRedirectError("No expires_in detected.")
|
|
1082
|
+
refresh_token = self._get_param(params, "refresh_token")
|
|
1083
|
+
if not refresh_token:
|
|
1084
|
+
raise AuthImplicitGrantRedirectError("No refresh_token detected.")
|
|
1085
|
+
token_type = self._get_param(params, "token_type")
|
|
1086
|
+
if not token_type:
|
|
1087
|
+
raise AuthImplicitGrantRedirectError("No token_type detected.")
|
|
1088
|
+
time_now = round(time.time())
|
|
1089
|
+
expires_at = time_now + int(expires_in)
|
|
1090
|
+
user = await self.get_user(access_token)
|
|
1091
|
+
if user is None:
|
|
1092
|
+
raise UserDoesntExist()
|
|
1093
|
+
session = Session(
|
|
1094
|
+
provider_token=provider_token,
|
|
1095
|
+
provider_refresh_token=provider_refresh_token,
|
|
1096
|
+
access_token=access_token,
|
|
1097
|
+
expires_in=int(expires_in),
|
|
1098
|
+
expires_at=expires_at,
|
|
1099
|
+
refresh_token=refresh_token,
|
|
1100
|
+
token_type=token_type,
|
|
1101
|
+
user=user.user,
|
|
1102
|
+
)
|
|
1103
|
+
redirect_type = self._get_param(params, "type")
|
|
1104
|
+
return session, redirect_type
|
|
1105
|
+
|
|
1106
|
+
async def _recover_and_refresh(self) -> None:
|
|
1107
|
+
raw_session = await self._storage.get_item(self._storage_key)
|
|
1108
|
+
current_session = self._get_valid_session(raw_session)
|
|
1109
|
+
if not current_session:
|
|
1110
|
+
if raw_session:
|
|
1111
|
+
await self._remove_session()
|
|
1112
|
+
return
|
|
1113
|
+
time_now = round(time.time())
|
|
1114
|
+
expires_at = current_session.expires_at
|
|
1115
|
+
if expires_at and expires_at < time_now + EXPIRY_MARGIN:
|
|
1116
|
+
refresh_token = current_session.refresh_token
|
|
1117
|
+
if not refresh_token:
|
|
1118
|
+
await self._remove_session()
|
|
1119
|
+
return
|
|
1120
|
+
if not self._auto_refresh_token:
|
|
1121
|
+
return
|
|
1122
|
+
self._network_retries += 1
|
|
1123
|
+
try:
|
|
1124
|
+
await self._call_refresh_token(refresh_token)
|
|
1125
|
+
self._network_retries = 0
|
|
1126
|
+
return
|
|
1127
|
+
except Exception as e:
|
|
1128
|
+
if (
|
|
1129
|
+
isinstance(e, AuthRetryableError)
|
|
1130
|
+
and self._network_retries < MAX_RETRIES
|
|
1131
|
+
):
|
|
1132
|
+
if self._refresh_token_timer:
|
|
1133
|
+
self._refresh_token_timer.cancel()
|
|
1134
|
+
self._refresh_token_timer = Timer(
|
|
1135
|
+
(200 * (2 ** (self._network_retries - 1))),
|
|
1136
|
+
self._recover_and_refresh,
|
|
1137
|
+
)
|
|
1138
|
+
self._refresh_token_timer.start()
|
|
1139
|
+
return
|
|
1140
|
+
await self._remove_session()
|
|
1141
|
+
return
|
|
1142
|
+
if self._persist_session:
|
|
1143
|
+
await self._save_session(current_session)
|
|
1144
|
+
self._notify_all_subscribers("SIGNED_IN", current_session)
|
|
1145
|
+
|
|
1146
|
+
async def _call_refresh_token(self, refresh_token: str) -> Session:
|
|
1147
|
+
if not refresh_token:
|
|
1148
|
+
raise AuthSessionMissingError()
|
|
1149
|
+
response = await self._refresh_access_token(refresh_token)
|
|
1150
|
+
if not response.session:
|
|
1151
|
+
raise AuthSessionMissingError()
|
|
1152
|
+
await self._save_session(response.session)
|
|
1153
|
+
self._notify_all_subscribers("TOKEN_REFRESHED", response.session)
|
|
1154
|
+
return response.session
|
|
1155
|
+
|
|
1156
|
+
async def _refresh_access_token(self, refresh_token: str) -> AuthResponse:
|
|
1157
|
+
response = await self._request(
|
|
1158
|
+
"POST",
|
|
1159
|
+
"token",
|
|
1160
|
+
query=QueryParams(grant_type="refresh_token"),
|
|
1161
|
+
body={"refresh_token": refresh_token},
|
|
1162
|
+
)
|
|
1163
|
+
return parse_auth_response(response)
|
|
1164
|
+
|
|
1165
|
+
async def _save_session(self, session: Session) -> None:
|
|
1166
|
+
if not self._persist_session:
|
|
1167
|
+
self._in_memory_session = session
|
|
1168
|
+
expire_at = session.expires_at
|
|
1169
|
+
if expire_at:
|
|
1170
|
+
time_now = round(time.time())
|
|
1171
|
+
expire_in = expire_at - time_now
|
|
1172
|
+
refresh_duration_before_expires = (
|
|
1173
|
+
EXPIRY_MARGIN if expire_in > EXPIRY_MARGIN else 0.5
|
|
1174
|
+
)
|
|
1175
|
+
value = (expire_in - refresh_duration_before_expires) * 1000
|
|
1176
|
+
await self._start_auto_refresh_token(value)
|
|
1177
|
+
if self._persist_session and session.expires_at:
|
|
1178
|
+
await self._storage.set_item(self._storage_key, session.model_dump_json())
|
|
1179
|
+
|
|
1180
|
+
async def _start_auto_refresh_token(self, value: float) -> None:
|
|
1181
|
+
if self._refresh_token_timer:
|
|
1182
|
+
self._refresh_token_timer.cancel()
|
|
1183
|
+
self._refresh_token_timer = None
|
|
1184
|
+
if value <= 0 or not self._auto_refresh_token:
|
|
1185
|
+
return
|
|
1186
|
+
|
|
1187
|
+
async def refresh_token_function() -> None:
|
|
1188
|
+
self._network_retries += 1
|
|
1189
|
+
try:
|
|
1190
|
+
# get_session() would refresh too: the timer fires inside EXPIRY_MARGIN.
|
|
1191
|
+
session = await self._load_session()
|
|
1192
|
+
if session:
|
|
1193
|
+
await self._call_refresh_token(session.refresh_token)
|
|
1194
|
+
self._network_retries = 0
|
|
1195
|
+
except Exception as e:
|
|
1196
|
+
if (
|
|
1197
|
+
isinstance(e, AuthRetryableError)
|
|
1198
|
+
and self._network_retries < MAX_RETRIES
|
|
1199
|
+
):
|
|
1200
|
+
await self._start_auto_refresh_token(
|
|
1201
|
+
200 * (2 ** (self._network_retries - 1))
|
|
1202
|
+
)
|
|
1203
|
+
|
|
1204
|
+
self._refresh_token_timer = Timer(value, refresh_token_function)
|
|
1205
|
+
self._refresh_token_timer.start()
|
|
1206
|
+
|
|
1207
|
+
def _notify_all_subscribers(
|
|
1208
|
+
self,
|
|
1209
|
+
event: AuthChangeEvent,
|
|
1210
|
+
session: Session | None,
|
|
1211
|
+
) -> None:
|
|
1212
|
+
for subscription in list(self._state_change_emitters.values()):
|
|
1213
|
+
subscription.callback(event, session)
|
|
1214
|
+
|
|
1215
|
+
def _get_valid_session(
|
|
1216
|
+
self,
|
|
1217
|
+
raw_session: str | None,
|
|
1218
|
+
) -> Session | None:
|
|
1219
|
+
if not raw_session:
|
|
1220
|
+
return None
|
|
1221
|
+
try:
|
|
1222
|
+
session = Session.model_validate_json(raw_session)
|
|
1223
|
+
if session.expires_at is None:
|
|
1224
|
+
return None
|
|
1225
|
+
return session
|
|
1226
|
+
except Exception:
|
|
1227
|
+
return None
|
|
1228
|
+
|
|
1229
|
+
def _get_param(
|
|
1230
|
+
self,
|
|
1231
|
+
query_params: dict[str, list[str]],
|
|
1232
|
+
name: str,
|
|
1233
|
+
) -> str | None:
|
|
1234
|
+
return query_params[name][0] if name in query_params else None
|
|
1235
|
+
|
|
1236
|
+
def _is_implicit_grant_flow(self, url: str) -> bool:
|
|
1237
|
+
params = _parse_url_params(url)
|
|
1238
|
+
return "access_token" in params or "error_description" in params
|
|
1239
|
+
|
|
1240
|
+
async def _get_url_for_provider(
|
|
1241
|
+
self,
|
|
1242
|
+
url: str,
|
|
1243
|
+
provider: Provider,
|
|
1244
|
+
params: dict[str, str],
|
|
1245
|
+
) -> tuple[str, QueryParams]:
|
|
1246
|
+
query = QueryParams(params)
|
|
1247
|
+
prepared = await self._prepare_pkce_challenge()
|
|
1248
|
+
if prepared:
|
|
1249
|
+
code_challenge, code_challenge_method = prepared
|
|
1250
|
+
query = query.set("code_challenge", code_challenge).set(
|
|
1251
|
+
"code_challenge_method", code_challenge_method
|
|
1252
|
+
)
|
|
1253
|
+
query = query.set("provider", provider)
|
|
1254
|
+
return f"{url}?{query}", query
|
|
1255
|
+
|
|
1256
|
+
async def _prepare_pkce_challenge(
|
|
1257
|
+
self, *, password_recovery: bool = False
|
|
1258
|
+
) -> tuple[str, str] | None:
|
|
1259
|
+
if self._flow_type != "pkce":
|
|
1260
|
+
return None
|
|
1261
|
+
code_verifier = generate_pkce_verifier()
|
|
1262
|
+
stored_verifier = (
|
|
1263
|
+
f"{code_verifier}/PASSWORD_RECOVERY" if password_recovery else code_verifier
|
|
1264
|
+
)
|
|
1265
|
+
await self._storage.set_item(
|
|
1266
|
+
f"{self._storage_key}-code-verifier", stored_verifier
|
|
1267
|
+
)
|
|
1268
|
+
code_challenge = generate_pkce_challenge(code_verifier)
|
|
1269
|
+
code_challenge_method = "plain" if code_verifier == code_challenge else "s256"
|
|
1270
|
+
return code_challenge, code_challenge_method
|
|
1271
|
+
|
|
1272
|
+
async def _with_pkce_challenge(
|
|
1273
|
+
self, body: dict, *, password_recovery: bool = False
|
|
1274
|
+
) -> dict:
|
|
1275
|
+
prepared = await self._prepare_pkce_challenge(
|
|
1276
|
+
password_recovery=password_recovery
|
|
1277
|
+
)
|
|
1278
|
+
if prepared:
|
|
1279
|
+
code_challenge, code_challenge_method = prepared
|
|
1280
|
+
body["code_challenge"] = code_challenge
|
|
1281
|
+
body["code_challenge_method"] = code_challenge_method
|
|
1282
|
+
return body
|
|
1283
|
+
|
|
1284
|
+
async def exchange_code_for_session(
|
|
1285
|
+
self, params: CodeExchangeParams
|
|
1286
|
+
) -> AuthResponse:
|
|
1287
|
+
code_verifier = params.get("code_verifier") or None
|
|
1288
|
+
event: AuthChangeEvent = "SIGNED_IN"
|
|
1289
|
+
if not code_verifier:
|
|
1290
|
+
stored = await self._storage.get_item(f"{self._storage_key}-code-verifier")
|
|
1291
|
+
if stored:
|
|
1292
|
+
code_verifier, _, redirect_type = stored.partition("/")
|
|
1293
|
+
if redirect_type == "PASSWORD_RECOVERY":
|
|
1294
|
+
event = "PASSWORD_RECOVERY"
|
|
1295
|
+
response = await self._request(
|
|
1296
|
+
"POST",
|
|
1297
|
+
"token",
|
|
1298
|
+
query=QueryParams(grant_type="pkce"),
|
|
1299
|
+
body={
|
|
1300
|
+
"auth_code": params.get("auth_code"),
|
|
1301
|
+
"code_verifier": code_verifier,
|
|
1302
|
+
},
|
|
1303
|
+
redirect_to=params.get("redirect_to"),
|
|
1304
|
+
)
|
|
1305
|
+
auth_response = parse_auth_response(response)
|
|
1306
|
+
await self._storage.remove_item(f"{self._storage_key}-code-verifier")
|
|
1307
|
+
if auth_response.session:
|
|
1308
|
+
await self._save_session(auth_response.session)
|
|
1309
|
+
self._notify_all_subscribers(event, auth_response.session)
|
|
1310
|
+
return auth_response
|
|
1311
|
+
|
|
1312
|
+
async def _fetch_jwks(self, kid: str, jwks: JWKSet) -> JWK:
|
|
1313
|
+
jwk: JWK | None = None
|
|
1314
|
+
|
|
1315
|
+
# try fetching from the suplied keys.
|
|
1316
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk.get("kid") == kid), None)
|
|
1317
|
+
|
|
1318
|
+
if jwk:
|
|
1319
|
+
return jwk
|
|
1320
|
+
|
|
1321
|
+
if self._jwks and (
|
|
1322
|
+
self._jwks_cached_at and time.time() - self._jwks_cached_at < self._jwks_ttl
|
|
1323
|
+
):
|
|
1324
|
+
# try fetching from the cache.
|
|
1325
|
+
jwk = next(
|
|
1326
|
+
(jwk for jwk in self._jwks["keys"] if jwk.get("kid") == kid),
|
|
1327
|
+
None,
|
|
1328
|
+
)
|
|
1329
|
+
if jwk:
|
|
1330
|
+
return jwk
|
|
1331
|
+
|
|
1332
|
+
# jwk isn't cached in memory so we need to fetch it from the well-known endpoint
|
|
1333
|
+
response = await self._request("GET", ".well-known/jwks.json")
|
|
1334
|
+
jwks = parse_jwks(response)
|
|
1335
|
+
if response:
|
|
1336
|
+
self._jwks = jwks
|
|
1337
|
+
self._jwks_cached_at = time.time()
|
|
1338
|
+
|
|
1339
|
+
# find the signing key
|
|
1340
|
+
jwk = next((jwk for jwk in jwks["keys"] if jwk.get("kid") == kid), None)
|
|
1341
|
+
if not jwk:
|
|
1342
|
+
raise AuthInvalidJwtError("No matching signing key found in JWKS")
|
|
1343
|
+
|
|
1344
|
+
return jwk
|
|
1345
|
+
|
|
1346
|
+
raise AuthInvalidJwtError("JWT has no valid kid")
|
|
1347
|
+
|
|
1348
|
+
async def get_claims(
|
|
1349
|
+
self, jwt: str | None = None, jwks: JWKSet | None = None
|
|
1350
|
+
) -> ClaimsResponse | None:
|
|
1351
|
+
token = jwt
|
|
1352
|
+
if not token:
|
|
1353
|
+
session = await self.get_session()
|
|
1354
|
+
if not session:
|
|
1355
|
+
return None
|
|
1356
|
+
|
|
1357
|
+
token = session.access_token
|
|
1358
|
+
|
|
1359
|
+
decoded_jwt = decode_jwt(token)
|
|
1360
|
+
|
|
1361
|
+
payload, header, signature = (
|
|
1362
|
+
decoded_jwt["payload"],
|
|
1363
|
+
decoded_jwt["header"],
|
|
1364
|
+
decoded_jwt["signature"],
|
|
1365
|
+
)
|
|
1366
|
+
raw_header, raw_payload = (
|
|
1367
|
+
decoded_jwt["raw"]["header"],
|
|
1368
|
+
decoded_jwt["raw"]["payload"],
|
|
1369
|
+
)
|
|
1370
|
+
|
|
1371
|
+
validate_exp(payload.get("exp"))
|
|
1372
|
+
|
|
1373
|
+
# if symmetric algorithm, fallback to get_user
|
|
1374
|
+
if "kid" not in header or header["alg"] == "HS256":
|
|
1375
|
+
await self.get_user(token)
|
|
1376
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1377
|
+
|
|
1378
|
+
algorithm = get_algorithm_by_name(header["alg"])
|
|
1379
|
+
jwk_set = await self._fetch_jwks(header["kid"], jwks or {"keys": []})
|
|
1380
|
+
signing_key = algorithm.from_jwk(cast(dict[str, str], jwk_set))
|
|
1381
|
+
|
|
1382
|
+
# verify the signature
|
|
1383
|
+
is_valid = algorithm.verify(
|
|
1384
|
+
msg=f"{raw_header}.{raw_payload}".encode(), key=signing_key, sig=signature
|
|
1385
|
+
)
|
|
1386
|
+
|
|
1387
|
+
if not is_valid:
|
|
1388
|
+
raise AuthInvalidJwtError("Invalid JWT signature")
|
|
1389
|
+
|
|
1390
|
+
# If verification succeeds, decode and return claims
|
|
1391
|
+
return ClaimsResponse(claims=payload, headers=header, signature=signature)
|
|
1392
|
+
|
|
1393
|
+
def __del__(self) -> None:
|
|
1394
|
+
"""Clean up resources when the client is destroyed."""
|
|
1395
|
+
if self._refresh_token_timer:
|
|
1396
|
+
try:
|
|
1397
|
+
# Try to cancel the timer
|
|
1398
|
+
self._refresh_token_timer.cancel()
|
|
1399
|
+
except Exception:
|
|
1400
|
+
# Ignore errors if event loop is closed or selector is not registered
|
|
1401
|
+
pass
|
|
1402
|
+
finally:
|
|
1403
|
+
# Always set to None to prevent further attempts
|
|
1404
|
+
self._refresh_token_timer = None
|