hosteday-python 0.1.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.
- hosteday/__init__.py +111 -0
- hosteday/_version.py +3 -0
- hosteday/auth/__init__.py +34 -0
- hosteday/auth/hosteday_auth.py +444 -0
- hosteday/auth/hosteday_auth_storage.py +130 -0
- hosteday/auth/hosteday_session.py +184 -0
- hosteday/auth/hosteday_token_provider.py +82 -0
- hosteday/auth/hosteday_user.py +223 -0
- hosteday/cli/__init__.py +5 -0
- hosteday/cli/setup.py +163 -0
- hosteday/config/__init__.py +15 -0
- hosteday/config/hosteday_config.py +576 -0
- hosteday/config/hosteday_option_keys.py +60 -0
- hosteday/config/hosteday_url_resolver.py +255 -0
- hosteday/connectivity/__init__.py +5 -0
- hosteday/connectivity/hosteday_connectivity.py +147 -0
- hosteday/exceptions.py +233 -0
- hosteday/features/__init__.py +5 -0
- hosteday/features/hosteday_features.py +78 -0
- hosteday/hosteday.py +346 -0
- hosteday/hosteday_client.py +579 -0
- hosteday/http/__init__.py +18 -0
- hosteday/http/hosteday_http_client.py +340 -0
- hosteday/http/hosteday_response_reader.py +171 -0
- hosteday/http/query_builder.py +204 -0
- hosteday/jobs/__init__.py +9 -0
- hosteday/jobs/hosteday_job_response.py +76 -0
- hosteday/jobs/hosteday_jobs_client.py +109 -0
- hosteday/notifications/__init__.py +13 -0
- hosteday/notifications/hosteday_notification_client.py +290 -0
- hosteday/notifications/hosteday_notification_response.py +79 -0
- hosteday/py.typed +1 -0
- hosteday/reactive/__init__.py +5 -0
- hosteday/reactive/observable_state.py +67 -0
- hosteday/realtime/__init__.py +31 -0
- hosteday/realtime/connection_state.py +14 -0
- hosteday/realtime/hosteday_channel.py +258 -0
- hosteday/realtime/hosteday_channel_auth.py +163 -0
- hosteday/realtime/hosteday_channel_type.py +68 -0
- hosteday/realtime/hosteday_realtime_client.py +790 -0
- hosteday/realtime/hosteday_realtime_event.py +130 -0
- hosteday/web/__init__.py +5 -0
- hosteday/web/server.py +637 -0
- hosteday_python/__init__.py +6 -0
- hosteday_python/py.typed +1 -0
- hosteday_python-0.1.0.dist-info/METADATA +205 -0
- hosteday_python-0.1.0.dist-info/RECORD +50 -0
- hosteday_python-0.1.0.dist-info/WHEEL +4 -0
- hosteday_python-0.1.0.dist-info/entry_points.txt +2 -0
- hosteday_python-0.1.0.dist-info/licenses/LICENSE +21 -0
hosteday/__init__.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Official HosteDay Python SDK."""
|
|
2
|
+
|
|
3
|
+
from hosteday._version import __version__
|
|
4
|
+
from hosteday.auth import (
|
|
5
|
+
HostedayAuth,
|
|
6
|
+
HostedayAuthStorage,
|
|
7
|
+
HostedayAuthStorageKeys,
|
|
8
|
+
HostedayAuthTokenProvider,
|
|
9
|
+
HostedayCombinedTokenProvider,
|
|
10
|
+
HostedaySession,
|
|
11
|
+
HostedayTokenProvider,
|
|
12
|
+
HostedayUser,
|
|
13
|
+
HostedayUserCredential,
|
|
14
|
+
JsonFileHostedayAuthStorage,
|
|
15
|
+
KeyringHostedayAuthStorage,
|
|
16
|
+
MemoryHostedayAuthStorage,
|
|
17
|
+
StaticHostedayTokenProvider,
|
|
18
|
+
)
|
|
19
|
+
from hosteday.config import (
|
|
20
|
+
HostedayConfig,
|
|
21
|
+
HostedayOptionKeys,
|
|
22
|
+
HostedayStaticPages,
|
|
23
|
+
HostedayUrlResolver,
|
|
24
|
+
)
|
|
25
|
+
from hosteday.connectivity import HostedayConnectivity
|
|
26
|
+
from hosteday.exceptions import (
|
|
27
|
+
HostedayAuthException,
|
|
28
|
+
HostedayException,
|
|
29
|
+
HostedayRealtimeAuthorizationException,
|
|
30
|
+
)
|
|
31
|
+
from hosteday.features import HostedayFeatures
|
|
32
|
+
from hosteday.hosteday import Hosteday
|
|
33
|
+
from hosteday.hosteday_client import HostedayClient
|
|
34
|
+
from hosteday.http import (
|
|
35
|
+
MAX_FILTER_VALUES,
|
|
36
|
+
MAX_FILTERS,
|
|
37
|
+
HostedayHttpClient,
|
|
38
|
+
HostedayPage,
|
|
39
|
+
HostedayResponseReader,
|
|
40
|
+
QueryBuilder,
|
|
41
|
+
)
|
|
42
|
+
from hosteday.jobs import HostedayJobResponse, HostedayJobsClient
|
|
43
|
+
from hosteday.notifications import (
|
|
44
|
+
HostedayNotificationClient,
|
|
45
|
+
HostedayNotificationResponse,
|
|
46
|
+
)
|
|
47
|
+
from hosteday.reactive import ObservableState
|
|
48
|
+
from hosteday.realtime import (
|
|
49
|
+
ChannelAuthData,
|
|
50
|
+
ChannelSubscription,
|
|
51
|
+
HostedayChannel,
|
|
52
|
+
HostedayChannelAuthorizationDelegate,
|
|
53
|
+
HostedayChannelType,
|
|
54
|
+
HostedayRealtimeCallback,
|
|
55
|
+
HostedayRealtimeClient,
|
|
56
|
+
HostedayRealtimeEvent,
|
|
57
|
+
PresenceChannel,
|
|
58
|
+
RealtimeConnectionState,
|
|
59
|
+
)
|
|
60
|
+
from hosteday.web import HostedayWebApp, HostedayWebError
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"__version__",
|
|
64
|
+
"ChannelAuthData",
|
|
65
|
+
"ChannelSubscription",
|
|
66
|
+
"Hosteday",
|
|
67
|
+
"HostedayAuth",
|
|
68
|
+
"HostedayAuthException",
|
|
69
|
+
"HostedayAuthStorage",
|
|
70
|
+
"HostedayAuthStorageKeys",
|
|
71
|
+
"HostedayAuthTokenProvider",
|
|
72
|
+
"HostedayChannel",
|
|
73
|
+
"HostedayChannelAuthorizationDelegate",
|
|
74
|
+
"HostedayChannelType",
|
|
75
|
+
"HostedayClient",
|
|
76
|
+
"HostedayCombinedTokenProvider",
|
|
77
|
+
"HostedayConfig",
|
|
78
|
+
"HostedayConnectivity",
|
|
79
|
+
"HostedayException",
|
|
80
|
+
"HostedayFeatures",
|
|
81
|
+
"HostedayHttpClient",
|
|
82
|
+
"HostedayJobResponse",
|
|
83
|
+
"HostedayJobsClient",
|
|
84
|
+
"HostedayNotificationClient",
|
|
85
|
+
"HostedayNotificationResponse",
|
|
86
|
+
"HostedayOptionKeys",
|
|
87
|
+
"HostedayPage",
|
|
88
|
+
"HostedayRealtimeAuthorizationException",
|
|
89
|
+
"HostedayRealtimeCallback",
|
|
90
|
+
"HostedayRealtimeClient",
|
|
91
|
+
"HostedayRealtimeEvent",
|
|
92
|
+
"HostedayResponseReader",
|
|
93
|
+
"HostedaySession",
|
|
94
|
+
"HostedayStaticPages",
|
|
95
|
+
"HostedayTokenProvider",
|
|
96
|
+
"HostedayUrlResolver",
|
|
97
|
+
"HostedayUser",
|
|
98
|
+
"HostedayUserCredential",
|
|
99
|
+
"HostedayWebApp",
|
|
100
|
+
"HostedayWebError",
|
|
101
|
+
"JsonFileHostedayAuthStorage",
|
|
102
|
+
"KeyringHostedayAuthStorage",
|
|
103
|
+
"MAX_FILTERS",
|
|
104
|
+
"MAX_FILTER_VALUES",
|
|
105
|
+
"MemoryHostedayAuthStorage",
|
|
106
|
+
"ObservableState",
|
|
107
|
+
"PresenceChannel",
|
|
108
|
+
"QueryBuilder",
|
|
109
|
+
"RealtimeConnectionState",
|
|
110
|
+
"StaticHostedayTokenProvider",
|
|
111
|
+
]
|
hosteday/_version.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Authentication, session persistence, and token provider abstractions."""
|
|
2
|
+
|
|
3
|
+
from hosteday.auth.hosteday_auth import HostedayAuth, HostedayUserCredential
|
|
4
|
+
from hosteday.auth.hosteday_auth_storage import (
|
|
5
|
+
HostedayAuthStorage,
|
|
6
|
+
HostedayAuthStorageKeys,
|
|
7
|
+
JsonFileHostedayAuthStorage,
|
|
8
|
+
KeyringHostedayAuthStorage,
|
|
9
|
+
MemoryHostedayAuthStorage,
|
|
10
|
+
)
|
|
11
|
+
from hosteday.auth.hosteday_session import HostedaySession
|
|
12
|
+
from hosteday.auth.hosteday_token_provider import (
|
|
13
|
+
HostedayAuthTokenProvider,
|
|
14
|
+
HostedayCombinedTokenProvider,
|
|
15
|
+
HostedayTokenProvider,
|
|
16
|
+
StaticHostedayTokenProvider,
|
|
17
|
+
)
|
|
18
|
+
from hosteday.auth.hosteday_user import HostedayUser
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"HostedayAuth",
|
|
22
|
+
"HostedayAuthStorage",
|
|
23
|
+
"HostedayAuthStorageKeys",
|
|
24
|
+
"HostedayAuthTokenProvider",
|
|
25
|
+
"HostedayCombinedTokenProvider",
|
|
26
|
+
"HostedaySession",
|
|
27
|
+
"HostedayTokenProvider",
|
|
28
|
+
"HostedayUser",
|
|
29
|
+
"HostedayUserCredential",
|
|
30
|
+
"JsonFileHostedayAuthStorage",
|
|
31
|
+
"KeyringHostedayAuthStorage",
|
|
32
|
+
"MemoryHostedayAuthStorage",
|
|
33
|
+
"StaticHostedayTokenProvider",
|
|
34
|
+
]
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""Firebase-style authentication service for HosteDay with reactive state streams."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from hosteday.auth.hosteday_auth_storage import (
|
|
12
|
+
HostedayAuthStorage,
|
|
13
|
+
HostedayAuthStorageKeys,
|
|
14
|
+
)
|
|
15
|
+
from hosteday.auth.hosteday_session import HostedaySession
|
|
16
|
+
from hosteday.auth.hosteday_user import HostedayUser
|
|
17
|
+
from hosteday.config.hosteday_config import HostedayConfig
|
|
18
|
+
from hosteday.exceptions import HostedayAuthException, HostedayException
|
|
19
|
+
from hosteday.http.hosteday_http_client import HostedayHttpClient
|
|
20
|
+
from hosteday.reactive.observable_state import ObservableState
|
|
21
|
+
|
|
22
|
+
_SUPPORTED_AVATAR_EXTENSIONS = frozenset({"jpg", "jpeg", "png", "webp"})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class HostedayUserCredential:
|
|
27
|
+
"""Result returned after signing in or creating a new HosteDay user account."""
|
|
28
|
+
|
|
29
|
+
user: HostedayUser
|
|
30
|
+
session: HostedaySession
|
|
31
|
+
is_new_user: bool = False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class HostedayAuth:
|
|
35
|
+
"""Authentication and session lifecycle manager for HosteDay."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
config: HostedayConfig,
|
|
41
|
+
http: HostedayHttpClient,
|
|
42
|
+
storage: HostedayAuthStorage,
|
|
43
|
+
on_session_cleared: Callable[[], Awaitable[None]] | None = None,
|
|
44
|
+
on_before_sign_out: Callable[[], Awaitable[None]] | None = None,
|
|
45
|
+
on_session_activated: Callable[[HostedayUser], Awaitable[None]] | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self.config = config
|
|
48
|
+
self.http = http
|
|
49
|
+
self.storage = storage
|
|
50
|
+
self._on_session_cleared = on_session_cleared
|
|
51
|
+
self._on_before_sign_out = on_before_sign_out
|
|
52
|
+
self._on_session_activated = on_session_activated
|
|
53
|
+
|
|
54
|
+
self._auth_state: ObservableState[HostedayUser | None] = ObservableState(None)
|
|
55
|
+
self._id_token_state: ObservableState[HostedayUser | None] = ObservableState(None)
|
|
56
|
+
self._user_state: ObservableState[HostedayUser | None] = ObservableState(None)
|
|
57
|
+
|
|
58
|
+
self._current_session: HostedaySession | None = None
|
|
59
|
+
self._initialized: bool = False
|
|
60
|
+
self._disposed: bool = False
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def is_initialized(self) -> bool:
|
|
64
|
+
return self._initialized
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def current_user(self) -> HostedayUser | None:
|
|
68
|
+
return self._current_session.user if self._current_session is not None else None
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def current_session(self) -> HostedaySession | None:
|
|
72
|
+
return self._current_session
|
|
73
|
+
|
|
74
|
+
async def initialize(self) -> None:
|
|
75
|
+
"""Restores any persisted session; automatically purges expired or corrupted data."""
|
|
76
|
+
if self._initialized:
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
serialized = await self.storage.read(HostedayAuthStorageKeys.SESSION)
|
|
80
|
+
if serialized and serialized.strip():
|
|
81
|
+
try:
|
|
82
|
+
decoded = json.loads(serialized)
|
|
83
|
+
if not isinstance(decoded, Mapping):
|
|
84
|
+
raise ValueError("Stored Hosteday session is not a JSON object.")
|
|
85
|
+
session = HostedaySession.from_json(decoded)
|
|
86
|
+
if session.is_expired:
|
|
87
|
+
await self._remove_persisted_session()
|
|
88
|
+
else:
|
|
89
|
+
self._current_session = session
|
|
90
|
+
self._auth_state.emit(session.user)
|
|
91
|
+
self._id_token_state.emit(session.user)
|
|
92
|
+
self._user_state.emit(session.user)
|
|
93
|
+
except (ValueError, json.JSONDecodeError):
|
|
94
|
+
await self._remove_persisted_session()
|
|
95
|
+
|
|
96
|
+
self._initialized = True
|
|
97
|
+
|
|
98
|
+
def auth_state_changes(self) -> AsyncIterator[HostedayUser | None]:
|
|
99
|
+
"""Emits current auth state immediately, then on sign-in, sign-out, or account deletion."""
|
|
100
|
+
return self._auth_state.stream(replay_current=True)
|
|
101
|
+
|
|
102
|
+
def id_token_changes(self) -> AsyncIterator[HostedayUser | None]:
|
|
103
|
+
"""Emits current user immediately, then on auth or token changes."""
|
|
104
|
+
return self._id_token_state.stream(replay_current=True)
|
|
105
|
+
|
|
106
|
+
def user_changes(self) -> AsyncIterator[HostedayUser | None]:
|
|
107
|
+
"""Emits current user immediately, then on auth, profile update, or reload."""
|
|
108
|
+
return self._user_state.stream(replay_current=True)
|
|
109
|
+
|
|
110
|
+
async def get_access_token(self) -> str | None:
|
|
111
|
+
await self._ensure_initialized()
|
|
112
|
+
return self._current_session.access_token if self._current_session is not None else None
|
|
113
|
+
|
|
114
|
+
async def sign_in_with_email_and_password(
|
|
115
|
+
self,
|
|
116
|
+
*,
|
|
117
|
+
email: str,
|
|
118
|
+
password: str,
|
|
119
|
+
) -> HostedayUserCredential:
|
|
120
|
+
self._validate_email_and_password(email=email, password=password)
|
|
121
|
+
return await self._authenticate(
|
|
122
|
+
path=self.config.sign_in_path,
|
|
123
|
+
body={"email": email.strip(), "password": password},
|
|
124
|
+
is_new_user=False,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
async def create_user_with_email_and_password(
|
|
128
|
+
self,
|
|
129
|
+
*,
|
|
130
|
+
email: str,
|
|
131
|
+
password: str,
|
|
132
|
+
additional_data: Mapping[str, Any] | None = None,
|
|
133
|
+
) -> HostedayUserCredential:
|
|
134
|
+
self._validate_email_and_password(email=email, password=password)
|
|
135
|
+
body: dict[str, Any] = dict(additional_data) if additional_data else {}
|
|
136
|
+
body.update(
|
|
137
|
+
{
|
|
138
|
+
"email": email.strip(),
|
|
139
|
+
"password": password,
|
|
140
|
+
"password_confirmation": password,
|
|
141
|
+
}
|
|
142
|
+
)
|
|
143
|
+
return await self._authenticate(
|
|
144
|
+
path=self.config.sign_up_path,
|
|
145
|
+
body=body,
|
|
146
|
+
is_new_user=True,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
async def send_password_reset_email(
|
|
150
|
+
self,
|
|
151
|
+
*,
|
|
152
|
+
email: str,
|
|
153
|
+
additional_data: Mapping[str, Any] | None = None,
|
|
154
|
+
) -> None:
|
|
155
|
+
if not email.strip():
|
|
156
|
+
raise HostedayAuthException(
|
|
157
|
+
"An email address is required.",
|
|
158
|
+
code="invalid-email",
|
|
159
|
+
)
|
|
160
|
+
body: dict[str, Any] = dict(additional_data) if additional_data else {}
|
|
161
|
+
body["email"] = email.strip()
|
|
162
|
+
try:
|
|
163
|
+
await self.http.post(self.config.send_password_reset_email_path, body=body)
|
|
164
|
+
except HostedayException as exc:
|
|
165
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
166
|
+
|
|
167
|
+
async def send_current_user_password_reset_email(self) -> None:
|
|
168
|
+
await self._ensure_initialized()
|
|
169
|
+
self._require_signed_in_user()
|
|
170
|
+
try:
|
|
171
|
+
await self.http.post(
|
|
172
|
+
self.config.send_current_user_password_reset_email_path,
|
|
173
|
+
with_auth=True,
|
|
174
|
+
)
|
|
175
|
+
except HostedayException as exc:
|
|
176
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
177
|
+
|
|
178
|
+
async def reload(self) -> HostedayUser:
|
|
179
|
+
await self._ensure_initialized()
|
|
180
|
+
self._require_signed_in_user()
|
|
181
|
+
try:
|
|
182
|
+
response = await self.http.get(self.config.current_user_path, with_auth=True)
|
|
183
|
+
user_payload = self._extract_user_payload(response)
|
|
184
|
+
user = HostedayUser.from_json(user_payload)
|
|
185
|
+
await self._replace_current_user(user)
|
|
186
|
+
return user
|
|
187
|
+
except HostedayException as exc:
|
|
188
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
189
|
+
except ValueError as exc:
|
|
190
|
+
raise HostedayAuthException(
|
|
191
|
+
str(exc),
|
|
192
|
+
code="malformed-auth-response",
|
|
193
|
+
error=exc,
|
|
194
|
+
) from exc
|
|
195
|
+
|
|
196
|
+
async def update_profile(self, *, name: str) -> HostedayUser:
|
|
197
|
+
await self._ensure_initialized()
|
|
198
|
+
self._require_signed_in_user()
|
|
199
|
+
normalized_name = name.strip()
|
|
200
|
+
if not normalized_name:
|
|
201
|
+
raise HostedayAuthException(
|
|
202
|
+
"The user name cannot be empty.",
|
|
203
|
+
code="invalid-name",
|
|
204
|
+
)
|
|
205
|
+
try:
|
|
206
|
+
response = await self.http.put(
|
|
207
|
+
self.config.update_user_path,
|
|
208
|
+
with_auth=True,
|
|
209
|
+
body={"name": normalized_name},
|
|
210
|
+
)
|
|
211
|
+
user_payload = self._try_extract_user_payload(response)
|
|
212
|
+
if user_payload is None:
|
|
213
|
+
return await self.reload()
|
|
214
|
+
user = HostedayUser.from_json(user_payload)
|
|
215
|
+
await self._replace_current_user(user)
|
|
216
|
+
return user
|
|
217
|
+
except HostedayException as exc:
|
|
218
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
219
|
+
|
|
220
|
+
async def update_avatar(self, *, data: bytes, extension: str) -> HostedayUser:
|
|
221
|
+
await self._ensure_initialized()
|
|
222
|
+
self._require_signed_in_user()
|
|
223
|
+
if not data:
|
|
224
|
+
raise HostedayAuthException(
|
|
225
|
+
"Avatar image bytes cannot be empty.",
|
|
226
|
+
code="invalid-avatar-bytes",
|
|
227
|
+
)
|
|
228
|
+
normalized_ext = self._normalize_avatar_extension(extension)
|
|
229
|
+
encoded = base64.b64encode(data).decode("ascii")
|
|
230
|
+
try:
|
|
231
|
+
response = await self.http.post(
|
|
232
|
+
self.config.update_user_avatar_path,
|
|
233
|
+
with_auth=True,
|
|
234
|
+
body={"bytes": encoded, "extension": normalized_ext},
|
|
235
|
+
)
|
|
236
|
+
user_payload = self._try_extract_user_payload(response)
|
|
237
|
+
if user_payload is not None:
|
|
238
|
+
user = HostedayUser.from_json(user_payload)
|
|
239
|
+
await self._replace_current_user(user)
|
|
240
|
+
return user
|
|
241
|
+
return await self.reload()
|
|
242
|
+
except HostedayException as exc:
|
|
243
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
244
|
+
|
|
245
|
+
async def send_email_verification(self) -> None:
|
|
246
|
+
await self._ensure_initialized()
|
|
247
|
+
self._require_signed_in_user()
|
|
248
|
+
try:
|
|
249
|
+
await self.http.post(
|
|
250
|
+
self.config.send_email_verification_notification_path,
|
|
251
|
+
with_auth=True,
|
|
252
|
+
)
|
|
253
|
+
except HostedayException as exc:
|
|
254
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
255
|
+
|
|
256
|
+
async def delete_user(self) -> None:
|
|
257
|
+
await self._ensure_initialized()
|
|
258
|
+
self._require_signed_in_user()
|
|
259
|
+
try:
|
|
260
|
+
await self.http.request(
|
|
261
|
+
method="DELETE",
|
|
262
|
+
path=self.config.delete_user_path,
|
|
263
|
+
with_auth=True,
|
|
264
|
+
)
|
|
265
|
+
await self._clear_local_session(emit_events=True)
|
|
266
|
+
except HostedayException as exc:
|
|
267
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
268
|
+
|
|
269
|
+
async def sign_out(self) -> None:
|
|
270
|
+
"""Signs out remotely and ALWAYS clears the local session even if remote logout fails."""
|
|
271
|
+
await self._ensure_initialized()
|
|
272
|
+
|
|
273
|
+
if self._on_before_sign_out is not None:
|
|
274
|
+
try:
|
|
275
|
+
await self._on_before_sign_out()
|
|
276
|
+
except Exception:
|
|
277
|
+
pass
|
|
278
|
+
|
|
279
|
+
remote_error: BaseException | None = None
|
|
280
|
+
if self._current_session is not None:
|
|
281
|
+
try:
|
|
282
|
+
await self.http.post(self.config.sign_out_path, with_auth=True)
|
|
283
|
+
except BaseException as exc:
|
|
284
|
+
remote_error = exc
|
|
285
|
+
|
|
286
|
+
await self._clear_local_session(emit_events=True)
|
|
287
|
+
|
|
288
|
+
if isinstance(remote_error, HostedayException):
|
|
289
|
+
raise HostedayAuthException.from_hosteday_exception(remote_error) from remote_error
|
|
290
|
+
if remote_error is not None:
|
|
291
|
+
raise remote_error
|
|
292
|
+
|
|
293
|
+
async def dispose(self) -> None:
|
|
294
|
+
"""Releases reactive stream resources without deleting persisted storage."""
|
|
295
|
+
if self._disposed:
|
|
296
|
+
return
|
|
297
|
+
self._disposed = True
|
|
298
|
+
await self._auth_state.close()
|
|
299
|
+
await self._id_token_state.close()
|
|
300
|
+
await self._user_state.close()
|
|
301
|
+
|
|
302
|
+
async def _authenticate(
|
|
303
|
+
self,
|
|
304
|
+
*,
|
|
305
|
+
path: str,
|
|
306
|
+
body: Mapping[str, Any],
|
|
307
|
+
is_new_user: bool,
|
|
308
|
+
) -> HostedayUserCredential:
|
|
309
|
+
await self._ensure_initialized()
|
|
310
|
+
try:
|
|
311
|
+
response = await self.http.post(path, body=body, with_auth=False)
|
|
312
|
+
session = HostedaySession.from_auth_response(response)
|
|
313
|
+
await self._activate_session(session)
|
|
314
|
+
return HostedayUserCredential(
|
|
315
|
+
user=session.user,
|
|
316
|
+
session=session,
|
|
317
|
+
is_new_user=is_new_user,
|
|
318
|
+
)
|
|
319
|
+
except HostedayException as exc:
|
|
320
|
+
raise HostedayAuthException.from_hosteday_exception(exc) from exc
|
|
321
|
+
except ValueError as exc:
|
|
322
|
+
raise HostedayAuthException(
|
|
323
|
+
str(exc),
|
|
324
|
+
code="malformed-auth-response",
|
|
325
|
+
error=exc,
|
|
326
|
+
) from exc
|
|
327
|
+
|
|
328
|
+
async def _activate_session(self, session: HostedaySession) -> None:
|
|
329
|
+
await self._persist_session(session)
|
|
330
|
+
self._current_session = session
|
|
331
|
+
self._auth_state.emit(session.user)
|
|
332
|
+
self._id_token_state.emit(session.user)
|
|
333
|
+
self._user_state.emit(session.user)
|
|
334
|
+
|
|
335
|
+
if self._on_session_activated is not None:
|
|
336
|
+
try:
|
|
337
|
+
await self._on_session_activated(session.user)
|
|
338
|
+
except Exception:
|
|
339
|
+
pass
|
|
340
|
+
|
|
341
|
+
async def _replace_current_user(self, user: HostedayUser) -> None:
|
|
342
|
+
if self._current_session is None:
|
|
343
|
+
raise HostedayAuthException(
|
|
344
|
+
"No authenticated user is available.",
|
|
345
|
+
code="no-current-user",
|
|
346
|
+
)
|
|
347
|
+
updated = self._current_session.copy_with(user=user)
|
|
348
|
+
await self._persist_session(updated)
|
|
349
|
+
self._current_session = updated
|
|
350
|
+
self._user_state.emit(user)
|
|
351
|
+
|
|
352
|
+
async def _clear_local_session(self, *, emit_events: bool) -> None:
|
|
353
|
+
had_session = self._current_session is not None
|
|
354
|
+
await self._remove_persisted_session()
|
|
355
|
+
self._current_session = None
|
|
356
|
+
|
|
357
|
+
if emit_events and had_session:
|
|
358
|
+
self._auth_state.emit(None)
|
|
359
|
+
self._id_token_state.emit(None)
|
|
360
|
+
self._user_state.emit(None)
|
|
361
|
+
|
|
362
|
+
if had_session and self._on_session_cleared is not None:
|
|
363
|
+
try:
|
|
364
|
+
await self._on_session_cleared()
|
|
365
|
+
except Exception:
|
|
366
|
+
pass
|
|
367
|
+
|
|
368
|
+
async def _persist_session(self, session: HostedaySession) -> None:
|
|
369
|
+
await self.storage.write(
|
|
370
|
+
HostedayAuthStorageKeys.SESSION,
|
|
371
|
+
json.dumps(session.to_json()),
|
|
372
|
+
)
|
|
373
|
+
await self.storage.write(
|
|
374
|
+
HostedayAuthStorageKeys.ACCESS_TOKEN,
|
|
375
|
+
session.access_token,
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
async def _remove_persisted_session(self) -> None:
|
|
379
|
+
await self.storage.delete(HostedayAuthStorageKeys.SESSION)
|
|
380
|
+
await self.storage.delete(HostedayAuthStorageKeys.ACCESS_TOKEN)
|
|
381
|
+
|
|
382
|
+
async def _ensure_initialized(self) -> None:
|
|
383
|
+
if not self._initialized:
|
|
384
|
+
await self.initialize()
|
|
385
|
+
|
|
386
|
+
def _require_signed_in_user(self) -> None:
|
|
387
|
+
if self._current_session is None:
|
|
388
|
+
raise HostedayAuthException(
|
|
389
|
+
"This operation requires an authenticated user.",
|
|
390
|
+
code="no-current-user",
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
@staticmethod
|
|
394
|
+
def _validate_email_and_password(*, email: str, password: str) -> None:
|
|
395
|
+
if not email.strip():
|
|
396
|
+
raise HostedayAuthException(
|
|
397
|
+
"An email address is required.",
|
|
398
|
+
code="invalid-email",
|
|
399
|
+
)
|
|
400
|
+
if not password:
|
|
401
|
+
raise HostedayAuthException(
|
|
402
|
+
"A password is required.",
|
|
403
|
+
code="wrong-password",
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
@classmethod
|
|
407
|
+
def _extract_user_payload(cls, response: Mapping[str, Any]) -> dict[str, Any]:
|
|
408
|
+
payload = cls._try_extract_user_payload(response)
|
|
409
|
+
if payload is None:
|
|
410
|
+
raise ValueError("User response does not include a user object.")
|
|
411
|
+
return payload
|
|
412
|
+
|
|
413
|
+
@classmethod
|
|
414
|
+
def _try_extract_user_payload(cls, response: Mapping[str, Any]) -> dict[str, Any] | None:
|
|
415
|
+
root = dict(response)
|
|
416
|
+
data = root.get("data")
|
|
417
|
+
data_dict = dict(data) if isinstance(data, Mapping) else None
|
|
418
|
+
|
|
419
|
+
if isinstance(root.get("user"), Mapping):
|
|
420
|
+
return dict(root["user"])
|
|
421
|
+
if data_dict is not None and isinstance(data_dict.get("user"), Mapping):
|
|
422
|
+
return dict(data_dict["user"])
|
|
423
|
+
if data_dict is not None and cls._looks_like_user(data_dict):
|
|
424
|
+
return data_dict
|
|
425
|
+
if cls._looks_like_user(root):
|
|
426
|
+
return root
|
|
427
|
+
return None
|
|
428
|
+
|
|
429
|
+
@staticmethod
|
|
430
|
+
def _looks_like_user(value: Mapping[str, Any]) -> bool:
|
|
431
|
+
return "id" in value or "user_id" in value or "uuid" in value
|
|
432
|
+
|
|
433
|
+
@staticmethod
|
|
434
|
+
def _normalize_avatar_extension(extension: str) -> str:
|
|
435
|
+
normalized = extension.strip().lower()
|
|
436
|
+
if normalized.startswith("."):
|
|
437
|
+
normalized = normalized[1:]
|
|
438
|
+
if normalized not in _SUPPORTED_AVATAR_EXTENSIONS:
|
|
439
|
+
raise HostedayAuthException(
|
|
440
|
+
f"Unsupported avatar extension: {extension}. "
|
|
441
|
+
"Supported extensions are jpg, jpeg, png, and webp.",
|
|
442
|
+
code="invalid-avatar-extension",
|
|
443
|
+
)
|
|
444
|
+
return normalized
|