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,94 @@
|
|
|
1
|
+
from ..types import (
|
|
2
|
+
AuthMFAChallengeResponse,
|
|
3
|
+
AuthMFAEnrollResponse,
|
|
4
|
+
AuthMFAGetAuthenticatorAssuranceLevelResponse,
|
|
5
|
+
AuthMFAListFactorsResponse,
|
|
6
|
+
AuthMFAUnenrollResponse,
|
|
7
|
+
AuthMFAVerifyResponse,
|
|
8
|
+
MFAChallengeAndVerifyParams,
|
|
9
|
+
MFAChallengeParams,
|
|
10
|
+
MFAEnrollParams,
|
|
11
|
+
MFAUnenrollParams,
|
|
12
|
+
MFAVerifyParams,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SyncGoTrueMFAAPI:
|
|
17
|
+
"""
|
|
18
|
+
Contains the full multi-factor authentication API.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse:
|
|
22
|
+
"""
|
|
23
|
+
Starts the enrollment process for a new Multi-Factor Authentication
|
|
24
|
+
factor. This method creates a new factor in the 'unverified' state.
|
|
25
|
+
Present the QR code or secret to the user and ask them to add it to their
|
|
26
|
+
authenticator app. Ask the user to provide you with an authenticator code
|
|
27
|
+
from their app and verify it by calling challenge and then verify.
|
|
28
|
+
|
|
29
|
+
The first successful verification of an unverified factor activates the
|
|
30
|
+
factor. All other sessions are logged out and the current one gets an
|
|
31
|
+
`aal2` authenticator level.
|
|
32
|
+
"""
|
|
33
|
+
raise NotImplementedError() # pragma: no cover
|
|
34
|
+
|
|
35
|
+
def challenge(self, params: MFAChallengeParams) -> AuthMFAChallengeResponse:
|
|
36
|
+
"""
|
|
37
|
+
Prepares a challenge used to verify that a user has access to a MFA
|
|
38
|
+
factor. Provide the challenge ID and verification code by calling `verify`.
|
|
39
|
+
"""
|
|
40
|
+
raise NotImplementedError() # pragma: no cover
|
|
41
|
+
|
|
42
|
+
def challenge_and_verify(
|
|
43
|
+
self,
|
|
44
|
+
params: MFAChallengeAndVerifyParams,
|
|
45
|
+
) -> AuthMFAVerifyResponse:
|
|
46
|
+
"""
|
|
47
|
+
Helper method which creates a challenge and immediately uses the given code
|
|
48
|
+
to verify against it thereafter. The verification code is provided by the
|
|
49
|
+
user by entering a code seen in their authenticator app.
|
|
50
|
+
"""
|
|
51
|
+
raise NotImplementedError() # pragma: no cover
|
|
52
|
+
|
|
53
|
+
def verify(self, params: MFAVerifyParams) -> AuthMFAVerifyResponse:
|
|
54
|
+
"""
|
|
55
|
+
Verifies a verification code against a challenge. The verification code is
|
|
56
|
+
provided by the user by entering a code seen in their authenticator app.
|
|
57
|
+
"""
|
|
58
|
+
raise NotImplementedError() # pragma: no cover
|
|
59
|
+
|
|
60
|
+
def unenroll(self, params: MFAUnenrollParams) -> AuthMFAUnenrollResponse:
|
|
61
|
+
"""
|
|
62
|
+
Unenroll removes a MFA factor. Unverified factors can safely be ignored
|
|
63
|
+
and it's not necessary to unenroll them. Unenrolling a verified MFA factor
|
|
64
|
+
cannot be done from a session with an `aal1` authenticator level.
|
|
65
|
+
"""
|
|
66
|
+
raise NotImplementedError() # pragma: no cover
|
|
67
|
+
|
|
68
|
+
def list_factors(self) -> AuthMFAListFactorsResponse:
|
|
69
|
+
"""
|
|
70
|
+
Returns the list of MFA factors enabled for this user. For most use cases
|
|
71
|
+
you should consider using `get_authenticator_assurance_level`.
|
|
72
|
+
|
|
73
|
+
This uses a cached version of the factors and avoids incurring a network call.
|
|
74
|
+
If you need to update this list, call `get_user` first.
|
|
75
|
+
"""
|
|
76
|
+
raise NotImplementedError() # pragma: no cover
|
|
77
|
+
|
|
78
|
+
def get_authenticator_assurance_level(
|
|
79
|
+
self,
|
|
80
|
+
) -> AuthMFAGetAuthenticatorAssuranceLevelResponse:
|
|
81
|
+
"""
|
|
82
|
+
Returns the Authenticator Assurance Level (AAL) for the active session.
|
|
83
|
+
|
|
84
|
+
- `aal1` (or `null`) means that the user's identity has been verified only
|
|
85
|
+
with a conventional login (email+password, OTP, magic link, social login,
|
|
86
|
+
etc.).
|
|
87
|
+
- `aal2` means that the user's identity has been verified both with a
|
|
88
|
+
conventional login and at least one MFA factor.
|
|
89
|
+
|
|
90
|
+
Although this method returns a promise, it's fairly quick (microseconds)
|
|
91
|
+
and rarely uses the network. You can use this to check whether the current
|
|
92
|
+
user needs to be shown a screen to verify their MFA factors.
|
|
93
|
+
"""
|
|
94
|
+
raise NotImplementedError() # pragma: no cover
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SyncSupportedStorage(ABC):
|
|
7
|
+
@abstractmethod
|
|
8
|
+
def get_item(self, key: str) -> str | None: ... # pragma: no cover
|
|
9
|
+
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def set_item(self, key: str, value: str) -> None: ... # pragma: no cover
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def remove_item(self, key: str) -> None: ... # pragma: no cover
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SyncMemoryStorage(SyncSupportedStorage):
|
|
18
|
+
def __init__(self) -> None:
|
|
19
|
+
self.storage: dict[str, str] = {}
|
|
20
|
+
|
|
21
|
+
def get_item(self, key: str) -> str | None:
|
|
22
|
+
if key in self.storage:
|
|
23
|
+
return self.storage[key]
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
def set_item(self, key: str, value: str) -> None:
|
|
27
|
+
self.storage[key] = value
|
|
28
|
+
|
|
29
|
+
def remove_item(self, key: str) -> None:
|
|
30
|
+
if key in self.storage:
|
|
31
|
+
del self.storage[key]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
|
|
5
|
+
GOTRUE_URL = "http://localhost:9999"
|
|
6
|
+
EXPIRY_MARGIN = 10 # seconds
|
|
7
|
+
MAX_RETRIES = 10
|
|
8
|
+
STORAGE_KEY = "supabase.auth.token"
|
|
9
|
+
|
|
10
|
+
API_VERSION_HEADER_NAME = "X-Supabase-Api-Version"
|
|
11
|
+
API_VERSIONS_2024_01_01_TIMESTAMP = datetime.timestamp(
|
|
12
|
+
datetime.strptime("2024-01-01", "%Y-%m-%d")
|
|
13
|
+
)
|
|
14
|
+
API_VERSIONS_2024_01_01_NAME = "2024-01-01"
|
|
15
|
+
BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$"
|
corebase/auth/errors.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from typing_extensions import TypedDict
|
|
6
|
+
|
|
7
|
+
ErrorCode = Literal[
|
|
8
|
+
"unexpected_failure",
|
|
9
|
+
"validation_failed",
|
|
10
|
+
"bad_json",
|
|
11
|
+
"email_exists",
|
|
12
|
+
"phone_exists",
|
|
13
|
+
"bad_jwt",
|
|
14
|
+
"not_admin",
|
|
15
|
+
"no_authorization",
|
|
16
|
+
"user_not_found",
|
|
17
|
+
"session_not_found",
|
|
18
|
+
"flow_state_not_found",
|
|
19
|
+
"flow_state_expired",
|
|
20
|
+
"signup_disabled",
|
|
21
|
+
"user_banned",
|
|
22
|
+
"provider_email_needs_verification",
|
|
23
|
+
"invite_not_found",
|
|
24
|
+
"bad_oauth_state",
|
|
25
|
+
"bad_oauth_callback",
|
|
26
|
+
"oauth_provider_not_supported",
|
|
27
|
+
"unexpected_audience",
|
|
28
|
+
"single_identity_not_deletable",
|
|
29
|
+
"email_conflict_identity_not_deletable",
|
|
30
|
+
"identity_already_exists",
|
|
31
|
+
"email_provider_disabled",
|
|
32
|
+
"phone_provider_disabled",
|
|
33
|
+
"too_many_enrolled_mfa_factors",
|
|
34
|
+
"mfa_factor_name_conflict",
|
|
35
|
+
"mfa_factor_not_found",
|
|
36
|
+
"mfa_ip_address_mismatch",
|
|
37
|
+
"mfa_challenge_expired",
|
|
38
|
+
"mfa_verification_failed",
|
|
39
|
+
"mfa_verification_rejected",
|
|
40
|
+
"insufficient_aal",
|
|
41
|
+
"captcha_failed",
|
|
42
|
+
"saml_provider_disabled",
|
|
43
|
+
"manual_linking_disabled",
|
|
44
|
+
"sms_send_failed",
|
|
45
|
+
"email_not_confirmed",
|
|
46
|
+
"phone_not_confirmed",
|
|
47
|
+
"reauth_nonce_missing",
|
|
48
|
+
"saml_relay_state_not_found",
|
|
49
|
+
"saml_relay_state_expired",
|
|
50
|
+
"saml_idp_not_found",
|
|
51
|
+
"saml_assertion_no_user_id",
|
|
52
|
+
"saml_assertion_no_email",
|
|
53
|
+
"user_already_exists",
|
|
54
|
+
"sso_provider_not_found",
|
|
55
|
+
"saml_metadata_fetch_failed",
|
|
56
|
+
"saml_idp_already_exists",
|
|
57
|
+
"sso_domain_already_exists",
|
|
58
|
+
"saml_entity_id_mismatch",
|
|
59
|
+
"conflict",
|
|
60
|
+
"provider_disabled",
|
|
61
|
+
"user_sso_managed",
|
|
62
|
+
"reauthentication_needed",
|
|
63
|
+
"same_password",
|
|
64
|
+
"reauthentication_not_valid",
|
|
65
|
+
"otp_expired",
|
|
66
|
+
"otp_disabled",
|
|
67
|
+
"identity_not_found",
|
|
68
|
+
"weak_password",
|
|
69
|
+
"over_request_rate_limit",
|
|
70
|
+
"over_email_send_rate_limit",
|
|
71
|
+
"over_sms_send_rate_limit",
|
|
72
|
+
"bad_code_verifier",
|
|
73
|
+
"anonymous_provider_disabled",
|
|
74
|
+
"hook_timeout",
|
|
75
|
+
"hook_timeout_after_retry",
|
|
76
|
+
"hook_payload_over_size_limit",
|
|
77
|
+
"hook_payload_invalid_content_type",
|
|
78
|
+
"request_timeout",
|
|
79
|
+
"mfa_phone_enroll_not_enabled",
|
|
80
|
+
"mfa_phone_verify_not_enabled",
|
|
81
|
+
"mfa_totp_enroll_not_enabled",
|
|
82
|
+
"mfa_totp_verify_not_enabled",
|
|
83
|
+
"mfa_webauthn_enroll_not_enabled",
|
|
84
|
+
"mfa_webauthn_verify_not_enabled",
|
|
85
|
+
"mfa_verified_factor_exists",
|
|
86
|
+
"invalid_credentials",
|
|
87
|
+
"email_address_not_authorized",
|
|
88
|
+
"email_address_invalid",
|
|
89
|
+
"invalid_jwt",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AuthError(Exception):
|
|
94
|
+
def __init__(self, message: str, code: ErrorCode | None) -> None:
|
|
95
|
+
Exception.__init__(self, message)
|
|
96
|
+
self.message = message
|
|
97
|
+
self.name = "AuthError"
|
|
98
|
+
self.code = code
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AuthApiErrorDict(TypedDict):
|
|
102
|
+
name: str
|
|
103
|
+
message: str
|
|
104
|
+
status: int
|
|
105
|
+
code: ErrorCode | None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class AuthApiError(AuthError):
|
|
109
|
+
def __init__(self, message: str, status: int, code: ErrorCode | None) -> None:
|
|
110
|
+
AuthError.__init__(self, message, code)
|
|
111
|
+
self.name = "AuthApiError"
|
|
112
|
+
self.status = status
|
|
113
|
+
self.code = code
|
|
114
|
+
|
|
115
|
+
def to_dict(self) -> AuthApiErrorDict:
|
|
116
|
+
return {
|
|
117
|
+
"name": self.name,
|
|
118
|
+
"message": self.message,
|
|
119
|
+
"status": self.status,
|
|
120
|
+
"code": self.code,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AuthUnknownError(AuthError):
|
|
125
|
+
def __init__(self, message: str, original_error: Exception) -> None:
|
|
126
|
+
AuthError.__init__(self, message, None)
|
|
127
|
+
self.name = "AuthUnknownError"
|
|
128
|
+
self.original_error = original_error
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class CustomAuthError(AuthError):
|
|
132
|
+
def __init__(
|
|
133
|
+
self, message: str, name: str, status: int, code: ErrorCode | None
|
|
134
|
+
) -> None:
|
|
135
|
+
AuthError.__init__(self, message, code)
|
|
136
|
+
self.name = name
|
|
137
|
+
self.status = status
|
|
138
|
+
|
|
139
|
+
def to_dict(self) -> AuthApiErrorDict:
|
|
140
|
+
return {
|
|
141
|
+
"name": self.name,
|
|
142
|
+
"message": self.message,
|
|
143
|
+
"status": self.status,
|
|
144
|
+
"code": self.code,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class UserDoesntExist(CustomAuthError):
|
|
149
|
+
def __init__(self) -> None:
|
|
150
|
+
CustomAuthError.__init__(
|
|
151
|
+
self,
|
|
152
|
+
"User does not exist for the provided access token",
|
|
153
|
+
"UserDoesntExist",
|
|
154
|
+
404,
|
|
155
|
+
"user_not_found",
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class AuthSessionMissingError(CustomAuthError):
|
|
160
|
+
def __init__(self) -> None:
|
|
161
|
+
CustomAuthError.__init__(
|
|
162
|
+
self,
|
|
163
|
+
"Auth session missing!",
|
|
164
|
+
"AuthSessionMissingError",
|
|
165
|
+
400,
|
|
166
|
+
None,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class AuthInvalidCredentialsError(CustomAuthError):
|
|
171
|
+
def __init__(self, message: str) -> None:
|
|
172
|
+
CustomAuthError.__init__(
|
|
173
|
+
self,
|
|
174
|
+
message,
|
|
175
|
+
"AuthInvalidCredentialsError",
|
|
176
|
+
400,
|
|
177
|
+
None,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class AuthImplicitGrantRedirectErrorDetails(TypedDict):
|
|
182
|
+
error: str
|
|
183
|
+
code: str
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class AuthImplicitGrantRedirectErrorDict(AuthApiErrorDict):
|
|
187
|
+
details: AuthImplicitGrantRedirectErrorDetails | None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class AuthImplicitGrantRedirectError(CustomAuthError):
|
|
191
|
+
def __init__(
|
|
192
|
+
self,
|
|
193
|
+
message: str,
|
|
194
|
+
details: AuthImplicitGrantRedirectErrorDetails | None = None,
|
|
195
|
+
) -> None:
|
|
196
|
+
CustomAuthError.__init__(
|
|
197
|
+
self,
|
|
198
|
+
message,
|
|
199
|
+
"AuthImplicitGrantRedirectError",
|
|
200
|
+
500,
|
|
201
|
+
None,
|
|
202
|
+
)
|
|
203
|
+
self.details = details
|
|
204
|
+
|
|
205
|
+
def to_dict(self) -> AuthImplicitGrantRedirectErrorDict:
|
|
206
|
+
return {
|
|
207
|
+
"name": self.name,
|
|
208
|
+
"message": self.message,
|
|
209
|
+
"status": self.status,
|
|
210
|
+
"details": self.details,
|
|
211
|
+
"code": self.code,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class AuthRetryableError(CustomAuthError):
|
|
216
|
+
def __init__(self, message: str, status: int) -> None:
|
|
217
|
+
CustomAuthError.__init__(
|
|
218
|
+
self,
|
|
219
|
+
message,
|
|
220
|
+
"AuthRetryableError",
|
|
221
|
+
status,
|
|
222
|
+
None,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class AuthApiErrorWithReasonsDict(AuthApiErrorDict):
|
|
227
|
+
reasons: list[str]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class AuthWeakPasswordError(CustomAuthError):
|
|
231
|
+
def __init__(self, message: str, status: int, reasons: list[str]) -> None:
|
|
232
|
+
CustomAuthError.__init__(
|
|
233
|
+
self,
|
|
234
|
+
message,
|
|
235
|
+
"AuthWeakPasswordError",
|
|
236
|
+
status,
|
|
237
|
+
"weak_password",
|
|
238
|
+
)
|
|
239
|
+
self.reasons = reasons
|
|
240
|
+
|
|
241
|
+
def to_dict(self) -> AuthApiErrorWithReasonsDict:
|
|
242
|
+
return {
|
|
243
|
+
"name": self.name,
|
|
244
|
+
"message": self.message,
|
|
245
|
+
"status": self.status,
|
|
246
|
+
"reasons": self.reasons,
|
|
247
|
+
"code": self.code,
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class AuthInvalidJwtError(CustomAuthError):
|
|
252
|
+
def __init__(self, message: str) -> None:
|
|
253
|
+
CustomAuthError.__init__(
|
|
254
|
+
self,
|
|
255
|
+
message,
|
|
256
|
+
"AuthInvalidJwtError",
|
|
257
|
+
400,
|
|
258
|
+
"invalid_jwt",
|
|
259
|
+
)
|
corebase/auth/helpers.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
import string
|
|
8
|
+
import uuid
|
|
9
|
+
from base64 import urlsafe_b64decode
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import Any, TypedDict
|
|
12
|
+
from urllib.parse import parse_qs, urlparse
|
|
13
|
+
|
|
14
|
+
from httpx import HTTPStatusError, RequestError, Response
|
|
15
|
+
from pydantic import TypeAdapter, ValidationError
|
|
16
|
+
|
|
17
|
+
from .constants import (
|
|
18
|
+
API_VERSION_HEADER_NAME,
|
|
19
|
+
API_VERSIONS_2024_01_01_TIMESTAMP,
|
|
20
|
+
)
|
|
21
|
+
from .errors import (
|
|
22
|
+
AuthApiError,
|
|
23
|
+
AuthError,
|
|
24
|
+
AuthInvalidJwtError,
|
|
25
|
+
AuthRetryableError,
|
|
26
|
+
AuthUnknownError,
|
|
27
|
+
AuthWeakPasswordError,
|
|
28
|
+
)
|
|
29
|
+
from .types import (
|
|
30
|
+
AuthOtpResponse,
|
|
31
|
+
AuthResponse,
|
|
32
|
+
GenerateLinkProperties,
|
|
33
|
+
GenerateLinkResponse,
|
|
34
|
+
JWKSet,
|
|
35
|
+
JWTHeader,
|
|
36
|
+
JWTPayload,
|
|
37
|
+
LinkIdentityResponse,
|
|
38
|
+
Session,
|
|
39
|
+
SSOResponse,
|
|
40
|
+
User,
|
|
41
|
+
UserResponse,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def parse_auth_response(response: Response) -> AuthResponse:
|
|
46
|
+
try:
|
|
47
|
+
session = Session.model_validate_json(response.content)
|
|
48
|
+
user = session.user
|
|
49
|
+
except ValidationError:
|
|
50
|
+
session = None
|
|
51
|
+
user = User.model_validate_json(response.content)
|
|
52
|
+
return AuthResponse(user=user, session=session)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_auth_otp_response(response: Response) -> AuthOtpResponse:
|
|
56
|
+
return AuthOtpResponse.model_validate_json(response.content)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_link_identity_response(response: Response) -> LinkIdentityResponse:
|
|
60
|
+
return LinkIdentityResponse.model_validate_json(response.content)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_link_response(response: Response) -> GenerateLinkResponse:
|
|
64
|
+
properties = GenerateLinkProperties.model_validate_json(response.content)
|
|
65
|
+
user = User.model_validate_json(response.content)
|
|
66
|
+
return GenerateLinkResponse(properties=properties, user=user)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
UserParser: TypeAdapter = TypeAdapter(UserResponse | User)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_user_response(response: Response) -> UserResponse:
|
|
73
|
+
parsed = UserParser.validate_json(response.content)
|
|
74
|
+
return UserResponse(user=parsed) if isinstance(parsed, User) else parsed
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parse_sso_response(response: Response) -> SSOResponse:
|
|
78
|
+
return SSOResponse.model_validate_json(response.content)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
JWKSetParser: TypeAdapter[JWKSet] = TypeAdapter(JWKSet)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _parse_url_params(url: str) -> dict[str, list[str]]:
|
|
85
|
+
result = urlparse(url)
|
|
86
|
+
return {**parse_qs(result.fragment), **parse_qs(result.query)}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def parse_jwks(response: Response) -> JWKSet:
|
|
90
|
+
jwk = JWKSetParser.validate_json(response.content)
|
|
91
|
+
if len(jwk["keys"]) == 0:
|
|
92
|
+
raise AuthInvalidJwtError("JWKS is empty")
|
|
93
|
+
|
|
94
|
+
return jwk
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_error_message(error: Any) -> str:
|
|
98
|
+
props = ["msg", "message", "error_description", "error"]
|
|
99
|
+
|
|
100
|
+
def filter(prop) -> bool:
|
|
101
|
+
return prop in error if isinstance(error, dict) else hasattr(error, prop)
|
|
102
|
+
|
|
103
|
+
return next((error[prop] for prop in props if filter(prop)), str(error))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def handle_exception(
|
|
107
|
+
error: HTTPStatusError | RequestError | RuntimeError,
|
|
108
|
+
) -> AuthError:
|
|
109
|
+
if not isinstance(error, HTTPStatusError):
|
|
110
|
+
return AuthRetryableError(get_error_message(error), 0)
|
|
111
|
+
try:
|
|
112
|
+
network_error_codes = [502, 503, 504, 520, 521, 522, 523, 524, 530]
|
|
113
|
+
status = error.response.status_code
|
|
114
|
+
try:
|
|
115
|
+
data = error.response.json()
|
|
116
|
+
except Exception:
|
|
117
|
+
if status in network_error_codes:
|
|
118
|
+
# The reason phrase is empty when the server sends none and
|
|
119
|
+
# the status is non-standard (e.g. Cloudflare's 520-530).
|
|
120
|
+
return AuthRetryableError(
|
|
121
|
+
error.response.reason_phrase or f"HTTP {status}", status
|
|
122
|
+
)
|
|
123
|
+
raise
|
|
124
|
+
if status in network_error_codes:
|
|
125
|
+
return AuthRetryableError(get_error_message(data), status)
|
|
126
|
+
|
|
127
|
+
error_code = None
|
|
128
|
+
response_api_version = parse_response_api_version(error.response)
|
|
129
|
+
|
|
130
|
+
if (
|
|
131
|
+
response_api_version
|
|
132
|
+
and (
|
|
133
|
+
datetime.timestamp(response_api_version)
|
|
134
|
+
>= API_VERSIONS_2024_01_01_TIMESTAMP
|
|
135
|
+
)
|
|
136
|
+
and isinstance(data, dict)
|
|
137
|
+
and data
|
|
138
|
+
and isinstance(data.get("code"), str)
|
|
139
|
+
):
|
|
140
|
+
error_code = data.get("code")
|
|
141
|
+
elif (
|
|
142
|
+
isinstance(data, dict) and data and isinstance(data.get("error_code"), str)
|
|
143
|
+
):
|
|
144
|
+
error_code = data.get("error_code")
|
|
145
|
+
|
|
146
|
+
if error_code is None:
|
|
147
|
+
# Legacy support for weak password errors, from before error codes
|
|
148
|
+
# existed: the reasons are only carried by the `weak_password` object.
|
|
149
|
+
weak_password = (
|
|
150
|
+
data.get("weak_password") if isinstance(data, dict) else None
|
|
151
|
+
)
|
|
152
|
+
reasons = (
|
|
153
|
+
weak_password.get("reasons")
|
|
154
|
+
if isinstance(weak_password, dict)
|
|
155
|
+
else None
|
|
156
|
+
)
|
|
157
|
+
if (
|
|
158
|
+
isinstance(reasons, list)
|
|
159
|
+
and reasons
|
|
160
|
+
and all(isinstance(reason, str) for reason in reasons)
|
|
161
|
+
):
|
|
162
|
+
return AuthWeakPasswordError(
|
|
163
|
+
get_error_message(data),
|
|
164
|
+
error.response.status_code,
|
|
165
|
+
reasons,
|
|
166
|
+
)
|
|
167
|
+
elif error_code == "weak_password":
|
|
168
|
+
return AuthWeakPasswordError(
|
|
169
|
+
get_error_message(data),
|
|
170
|
+
error.response.status_code,
|
|
171
|
+
data["weak_password"].get("reasons", {}),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
return AuthApiError(
|
|
175
|
+
get_error_message(data),
|
|
176
|
+
error.response.status_code or 500,
|
|
177
|
+
error_code,
|
|
178
|
+
)
|
|
179
|
+
except Exception as e:
|
|
180
|
+
return AuthUnknownError(get_error_message(error), e)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def base64url_to_bytes(base64url: str) -> bytes:
|
|
184
|
+
# Addding padding otherwise the following error happens:
|
|
185
|
+
# binascii.Error: Incorrect padding
|
|
186
|
+
base64url_with_padding = base64url + "=" * (-len(base64url) % 4)
|
|
187
|
+
return urlsafe_b64decode(base64url_with_padding)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class DecodedJWT(TypedDict):
|
|
191
|
+
header: JWTHeader
|
|
192
|
+
payload: JWTPayload
|
|
193
|
+
signature: bytes
|
|
194
|
+
raw: dict[str, str]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
JWTHeaderParser: TypeAdapter[JWTHeader] = TypeAdapter(JWTHeader)
|
|
198
|
+
JWTPayloadParser: TypeAdapter[JWTPayload] = TypeAdapter(JWTPayload)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def decode_jwt(token: str) -> DecodedJWT:
|
|
202
|
+
parts = token.split(".")
|
|
203
|
+
if len(parts) != 3:
|
|
204
|
+
raise AuthInvalidJwtError("Invalid JWT structure")
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
header = JWTHeaderParser.validate_json(base64url_to_bytes(parts[0]))
|
|
208
|
+
payload = JWTPayloadParser.validate_json(base64url_to_bytes(parts[1]))
|
|
209
|
+
signature = base64url_to_bytes(parts[2])
|
|
210
|
+
except ValueError as e:
|
|
211
|
+
raise AuthInvalidJwtError("Invalid JWT structure") from e
|
|
212
|
+
|
|
213
|
+
return DecodedJWT(
|
|
214
|
+
header=header,
|
|
215
|
+
payload=payload,
|
|
216
|
+
signature=signature,
|
|
217
|
+
raw={
|
|
218
|
+
"header": parts[0],
|
|
219
|
+
"payload": parts[1],
|
|
220
|
+
},
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def generate_pkce_verifier(length=64) -> str:
|
|
225
|
+
"""Generate a random PKCE verifier of the specified length."""
|
|
226
|
+
if length < 43 or length > 128:
|
|
227
|
+
raise ValueError("PKCE verifier length must be between 43 and 128 characters")
|
|
228
|
+
|
|
229
|
+
# Define characters that can be used in the PKCE verifier
|
|
230
|
+
charset = string.ascii_letters + string.digits + "-._~"
|
|
231
|
+
|
|
232
|
+
return "".join(secrets.choice(charset) for _ in range(length))
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def generate_pkce_challenge(code_verifier) -> str:
|
|
236
|
+
"""Generate a code challenge from a PKCE verifier."""
|
|
237
|
+
# Hash the verifier using SHA-256
|
|
238
|
+
verifier_bytes = code_verifier.encode("utf-8")
|
|
239
|
+
sha256_hash = hashlib.sha256(verifier_bytes).digest()
|
|
240
|
+
|
|
241
|
+
return base64.urlsafe_b64encode(sha256_hash).rstrip(b"=").decode("utf-8")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
API_VERSION_REGEX = r"^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def parse_response_api_version(response: Response) -> datetime | None:
|
|
248
|
+
api_version = response.headers.get(API_VERSION_HEADER_NAME)
|
|
249
|
+
|
|
250
|
+
if not api_version:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
if re.search(API_VERSION_REGEX, api_version) is None:
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
dt = datetime.strptime(api_version, "%Y-%m-%d")
|
|
258
|
+
return dt
|
|
259
|
+
except Exception:
|
|
260
|
+
return None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def is_http_url(url: str) -> bool:
|
|
264
|
+
return urlparse(url).scheme in {"https", "http"}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def validate_exp(exp: int | None) -> None:
|
|
268
|
+
if not exp:
|
|
269
|
+
raise AuthInvalidJwtError("JWT has no expiration time")
|
|
270
|
+
|
|
271
|
+
time_now = datetime.now().timestamp()
|
|
272
|
+
if exp <= time_now:
|
|
273
|
+
raise AuthInvalidJwtError("JWT has expired")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def is_valid_uuid(value: str) -> bool:
|
|
277
|
+
try:
|
|
278
|
+
uuid.UUID(value)
|
|
279
|
+
return True
|
|
280
|
+
except ValueError:
|
|
281
|
+
return False
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def validate_uuid(id: str | None) -> None:
|
|
285
|
+
if id is None:
|
|
286
|
+
raise ValueError("Invalid id, id is None")
|
|
287
|
+
if not is_valid_uuid(id):
|
|
288
|
+
raise ValueError(f"Invalid id, '{id}' is not a valid uuid")
|
corebase/auth/py.typed
ADDED
|
File without changes
|