seb-auth 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.
- seb_auth/__init__.py +46 -0
- seb_auth/auth.py +43 -0
- seb_auth/client.py +213 -0
- seb_auth/database.py +60 -0
- seb_auth/email.py +98 -0
- seb_auth/exceptions.py +71 -0
- seb_auth-0.1.0.dist-info/METADATA +194 -0
- seb_auth-0.1.0.dist-info/RECORD +11 -0
- seb_auth-0.1.0.dist-info/WHEEL +5 -0
- seb_auth-0.1.0.dist-info/licenses/LICENSE +21 -0
- seb_auth-0.1.0.dist-info/top_level.txt +1 -0
seb_auth/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
seb-auth: Official Python SDK for SebAuth.
|
|
3
|
+
|
|
4
|
+
Example:
|
|
5
|
+
from seb_auth import SebAuth
|
|
6
|
+
|
|
7
|
+
seb = SebAuth() # reads SEBAUTH_API_KEY from env
|
|
8
|
+
seb.email.send(
|
|
9
|
+
to="user@example.com",
|
|
10
|
+
subject="Hello",
|
|
11
|
+
body="Hello from SebAuth!",
|
|
12
|
+
)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from .client import SebAuth
|
|
16
|
+
from .exceptions import (
|
|
17
|
+
SebAuthError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
APIError,
|
|
20
|
+
BadRequestError,
|
|
21
|
+
NotFoundError,
|
|
22
|
+
RateLimitError,
|
|
23
|
+
ServerError,
|
|
24
|
+
TimeoutError,
|
|
25
|
+
ConnectionError,
|
|
26
|
+
InvalidResponseError,
|
|
27
|
+
ConfigurationError,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"SebAuth",
|
|
34
|
+
"SebAuthError",
|
|
35
|
+
"AuthenticationError",
|
|
36
|
+
"APIError",
|
|
37
|
+
"BadRequestError",
|
|
38
|
+
"NotFoundError",
|
|
39
|
+
"RateLimitError",
|
|
40
|
+
"ServerError",
|
|
41
|
+
"TimeoutError",
|
|
42
|
+
"ConnectionError",
|
|
43
|
+
"InvalidResponseError",
|
|
44
|
+
"ConfigurationError",
|
|
45
|
+
"__version__",
|
|
46
|
+
]
|
seb_auth/auth.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Auth service placeholder.
|
|
2
|
+
|
|
3
|
+
The SebAuth authentication endpoints are not yet exposed on the public
|
|
4
|
+
API surface. This module reserves the ``seb.auth`` namespace so that
|
|
5
|
+
methods can be added without breaking users of the SDK.
|
|
6
|
+
|
|
7
|
+
Any call on this service will raise :class:`NotImplementedError` with a
|
|
8
|
+
clear message pointing users at the SebAuth changelog.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
16
|
+
from .client import SebAuth
|
|
17
|
+
|
|
18
|
+
__all__ = ["AuthService"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthService:
|
|
22
|
+
"""Placeholder for future SebAuth authentication endpoints."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, client: "SebAuth") -> None:
|
|
25
|
+
self._client = client
|
|
26
|
+
|
|
27
|
+
def _not_yet_available(self, feature: str) -> "NotImplementedError":
|
|
28
|
+
return NotImplementedError(
|
|
29
|
+
f"seb.auth.{feature} is not yet available in the public SebAuth API. "
|
|
30
|
+
"This namespace is reserved for future releases of the SDK."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def sign_up(self, *args, **kwargs): # pragma: no cover - stub
|
|
34
|
+
raise self._not_yet_available("sign_up")
|
|
35
|
+
|
|
36
|
+
def sign_in(self, *args, **kwargs): # pragma: no cover - stub
|
|
37
|
+
raise self._not_yet_available("sign_in")
|
|
38
|
+
|
|
39
|
+
def sign_out(self, *args, **kwargs): # pragma: no cover - stub
|
|
40
|
+
raise self._not_yet_available("sign_out")
|
|
41
|
+
|
|
42
|
+
def get_user(self, *args, **kwargs): # pragma: no cover - stub
|
|
43
|
+
raise self._not_yet_available("get_user")
|
seb_auth/client.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""The main :class:`SebAuth` client.
|
|
2
|
+
|
|
3
|
+
The client is the entry point for every SebAuth service (email, auth,
|
|
4
|
+
database, ...). It handles authentication, HTTP transport, timeouts, and
|
|
5
|
+
error translation so that individual service modules can stay focused on
|
|
6
|
+
their own business logic.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
from typing import Any, Dict, Mapping, Optional
|
|
15
|
+
|
|
16
|
+
import requests
|
|
17
|
+
|
|
18
|
+
from . import exceptions as exc
|
|
19
|
+
from .auth import AuthService
|
|
20
|
+
from .database import DatabaseService
|
|
21
|
+
from .email import EmailService
|
|
22
|
+
|
|
23
|
+
__all__ = ["SebAuth"]
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("seb_auth")
|
|
26
|
+
|
|
27
|
+
DEFAULT_BASE_URL = "https://seb-auth.lovable.app"
|
|
28
|
+
DEFAULT_TIMEOUT = 30.0
|
|
29
|
+
_USER_AGENT = "seb-auth-python/0.1.0"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _mask_key(api_key: str) -> str:
|
|
33
|
+
"""Return a safe, masked representation of an API key for logging."""
|
|
34
|
+
if not api_key:
|
|
35
|
+
return "<empty>"
|
|
36
|
+
if len(api_key) <= 8:
|
|
37
|
+
return "***"
|
|
38
|
+
return f"{api_key[:6]}…{api_key[-4:]}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SebAuth:
|
|
42
|
+
"""Client for the SebAuth Backend-as-a-Service.
|
|
43
|
+
|
|
44
|
+
The API key is read (in this order) from:
|
|
45
|
+
|
|
46
|
+
1. The ``api_key`` keyword argument.
|
|
47
|
+
2. The ``SEBAUTH_API_KEY`` environment variable.
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
>>> from seb_auth import SebAuth
|
|
51
|
+
>>> seb = SebAuth() # reads SEBAUTH_API_KEY from env
|
|
52
|
+
>>> seb.email.send(to="user@example.com", subject="Hi", body="Hello!")
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
api_key: Optional[str] = None,
|
|
58
|
+
*,
|
|
59
|
+
base_url: Optional[str] = None,
|
|
60
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
61
|
+
session: Optional[requests.Session] = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
resolved_key = api_key or os.environ.get("SEBAUTH_API_KEY")
|
|
64
|
+
if not resolved_key:
|
|
65
|
+
raise exc.ConfigurationError(
|
|
66
|
+
"SebAuth API key is required. Pass api_key=... or set the "
|
|
67
|
+
"SEBAUTH_API_KEY environment variable."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
self._api_key = resolved_key
|
|
71
|
+
self.base_url = (base_url or os.environ.get("SEBAUTH_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
72
|
+
self.timeout = timeout
|
|
73
|
+
self._session = session or requests.Session()
|
|
74
|
+
|
|
75
|
+
# Service namespaces.
|
|
76
|
+
self.email = EmailService(self)
|
|
77
|
+
self.auth = AuthService(self)
|
|
78
|
+
self.database = DatabaseService(self)
|
|
79
|
+
|
|
80
|
+
# ------------------------------------------------------------------ #
|
|
81
|
+
# Public helpers #
|
|
82
|
+
# ------------------------------------------------------------------ #
|
|
83
|
+
|
|
84
|
+
def __repr__(self) -> str: # pragma: no cover - trivial
|
|
85
|
+
return f"SebAuth(base_url={self.base_url!r}, api_key={_mask_key(self._api_key)!r})"
|
|
86
|
+
|
|
87
|
+
def close(self) -> None:
|
|
88
|
+
"""Close the underlying HTTP session."""
|
|
89
|
+
self._session.close()
|
|
90
|
+
|
|
91
|
+
def __enter__(self) -> "SebAuth":
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None: # noqa: D401
|
|
95
|
+
self.close()
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------------------ #
|
|
98
|
+
# Transport #
|
|
99
|
+
# ------------------------------------------------------------------ #
|
|
100
|
+
|
|
101
|
+
def request(
|
|
102
|
+
self,
|
|
103
|
+
method: str,
|
|
104
|
+
path: str,
|
|
105
|
+
*,
|
|
106
|
+
json_body: Optional[Mapping[str, Any]] = None,
|
|
107
|
+
params: Optional[Mapping[str, Any]] = None,
|
|
108
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
109
|
+
timeout: Optional[float] = None,
|
|
110
|
+
) -> Dict[str, Any]:
|
|
111
|
+
"""Send an authenticated HTTP request and return the parsed JSON body.
|
|
112
|
+
|
|
113
|
+
Raises a subclass of :class:`SebAuthError` for any failure.
|
|
114
|
+
"""
|
|
115
|
+
url = f"{self.base_url}{path if path.startswith('/') else '/' + path}"
|
|
116
|
+
merged_headers = {
|
|
117
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
118
|
+
"Accept": "application/json",
|
|
119
|
+
"User-Agent": _USER_AGENT,
|
|
120
|
+
}
|
|
121
|
+
if json_body is not None:
|
|
122
|
+
merged_headers["Content-Type"] = "application/json"
|
|
123
|
+
if headers:
|
|
124
|
+
merged_headers.update(headers)
|
|
125
|
+
|
|
126
|
+
logger.debug(
|
|
127
|
+
"SebAuth %s %s (key=%s)", method, url, _mask_key(self._api_key)
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
response = self._session.request(
|
|
132
|
+
method=method.upper(),
|
|
133
|
+
url=url,
|
|
134
|
+
json=json_body,
|
|
135
|
+
params=params,
|
|
136
|
+
headers=merged_headers,
|
|
137
|
+
timeout=timeout if timeout is not None else self.timeout,
|
|
138
|
+
)
|
|
139
|
+
except requests.exceptions.Timeout as e:
|
|
140
|
+
raise exc.TimeoutError(
|
|
141
|
+
f"Request to SebAuth timed out after "
|
|
142
|
+
f"{timeout if timeout is not None else self.timeout}s"
|
|
143
|
+
) from e
|
|
144
|
+
except requests.exceptions.ConnectionError as e:
|
|
145
|
+
raise exc.ConnectionError(
|
|
146
|
+
f"Could not connect to SebAuth at {self.base_url}"
|
|
147
|
+
) from e
|
|
148
|
+
except requests.exceptions.RequestException as e:
|
|
149
|
+
raise exc.SebAuthError(f"HTTP request failed: {e}") from e
|
|
150
|
+
|
|
151
|
+
return self._handle_response(response)
|
|
152
|
+
|
|
153
|
+
# ------------------------------------------------------------------ #
|
|
154
|
+
# Internals #
|
|
155
|
+
# ------------------------------------------------------------------ #
|
|
156
|
+
|
|
157
|
+
@staticmethod
|
|
158
|
+
def _parse_body(response: requests.Response) -> Any:
|
|
159
|
+
if not response.content:
|
|
160
|
+
return None
|
|
161
|
+
content_type = response.headers.get("Content-Type", "")
|
|
162
|
+
if "application/json" in content_type:
|
|
163
|
+
try:
|
|
164
|
+
return response.json()
|
|
165
|
+
except (json.JSONDecodeError, ValueError) as e:
|
|
166
|
+
raise exc.InvalidResponseError(
|
|
167
|
+
f"SebAuth returned invalid JSON: {e}"
|
|
168
|
+
) from e
|
|
169
|
+
# Some errors may not have a JSON content-type; try best-effort JSON.
|
|
170
|
+
try:
|
|
171
|
+
return response.json()
|
|
172
|
+
except (json.JSONDecodeError, ValueError):
|
|
173
|
+
return response.text
|
|
174
|
+
|
|
175
|
+
def _handle_response(self, response: requests.Response) -> Dict[str, Any]:
|
|
176
|
+
body = self._parse_body(response)
|
|
177
|
+
|
|
178
|
+
if 200 <= response.status_code < 300:
|
|
179
|
+
if body is None:
|
|
180
|
+
return {}
|
|
181
|
+
if isinstance(body, dict):
|
|
182
|
+
return body
|
|
183
|
+
raise exc.InvalidResponseError(
|
|
184
|
+
f"Expected JSON object from SebAuth, got {type(body).__name__}"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Error path — pull a human message out of the body.
|
|
188
|
+
message = "Unknown error"
|
|
189
|
+
if isinstance(body, dict):
|
|
190
|
+
message = (
|
|
191
|
+
body.get("error")
|
|
192
|
+
or body.get("message")
|
|
193
|
+
or body.get("detail")
|
|
194
|
+
or message
|
|
195
|
+
)
|
|
196
|
+
issues = body.get("issues")
|
|
197
|
+
if issues:
|
|
198
|
+
message = f"{message}: {issues}"
|
|
199
|
+
elif isinstance(body, str) and body.strip():
|
|
200
|
+
message = body.strip()
|
|
201
|
+
|
|
202
|
+
status = response.status_code
|
|
203
|
+
if status in (401, 403):
|
|
204
|
+
raise exc.AuthenticationError(message, status_code=status, response_body=body)
|
|
205
|
+
if status == 400:
|
|
206
|
+
raise exc.BadRequestError(message, status_code=status, response_body=body)
|
|
207
|
+
if status == 404:
|
|
208
|
+
raise exc.NotFoundError(message, status_code=status, response_body=body)
|
|
209
|
+
if status == 429:
|
|
210
|
+
raise exc.RateLimitError(message, status_code=status, response_body=body)
|
|
211
|
+
if 500 <= status < 600:
|
|
212
|
+
raise exc.ServerError(message, status_code=status, response_body=body)
|
|
213
|
+
raise exc.APIError(message, status_code=status, response_body=body)
|
seb_auth/database.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Database service placeholder.
|
|
2
|
+
|
|
3
|
+
The SebAuth database endpoints are not yet exposed on the public API
|
|
4
|
+
surface. This module reserves the ``seb.database`` namespace so that
|
|
5
|
+
methods can be added without breaking users of the SDK.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
13
|
+
from .client import SebAuth
|
|
14
|
+
|
|
15
|
+
__all__ = ["DatabaseService", "Table"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Table:
|
|
19
|
+
"""Placeholder for a future table/collection handle."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, service: "DatabaseService", name: str) -> None:
|
|
22
|
+
self._service = service
|
|
23
|
+
self.name = name
|
|
24
|
+
|
|
25
|
+
def _not_yet_available(self, op: str) -> "NotImplementedError":
|
|
26
|
+
return NotImplementedError(
|
|
27
|
+
f"seb.database.table({self.name!r}).{op} is not yet available in "
|
|
28
|
+
"the public SebAuth API. This namespace is reserved for future "
|
|
29
|
+
"releases of the SDK."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
def insert(self, *args, **kwargs): # pragma: no cover - stub
|
|
33
|
+
raise self._not_yet_available("insert")
|
|
34
|
+
|
|
35
|
+
def select(self, *args, **kwargs): # pragma: no cover - stub
|
|
36
|
+
raise self._not_yet_available("select")
|
|
37
|
+
|
|
38
|
+
def update(self, *args, **kwargs): # pragma: no cover - stub
|
|
39
|
+
raise self._not_yet_available("update")
|
|
40
|
+
|
|
41
|
+
def delete(self, *args, **kwargs): # pragma: no cover - stub
|
|
42
|
+
raise self._not_yet_available("delete")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class DatabaseService:
|
|
46
|
+
"""Placeholder for future SebAuth database endpoints."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, client: "SebAuth") -> None:
|
|
49
|
+
self._client = client
|
|
50
|
+
|
|
51
|
+
def table(self, name: str) -> Table:
|
|
52
|
+
"""Return a handle for the given table/collection.
|
|
53
|
+
|
|
54
|
+
Currently every operation on the returned :class:`Table` raises
|
|
55
|
+
:class:`NotImplementedError` because the database endpoints have not
|
|
56
|
+
yet shipped in the public SebAuth API.
|
|
57
|
+
"""
|
|
58
|
+
if not name or not isinstance(name, str):
|
|
59
|
+
raise ValueError("Table name must be a non-empty string")
|
|
60
|
+
return Table(self, name)
|
seb_auth/email.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Email service — wraps ``POST /api/public/v1/mail/send``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
8
|
+
from .client import SebAuth
|
|
9
|
+
|
|
10
|
+
__all__ = ["EmailService", "SendEmailResult"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SendEmailResult(dict):
|
|
14
|
+
"""Result returned by :meth:`EmailService.send`.
|
|
15
|
+
|
|
16
|
+
Behaves like a plain ``dict`` but exposes the most common fields as
|
|
17
|
+
attributes for convenience::
|
|
18
|
+
|
|
19
|
+
result = seb.email.send(to=..., subject=..., body=...)
|
|
20
|
+
print(result.id, result.status)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def id(self) -> Optional[str]:
|
|
25
|
+
return self.get("id")
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def status(self) -> Optional[str]:
|
|
29
|
+
return self.get("status")
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def to_email(self) -> Optional[str]:
|
|
33
|
+
return self.get("to_email")
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def from_email(self) -> Optional[str]:
|
|
37
|
+
return self.get("from_email")
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def message_id(self) -> Optional[str]:
|
|
41
|
+
return self.get("message_id")
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def sent_at(self) -> Optional[str]:
|
|
45
|
+
return self.get("sent_at")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class EmailService:
|
|
49
|
+
"""Send transactional email through SebAuth."""
|
|
50
|
+
|
|
51
|
+
_SEND_PATH = "/api/public/v1/mail/send"
|
|
52
|
+
|
|
53
|
+
def __init__(self, client: "SebAuth") -> None:
|
|
54
|
+
self._client = client
|
|
55
|
+
|
|
56
|
+
def send(
|
|
57
|
+
self,
|
|
58
|
+
to: str,
|
|
59
|
+
subject: str,
|
|
60
|
+
body: str,
|
|
61
|
+
*,
|
|
62
|
+
timeout: Optional[float] = None,
|
|
63
|
+
) -> SendEmailResult:
|
|
64
|
+
"""Send an email through SebAuth.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
to: Recipient email address.
|
|
68
|
+
subject: Email subject.
|
|
69
|
+
body: Email body (plain text or HTML, depending on your account).
|
|
70
|
+
timeout: Optional per-request timeout override in seconds.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
A :class:`SendEmailResult` describing the queued/sent message.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
seb_auth.SebAuthError: If the request fails for any reason.
|
|
77
|
+
"""
|
|
78
|
+
if not to or not isinstance(to, str):
|
|
79
|
+
raise ValueError("'to' must be a non-empty string")
|
|
80
|
+
if not isinstance(subject, str):
|
|
81
|
+
raise ValueError("'subject' must be a string")
|
|
82
|
+
if not isinstance(body, str):
|
|
83
|
+
raise ValueError("'body' must be a string")
|
|
84
|
+
|
|
85
|
+
payload: Dict[str, Any] = {"to": to, "subject": subject, "body": body}
|
|
86
|
+
|
|
87
|
+
response = self._client.request(
|
|
88
|
+
"POST",
|
|
89
|
+
self._SEND_PATH,
|
|
90
|
+
json_body=payload,
|
|
91
|
+
timeout=timeout,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
email = response.get("email") if isinstance(response, dict) else None
|
|
95
|
+
if isinstance(email, dict):
|
|
96
|
+
return SendEmailResult(email)
|
|
97
|
+
# Fall back to the full response if the API shape ever changes.
|
|
98
|
+
return SendEmailResult(response if isinstance(response, dict) else {})
|
seb_auth/exceptions.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Exceptions raised by the SebAuth SDK.
|
|
2
|
+
|
|
3
|
+
All exceptions inherit from :class:`SebAuthError` so users can catch every
|
|
4
|
+
SDK-specific problem with a single ``except SebAuthError`` clause.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SebAuthError(Exception):
|
|
13
|
+
"""Base class for every exception raised by the SebAuth SDK."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigurationError(SebAuthError):
|
|
17
|
+
"""Raised when the SDK is misconfigured (e.g. missing API key)."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class APIError(SebAuthError):
|
|
21
|
+
"""Raised when the SebAuth API returns a non-2xx response.
|
|
22
|
+
|
|
23
|
+
Attributes:
|
|
24
|
+
status_code: HTTP status code returned by the API.
|
|
25
|
+
message: Human-readable error message extracted from the response.
|
|
26
|
+
response_body: Parsed response body (dict if JSON, else raw text).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
message: str,
|
|
32
|
+
status_code: Optional[int] = None,
|
|
33
|
+
response_body: Any = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
self.status_code = status_code
|
|
36
|
+
self.message = message
|
|
37
|
+
self.response_body = response_body
|
|
38
|
+
formatted = f"[{status_code}] {message}" if status_code is not None else message
|
|
39
|
+
super().__init__(formatted)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class BadRequestError(APIError):
|
|
43
|
+
"""HTTP 400 — the request body or parameters were invalid."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AuthenticationError(APIError):
|
|
47
|
+
"""HTTP 401 / 403 — the API key is missing, malformed or invalid."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class NotFoundError(APIError):
|
|
51
|
+
"""HTTP 404 — the requested resource was not found."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class RateLimitError(APIError):
|
|
55
|
+
"""HTTP 429 — you have been rate limited."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ServerError(APIError):
|
|
59
|
+
"""HTTP 5xx — SebAuth is having trouble handling your request."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class TimeoutError(SebAuthError): # noqa: A001 — shadowing builtin is intentional
|
|
63
|
+
"""Raised when a request to SebAuth exceeds the configured timeout."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ConnectionError(SebAuthError): # noqa: A001 — shadowing builtin is intentional
|
|
67
|
+
"""Raised when the SDK cannot connect to the SebAuth API."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class InvalidResponseError(SebAuthError):
|
|
71
|
+
"""Raised when the API responds with something the SDK cannot parse."""
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: seb-auth
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for SebAuth — a Backend-as-a-Service for email, auth, and database.
|
|
5
|
+
Author: SebAuth
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://seb-auth.lovable.app
|
|
8
|
+
Project-URL: Documentation, https://seb-auth.lovable.app
|
|
9
|
+
Project-URL: Source, https://github.com/sebauth/seb-auth-python
|
|
10
|
+
Project-URL: Issues, https://github.com/sebauth/seb-auth-python/issues
|
|
11
|
+
Keywords: sebauth,baas,email,auth,sdk,seb-auth
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Topic :: Communications :: Email
|
|
25
|
+
Requires-Python: >=3.8
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Requires-Dist: requests>=2.25.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-mock>=3.10; extra == "dev"
|
|
32
|
+
Requires-Dist: responses>=0.23; extra == "dev"
|
|
33
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
34
|
+
Requires-Dist: twine>=4.0; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# seb-auth
|
|
38
|
+
|
|
39
|
+
**Official Python SDK for [SebAuth](https://seb-auth.lovable.app)** — a Backend-as-a-Service for email, authentication and database.
|
|
40
|
+
|
|
41
|
+
[](https://pypi.org/project/seb-auth/)
|
|
42
|
+
[](https://pypi.org/project/seb-auth/)
|
|
43
|
+
[](https://opensource.org/licenses/MIT)
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install seb-auth
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Quick start
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from seb_auth import SebAuth
|
|
57
|
+
|
|
58
|
+
# Reads SEBAUTH_API_KEY from the environment.
|
|
59
|
+
seb = SebAuth()
|
|
60
|
+
|
|
61
|
+
result = seb.email.send(
|
|
62
|
+
to="user@example.com",
|
|
63
|
+
subject="Hello",
|
|
64
|
+
body="Hello from SebAuth!",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
print(result.id, result.status)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Set your API key once and forget about it:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
export SEBAUTH_API_KEY="sk_live_..."
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Or pass it explicitly (never hard-code it in your source):
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import os
|
|
80
|
+
from seb_auth import SebAuth
|
|
81
|
+
|
|
82
|
+
seb = SebAuth(api_key=os.environ["MY_SEBAUTH_KEY"])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Features
|
|
86
|
+
|
|
87
|
+
- 📨 **Email** — send transactional email via `seb.email.send(...)`.
|
|
88
|
+
- 🔐 **Auth** — namespace reserved for upcoming SebAuth auth endpoints.
|
|
89
|
+
- 🗄️ **Database** — namespace reserved for upcoming SebAuth database endpoints.
|
|
90
|
+
- ⏱️ Sensible request **timeouts** (30 s default, per-call overridable).
|
|
91
|
+
- 🧯 Typed **exception hierarchy** for easy error handling.
|
|
92
|
+
- 🕵️ Never prints or logs your full API key.
|
|
93
|
+
|
|
94
|
+
## Sending email
|
|
95
|
+
|
|
96
|
+
`seb.email.send(...)` makes a real HTTP request to
|
|
97
|
+
`POST https://seb-auth.lovable.app/api/public/v1/mail/send` and returns a
|
|
98
|
+
result object exposing everything SebAuth tells you about the message.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from seb_auth import SebAuth
|
|
102
|
+
|
|
103
|
+
seb = SebAuth()
|
|
104
|
+
|
|
105
|
+
result = seb.email.send(
|
|
106
|
+
to="jane@example.com",
|
|
107
|
+
subject="Welcome to Acme",
|
|
108
|
+
body="<h1>Hi Jane 👋</h1><p>Thanks for signing up!</p>",
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
print(result.id) # -> "e5e7eea2-..."
|
|
112
|
+
print(result.status) # -> "sent"
|
|
113
|
+
print(result.message_id) # -> "<...@gmail.com>"
|
|
114
|
+
print(result.sent_at) # -> ISO-8601 timestamp
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`SendEmailResult` is a normal `dict`, so `result["id"]` works too.
|
|
118
|
+
|
|
119
|
+
## Error handling
|
|
120
|
+
|
|
121
|
+
Every exception raised by the SDK inherits from `SebAuthError`, so you can
|
|
122
|
+
catch everything with one clause or drill down as needed:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from seb_auth import (
|
|
126
|
+
SebAuth,
|
|
127
|
+
SebAuthError,
|
|
128
|
+
AuthenticationError,
|
|
129
|
+
BadRequestError,
|
|
130
|
+
RateLimitError,
|
|
131
|
+
TimeoutError,
|
|
132
|
+
ConnectionError,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
seb = SebAuth()
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
seb.email.send(to="user@example.com", subject="Hi", body="Hello!")
|
|
139
|
+
except AuthenticationError:
|
|
140
|
+
print("Your API key is invalid.")
|
|
141
|
+
except BadRequestError as e:
|
|
142
|
+
print("Bad request:", e.message)
|
|
143
|
+
except RateLimitError:
|
|
144
|
+
print("Slow down — you're being rate limited.")
|
|
145
|
+
except TimeoutError:
|
|
146
|
+
print("SebAuth took too long to respond.")
|
|
147
|
+
except ConnectionError:
|
|
148
|
+
print("Could not reach SebAuth.")
|
|
149
|
+
except SebAuthError as e:
|
|
150
|
+
print("Something else went wrong:", e)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Every `APIError` exposes `status_code`, `message` and `response_body` for
|
|
154
|
+
easy debugging.
|
|
155
|
+
|
|
156
|
+
## Configuration
|
|
157
|
+
|
|
158
|
+
| Argument | Env var | Default |
|
|
159
|
+
| ------------ | ------------------- | ------------------------------------ |
|
|
160
|
+
| `api_key` | `SEBAUTH_API_KEY` | — *(required)* |
|
|
161
|
+
| `base_url` | `SEBAUTH_BASE_URL` | `https://seb-auth.lovable.app` |
|
|
162
|
+
| `timeout` | — | `30` seconds |
|
|
163
|
+
|
|
164
|
+
You can also pass a custom `requests.Session` via `session=...` if you
|
|
165
|
+
need to configure retries, proxies, or connection pooling.
|
|
166
|
+
|
|
167
|
+
## Context manager
|
|
168
|
+
|
|
169
|
+
`SebAuth` can be used as a context manager to guarantee that the
|
|
170
|
+
underlying HTTP session is closed:
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
with SebAuth() as seb:
|
|
174
|
+
seb.email.send(to="user@example.com", subject="Hi", body="Hello!")
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Roadmap
|
|
178
|
+
|
|
179
|
+
The SebAuth public API currently exposes the email endpoint. The
|
|
180
|
+
`seb.auth` and `seb.database` namespaces are reserved for upcoming
|
|
181
|
+
endpoints and will raise `NotImplementedError` until they ship.
|
|
182
|
+
|
|
183
|
+
## Development
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
git clone https://github.com/sebauth/seb-auth-python
|
|
187
|
+
cd seb-auth-python
|
|
188
|
+
pip install -e ".[dev]"
|
|
189
|
+
pytest
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
MIT © SebAuth
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
seb_auth/__init__.py,sha256=YdW8Uiq7n06s2dC9a2klz7OfwVYOmZiv4CHOhs8cdGk,864
|
|
2
|
+
seb_auth/auth.py,sha256=Pn3A84DWHBcb0xCEZQQXb7z0l_lGQJGHQQPIXhHlxYM,1444
|
|
3
|
+
seb_auth/client.py,sha256=xke6H-RoWIRxX5nicTMVmA-emBKmgDpWvZFGDElJfFA,7619
|
|
4
|
+
seb_auth/database.py,sha256=EWITV09eoL29Gqbr6FMI5Xb8AkKbBqrXyhst9UtS_jg,2014
|
|
5
|
+
seb_auth/email.py,sha256=WGx50jyEzSQdKBFTQXGxYejSr41o0aiIBvHpw2ypxDE,2814
|
|
6
|
+
seb_auth/exceptions.py,sha256=NnIK1-IaTD7xp7bAqdTJhQ2NucYWsVa0nNtt3R8zA-Y,2123
|
|
7
|
+
seb_auth-0.1.0.dist-info/licenses/LICENSE,sha256=R-848iiTjCIN7D_qRmbsHqJks9nEVTeGz50-TAIblIw,1064
|
|
8
|
+
seb_auth-0.1.0.dist-info/METADATA,sha256=P6rl3o2jrqJS2X7TdJyZz9M3xQHT6eEe_N4_MJW1olA,5713
|
|
9
|
+
seb_auth-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
10
|
+
seb_auth-0.1.0.dist-info/top_level.txt,sha256=hOdvSfR2JPumzv7Vd56k0AkGlKQkPh9gHscnbz_zZyI,9
|
|
11
|
+
seb_auth-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SebAuth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
seb_auth
|