skapi 2.4.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.
- skapi/__init__.py +15 -0
- skapi/_cognito.py +386 -0
- skapi/_database.py +1454 -0
- skapi/_encryption.py +1359 -0
- skapi/_forward.py +484 -0
- skapi/_http.py +373 -0
- skapi/_md5.py +94 -0
- skapi/_project.py +83 -0
- skapi/_realtime.py +549 -0
- skapi/_social.py +323 -0
- skapi/_srp.py +126 -0
- skapi/_user.py +880 -0
- skapi/_ws.py +176 -0
- skapi/client.py +270 -0
- skapi/errors.py +26 -0
- skapi-2.4.0.dist-info/METADATA +46 -0
- skapi-2.4.0.dist-info/RECORD +20 -0
- skapi-2.4.0.dist-info/WHEEL +5 -0
- skapi-2.4.0.dist-info/licenses/LICENSE +201 -0
- skapi-2.4.0.dist-info/top_level.txt +1 -0
skapi/_ws.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A small WebSocket client (RFC 6455) on the Python standard library, for skapi-py's realtime
|
|
3
|
+
connection: TLS, the opening handshake, masked client frames, ping/pong, fragmented messages and
|
|
4
|
+
the closing handshake. Text messages only, which is all the realtime API sends.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
import socket
|
|
13
|
+
import ssl
|
|
14
|
+
import struct
|
|
15
|
+
import threading
|
|
16
|
+
from typing import Optional, Tuple
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
20
|
+
|
|
21
|
+
OP_CONT, OP_TEXT, OP_BINARY, OP_CLOSE, OP_PING, OP_PONG = 0x0, 0x1, 0x2, 0x8, 0x9, 0xA
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class WebSocketClosed(Exception):
|
|
25
|
+
def __init__(self, code: Optional[int] = None, reason: str = ""):
|
|
26
|
+
super().__init__(f"closed ({code}) {reason}".strip())
|
|
27
|
+
self.code = code
|
|
28
|
+
self.reason = reason
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class WebSocket:
|
|
32
|
+
def __init__(self, url: str, timeout: float = 30, headers: Optional[dict] = None):
|
|
33
|
+
parts = urlsplit(url)
|
|
34
|
+
if parts.scheme not in ("ws", "wss"):
|
|
35
|
+
raise ValueError(f"not a websocket url: {url}")
|
|
36
|
+
self.url = url
|
|
37
|
+
host = parts.hostname
|
|
38
|
+
port = parts.port or (443 if parts.scheme == "wss" else 80)
|
|
39
|
+
path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
|
|
40
|
+
raw = socket.create_connection((host, port), timeout=timeout)
|
|
41
|
+
if parts.scheme == "wss":
|
|
42
|
+
raw = ssl.create_default_context().wrap_socket(raw, server_hostname=host)
|
|
43
|
+
self.sock = raw
|
|
44
|
+
self._send_lock = threading.Lock()
|
|
45
|
+
self._buffer = b""
|
|
46
|
+
self.closed = False
|
|
47
|
+
self.close_code: Optional[int] = None
|
|
48
|
+
self.close_reason = ""
|
|
49
|
+
self._handshake(host, port, path, parts.scheme, headers or {})
|
|
50
|
+
self.sock.settimeout(None)
|
|
51
|
+
|
|
52
|
+
# ---- handshake ------------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
def _handshake(self, host: str, port: int, path: str, scheme: str, headers: dict) -> None:
|
|
55
|
+
key = base64.b64encode(os.urandom(16)).decode("ascii")
|
|
56
|
+
default_port = 443 if scheme == "wss" else 80
|
|
57
|
+
host_header = host if port == default_port else f"{host}:{port}"
|
|
58
|
+
lines = [
|
|
59
|
+
f"GET {path} HTTP/1.1",
|
|
60
|
+
f"Host: {host_header}",
|
|
61
|
+
"Upgrade: websocket",
|
|
62
|
+
"Connection: Upgrade",
|
|
63
|
+
f"Sec-WebSocket-Key: {key}",
|
|
64
|
+
"Sec-WebSocket-Version: 13",
|
|
65
|
+
] + [f"{k}: {v}" for k, v in headers.items()]
|
|
66
|
+
self.sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("utf-8"))
|
|
67
|
+
response = b""
|
|
68
|
+
while b"\r\n\r\n" not in response:
|
|
69
|
+
chunk = self.sock.recv(4096)
|
|
70
|
+
if not chunk:
|
|
71
|
+
raise WebSocketClosed(None, "connection closed during the handshake")
|
|
72
|
+
response += chunk
|
|
73
|
+
head, _, rest = response.partition(b"\r\n\r\n")
|
|
74
|
+
self._buffer = rest
|
|
75
|
+
status_line, *header_lines = head.decode("latin-1").split("\r\n")
|
|
76
|
+
if " 101 " not in f"{status_line} ":
|
|
77
|
+
raise WebSocketClosed(None, f"handshake refused: {status_line}")
|
|
78
|
+
got = {k.strip().lower(): v.strip() for k, v in (h.split(":", 1) for h in header_lines if ":" in h)}
|
|
79
|
+
expected = base64.b64encode(hashlib.sha1((key + GUID).encode("ascii")).digest()).decode("ascii")
|
|
80
|
+
if got.get("sec-websocket-accept") != expected:
|
|
81
|
+
raise WebSocketClosed(None, "handshake refused: bad Sec-WebSocket-Accept")
|
|
82
|
+
|
|
83
|
+
# ---- frames ---------------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
def _send_frame(self, opcode: int, payload: bytes) -> None:
|
|
86
|
+
header = bytes([0x80 | opcode])
|
|
87
|
+
n = len(payload)
|
|
88
|
+
if n < 126:
|
|
89
|
+
header += bytes([0x80 | n])
|
|
90
|
+
elif n < 65536:
|
|
91
|
+
header += bytes([0x80 | 126]) + struct.pack(">H", n)
|
|
92
|
+
else:
|
|
93
|
+
header += bytes([0x80 | 127]) + struct.pack(">Q", n)
|
|
94
|
+
mask = os.urandom(4)
|
|
95
|
+
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
|
|
96
|
+
with self._send_lock:
|
|
97
|
+
if self.closed and opcode != OP_CLOSE:
|
|
98
|
+
raise WebSocketClosed(self.close_code, self.close_reason)
|
|
99
|
+
self.sock.sendall(header + mask + masked)
|
|
100
|
+
|
|
101
|
+
def _read_exact(self, n: int) -> bytes:
|
|
102
|
+
while len(self._buffer) < n:
|
|
103
|
+
chunk = self.sock.recv(max(4096, n - len(self._buffer)))
|
|
104
|
+
if not chunk:
|
|
105
|
+
self.closed = True
|
|
106
|
+
raise WebSocketClosed(self.close_code or 1006, "connection lost")
|
|
107
|
+
self._buffer += chunk
|
|
108
|
+
data, self._buffer = self._buffer[:n], self._buffer[n:]
|
|
109
|
+
return data
|
|
110
|
+
|
|
111
|
+
def _read_frame(self) -> Tuple[bool, int, bytes]:
|
|
112
|
+
b0, b1 = self._read_exact(2)
|
|
113
|
+
fin, opcode = bool(b0 & 0x80), b0 & 0x0F
|
|
114
|
+
masked, n = bool(b1 & 0x80), b1 & 0x7F
|
|
115
|
+
if n == 126:
|
|
116
|
+
n = struct.unpack(">H", self._read_exact(2))[0]
|
|
117
|
+
elif n == 127:
|
|
118
|
+
n = struct.unpack(">Q", self._read_exact(8))[0]
|
|
119
|
+
mask = self._read_exact(4) if masked else None
|
|
120
|
+
payload = self._read_exact(n)
|
|
121
|
+
if mask:
|
|
122
|
+
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
|
|
123
|
+
return fin, opcode, payload
|
|
124
|
+
|
|
125
|
+
# ---- public ---------------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
def send(self, text: str) -> None:
|
|
128
|
+
self._send_frame(OP_TEXT, text.encode("utf-8"))
|
|
129
|
+
|
|
130
|
+
def recv(self) -> str:
|
|
131
|
+
"""The next text message. Answers pings on its own; raises WebSocketClosed when the connection ends."""
|
|
132
|
+
parts = []
|
|
133
|
+
while True:
|
|
134
|
+
fin, opcode, payload = self._read_frame()
|
|
135
|
+
if opcode == OP_PING:
|
|
136
|
+
self._send_frame(OP_PONG, payload)
|
|
137
|
+
continue
|
|
138
|
+
if opcode == OP_PONG:
|
|
139
|
+
continue
|
|
140
|
+
if opcode == OP_CLOSE:
|
|
141
|
+
code = struct.unpack(">H", payload[:2])[0] if len(payload) >= 2 else 1005
|
|
142
|
+
reason = payload[2:].decode("utf-8", errors="replace")
|
|
143
|
+
if not self.closed:
|
|
144
|
+
try:
|
|
145
|
+
self._send_frame(OP_CLOSE, payload[:2])
|
|
146
|
+
except OSError:
|
|
147
|
+
pass
|
|
148
|
+
self.closed = True
|
|
149
|
+
self.close_code, self.close_reason = code, reason
|
|
150
|
+
try:
|
|
151
|
+
self.sock.close()
|
|
152
|
+
except OSError:
|
|
153
|
+
pass
|
|
154
|
+
raise WebSocketClosed(code, reason)
|
|
155
|
+
if opcode in (OP_TEXT, OP_BINARY, OP_CONT):
|
|
156
|
+
parts.append(payload)
|
|
157
|
+
if fin:
|
|
158
|
+
return b"".join(parts).decode("utf-8", errors="replace")
|
|
159
|
+
|
|
160
|
+
def close(self, code: int = 1000, reason: str = "") -> None:
|
|
161
|
+
if self.closed:
|
|
162
|
+
return
|
|
163
|
+
try:
|
|
164
|
+
self._send_frame(OP_CLOSE, struct.pack(">H", code) + reason.encode("utf-8")[:120])
|
|
165
|
+
except OSError:
|
|
166
|
+
pass
|
|
167
|
+
self.closed = True
|
|
168
|
+
self.close_code, self.close_reason = code, reason
|
|
169
|
+
try:
|
|
170
|
+
self.sock.shutdown(socket.SHUT_RDWR)
|
|
171
|
+
except OSError:
|
|
172
|
+
pass
|
|
173
|
+
try:
|
|
174
|
+
self.sock.close()
|
|
175
|
+
except OSError:
|
|
176
|
+
pass
|
skapi/client.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""The Skapi class: one project, its connection, and the signed-in user's session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from ._cognito import CognitoError, UserPool, make_storage
|
|
12
|
+
from ._database import DatabaseMixin
|
|
13
|
+
from ._forward import ForwardMixin
|
|
14
|
+
from ._social import SocialMixin
|
|
15
|
+
from ._realtime import RealtimeMixin
|
|
16
|
+
from ._encryption import EncryptionMixin, EncState, parse_option as parse_encryption_option, _lib as ensure_crypto_available
|
|
17
|
+
from ._http import Requester
|
|
18
|
+
from ._project import decode_project_id, format_project_id, is_project_id
|
|
19
|
+
from ._user import UserMixin, parse_user_attributes
|
|
20
|
+
from .errors import SkapiError
|
|
21
|
+
|
|
22
|
+
TOKEN_REFRESH_SKEW_SECONDS = 60 * 60 # refresh the ID token when it has less than an hour left
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Skapi(EncryptionMixin, DatabaseMixin, UserMixin, SocialMixin, ForwardMixin, RealtimeMixin):
|
|
26
|
+
"""
|
|
27
|
+
Skapi("<Project ID>") the Project ID from your project's Settings page on skapi.com
|
|
28
|
+
|
|
29
|
+
storage: where the signed-in session is kept between runs. None (default) keeps it in memory for
|
|
30
|
+
this object only; a file path keeps it in that JSON file (created with mode 600); or any
|
|
31
|
+
object with get_item(key), set_item(key, value) and remove_item(key).
|
|
32
|
+
timeout: seconds to wait for each request.
|
|
33
|
+
encryption: True (or options) seals the data of private records in this client before upload.
|
|
34
|
+
Needs the "cryptography" package: pip install "skapi[encryption]".
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, project_id: str, *, storage: Any = None, timeout: float = 120, target_cdn: Optional[str] = None,
|
|
38
|
+
encryption: Any = None):
|
|
39
|
+
if not isinstance(project_id, str) or not project_id.strip():
|
|
40
|
+
raise SkapiError("Project ID is required.", "INVALID_PARAMETER")
|
|
41
|
+
if not is_project_id(project_id.strip()):
|
|
42
|
+
raise SkapiError("Project ID is invalid.", "INVALID_PARAMETER")
|
|
43
|
+
service, owner = decode_project_id(project_id)
|
|
44
|
+
self.service: str = service
|
|
45
|
+
self.owner: str = owner
|
|
46
|
+
try:
|
|
47
|
+
self.project_id: str = format_project_id(service, owner)
|
|
48
|
+
except (ValueError, IndexError):
|
|
49
|
+
self.project_id = ""
|
|
50
|
+
self.version: str = __version__
|
|
51
|
+
self.connection: Optional[Dict[str, Any]] = None
|
|
52
|
+
|
|
53
|
+
self._requester = Requester(service, owner, __version__, target_cdn=target_cdn, timeout=timeout)
|
|
54
|
+
self._storage = make_storage(storage)
|
|
55
|
+
self._pool: Optional[UserPool] = None
|
|
56
|
+
self._session = None
|
|
57
|
+
self._cognito_username: Optional[str] = None
|
|
58
|
+
self._user: Optional[Dict[str, Any]] = None
|
|
59
|
+
self._restored = False
|
|
60
|
+
self._lock = threading.RLock()
|
|
61
|
+
self._refresh_lock = threading.RLock() # one token refresh at a time, shared by every thread
|
|
62
|
+
# Counts sign-outs: _clear_session adds one. A token refresh that started before a sign-out
|
|
63
|
+
# compares it before adopting its tokens, so a refresh still running when the user logged out
|
|
64
|
+
# cannot sign them back in (as skapi-js sessionEpoch).
|
|
65
|
+
self._sign_outs = 0
|
|
66
|
+
self._session_lock = threading.RLock() # makes "not signed out since" + adopting one step
|
|
67
|
+
self._restore_refreshed_token: Optional[str] = None # the id token _restore just refreshed to
|
|
68
|
+
enc_cfg = parse_encryption_option(encryption)
|
|
69
|
+
if enc_cfg:
|
|
70
|
+
ensure_crypto_available() # fails here, with the install hint, when "cryptography" is missing
|
|
71
|
+
self._enc = EncState(enc_cfg) if enc_cfg else None
|
|
72
|
+
|
|
73
|
+
# per-instance state, as in skapi-js
|
|
74
|
+
self._private_access_key: Dict[str, str] = {}
|
|
75
|
+
self._my_unique_ids: Dict[str, Dict[str, str]] = {}
|
|
76
|
+
self._handed_out_file_urls: Dict[str, str] = {} # get_file url given out -> the stored file url
|
|
77
|
+
self._pending_mfa = None
|
|
78
|
+
self._request_signup_confirmation: Optional[str] = None
|
|
79
|
+
self._disabled_account: Optional[str] = None
|
|
80
|
+
self._anonymous_timer: Optional[threading.Timer] = None
|
|
81
|
+
|
|
82
|
+
def __repr__(self) -> str:
|
|
83
|
+
return f"Skapi(project_id={self.project_id!r})"
|
|
84
|
+
|
|
85
|
+
# ---- connection -----------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
def _ensure_connection(self, refresh: bool = False) -> Dict[str, Any]:
|
|
88
|
+
with self._lock:
|
|
89
|
+
if self.connection is None or refresh:
|
|
90
|
+
self.connection = self._requester.request("service", {"service": self.service, "owner": self.owner, "refresh": refresh}, method="GET")
|
|
91
|
+
return self.connection
|
|
92
|
+
|
|
93
|
+
def get_connection_info(self, refresh: bool = False) -> Dict[str, Any]:
|
|
94
|
+
"""The project's name and settings, and the caller's IP and location as the server sees them."""
|
|
95
|
+
conn = self._ensure_connection(refresh)
|
|
96
|
+
info = {
|
|
97
|
+
"project_id": self.project_id,
|
|
98
|
+
"user_ip": conn.get("ip"),
|
|
99
|
+
"user_agent": conn.get("user_agent"),
|
|
100
|
+
"user_location": conn.get("locale"),
|
|
101
|
+
"service_name": conn.get("service_name"),
|
|
102
|
+
"version": self.version,
|
|
103
|
+
"ai_agent": conn.get("ai_agent"),
|
|
104
|
+
"conf": conn.get("opt"),
|
|
105
|
+
}
|
|
106
|
+
# Only with encryption on and a signed-in user: the encryption recovery code on the first
|
|
107
|
+
# call after it was created, then only a message (see _encryption_recovery_info).
|
|
108
|
+
recovery = self._encryption_recovery_info()
|
|
109
|
+
if recovery is not None:
|
|
110
|
+
info["encryption_recovery"] = recovery
|
|
111
|
+
return info
|
|
112
|
+
|
|
113
|
+
# ---- session --------------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def _user_pool(self) -> UserPool:
|
|
116
|
+
if self._pool is None:
|
|
117
|
+
admin, _ = self._requester.endpoints()
|
|
118
|
+
self._pool = UserPool(admin["userpool_id"], admin["userpool_client"], self._storage)
|
|
119
|
+
return self._pool
|
|
120
|
+
|
|
121
|
+
def _restore(self) -> None:
|
|
122
|
+
"""Once: sign back in from storage (refreshing the tokens when they expired)."""
|
|
123
|
+
with self._lock:
|
|
124
|
+
if self._restored:
|
|
125
|
+
return
|
|
126
|
+
self._restored = True
|
|
127
|
+
pool = self._user_pool()
|
|
128
|
+
username = pool.last_auth_user()
|
|
129
|
+
if not username:
|
|
130
|
+
return
|
|
131
|
+
session = pool.cached_session(username)
|
|
132
|
+
if session is None:
|
|
133
|
+
return
|
|
134
|
+
try:
|
|
135
|
+
if not session.is_valid():
|
|
136
|
+
if not session.refresh_token:
|
|
137
|
+
return
|
|
138
|
+
try:
|
|
139
|
+
session = pool.refresh(username, session.refresh_token)
|
|
140
|
+
# get_profile(refresh_token=True) right after this has nothing left to ask for
|
|
141
|
+
self._restore_refreshed_token = session.id_token.jwt_token
|
|
142
|
+
except CognitoError as err:
|
|
143
|
+
if err.code != "NetworkError":
|
|
144
|
+
raise
|
|
145
|
+
# The server never answered: that says nothing about the session, which is kept
|
|
146
|
+
# with its stored tokens. The next signed-in call refreshes again (NETWORK_ERROR
|
|
147
|
+
# while there is no network), as for a session that expires while running.
|
|
148
|
+
self._adopt_session(username, session)
|
|
149
|
+
if self._user.get("anonymous"):
|
|
150
|
+
# a temporary account restored from storage: check it still exists, and keep it alive
|
|
151
|
+
self._start_anonymous_keep_alive(beat_now=True)
|
|
152
|
+
except CognitoError as err:
|
|
153
|
+
if err.code != "NetworkError":
|
|
154
|
+
self._clear_session(local_only=True)
|
|
155
|
+
except SkapiError:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
def _adopt_session(self, username: str, session) -> Dict[str, Any]:
|
|
159
|
+
claims = session.id_token.payload
|
|
160
|
+
if claims.get("custom:service") != self.service:
|
|
161
|
+
self._clear_session(local_only=True)
|
|
162
|
+
raise SkapiError("Invalid session.", "INVALID_REQUEST")
|
|
163
|
+
previous = self._cognito_username
|
|
164
|
+
if previous and previous != username:
|
|
165
|
+
# a new sign-in as someone else: nothing the previous user was handed carries over
|
|
166
|
+
self._private_access_key.clear()
|
|
167
|
+
self._my_unique_ids.clear()
|
|
168
|
+
if self._pool:
|
|
169
|
+
# the previous user's tokens leave the storage
|
|
170
|
+
self._stop_anonymous_keep_alive()
|
|
171
|
+
for key in ("idToken", "accessToken", "refreshToken", "clockDrift", "userData"):
|
|
172
|
+
self._pool.storage.remove_item(f"{self._pool.key_prefix}.{previous}.{key}")
|
|
173
|
+
self._session = session
|
|
174
|
+
self._cognito_username = username
|
|
175
|
+
self._user = parse_user_attributes(claims)
|
|
176
|
+
return self._user
|
|
177
|
+
|
|
178
|
+
def _clear_session(self, local_only: bool = True) -> None:
|
|
179
|
+
if getattr(self, "_rt", None) is not None:
|
|
180
|
+
self.close_realtime() # a signed-in connection does not outlive the session
|
|
181
|
+
self._stop_anonymous_keep_alive()
|
|
182
|
+
self._enc_clear()
|
|
183
|
+
self._pending_mfa = None
|
|
184
|
+
if self._cognito_username and self._pool:
|
|
185
|
+
self._pool.clear_cached_tokens(self._cognito_username)
|
|
186
|
+
with self._session_lock:
|
|
187
|
+
self._session = None
|
|
188
|
+
self._cognito_username = None
|
|
189
|
+
self._user = None
|
|
190
|
+
self._sign_outs += 1 # a refresh still running from before this point is not adopted
|
|
191
|
+
self._restore_refreshed_token = None
|
|
192
|
+
self._private_access_key.clear()
|
|
193
|
+
self._my_unique_ids.clear()
|
|
194
|
+
self._requester._start_key_history.clear()
|
|
195
|
+
|
|
196
|
+
def _signed_in(self) -> bool:
|
|
197
|
+
self._restore()
|
|
198
|
+
return bool(self._user and self._session)
|
|
199
|
+
|
|
200
|
+
def _refresh_session(self) -> None:
|
|
201
|
+
"""Forced token refresh. A network failure keeps the session; any other refusal ends it."""
|
|
202
|
+
with self._refresh_lock:
|
|
203
|
+
if not self._session:
|
|
204
|
+
raise SkapiError("User login is required.", "INVALID_REQUEST")
|
|
205
|
+
epoch, username = self._sign_outs, self._cognito_username
|
|
206
|
+
pool = self._user_pool()
|
|
207
|
+
try:
|
|
208
|
+
session = pool.refresh(username, self._session.refresh_token)
|
|
209
|
+
except CognitoError as err:
|
|
210
|
+
if self._sign_outs != epoch:
|
|
211
|
+
self._signed_out_meanwhile(pool, username)
|
|
212
|
+
if err.code == "NetworkError":
|
|
213
|
+
raise SkapiError("Network error", "NETWORK_ERROR", err) from None
|
|
214
|
+
self._clear_session()
|
|
215
|
+
raise SkapiError("User login is required.", "INVALID_REQUEST", err) from None
|
|
216
|
+
with self._session_lock:
|
|
217
|
+
if self._sign_outs != epoch:
|
|
218
|
+
self._signed_out_meanwhile(pool, username)
|
|
219
|
+
self._adopt_session(username, session)
|
|
220
|
+
|
|
221
|
+
def _signed_out_meanwhile(self, pool, username) -> None:
|
|
222
|
+
"""
|
|
223
|
+
logout() ran while a token refresh waited on the server. The refresh is not adopted, and the
|
|
224
|
+
tokens it wrote back to storage are removed again; a sign-in made after the logout keeps its
|
|
225
|
+
own tokens. Raises, as for any call made without a session.
|
|
226
|
+
"""
|
|
227
|
+
pool.clear_cached_tokens(username)
|
|
228
|
+
if self._session and self._cognito_username:
|
|
229
|
+
pool.cache_tokens(self._cognito_username, self._session)
|
|
230
|
+
raise SkapiError("User login is required.", "INVALID_REQUEST")
|
|
231
|
+
|
|
232
|
+
def _fresh_id_token(self) -> str:
|
|
233
|
+
self._restore()
|
|
234
|
+
if not self._session:
|
|
235
|
+
self._clear_session()
|
|
236
|
+
raise SkapiError("User login is required.", "INVALID_REQUEST")
|
|
237
|
+
session = self._session
|
|
238
|
+
if (session.id_token.expiration or 0) < time.time() + TOKEN_REFRESH_SKEW_SECONDS:
|
|
239
|
+
with self._refresh_lock:
|
|
240
|
+
# another thread may have refreshed (or ended the session) while this one waited
|
|
241
|
+
session = self._session
|
|
242
|
+
if not session:
|
|
243
|
+
raise SkapiError("User login is required.", "INVALID_REQUEST")
|
|
244
|
+
if (session.id_token.expiration or 0) < time.time() + TOKEN_REFRESH_SKEW_SECONDS:
|
|
245
|
+
self._refresh_session()
|
|
246
|
+
session = self._session
|
|
247
|
+
return session.id_token.jwt_token
|
|
248
|
+
|
|
249
|
+
def _access_token(self) -> str:
|
|
250
|
+
self._fresh_id_token()
|
|
251
|
+
return self._session.access_token.jwt_token
|
|
252
|
+
|
|
253
|
+
def _call(self, path: str, data: Any = None, *, auth: bool = False, method: str = "POST",
|
|
254
|
+
fetch_options: Optional[dict] = None, ignore_service: bool = False) -> Any:
|
|
255
|
+
self._ensure_connection()
|
|
256
|
+
token = self._fresh_id_token() if auth else None
|
|
257
|
+
return self._requester.request(path, data, auth=auth, method=method, token=token,
|
|
258
|
+
fetch_options=fetch_options, ignore_service=ignore_service)
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def user(self) -> Optional[Dict[str, Any]]:
|
|
262
|
+
"""The signed-in user's profile (a copy), or None."""
|
|
263
|
+
self._restore()
|
|
264
|
+
return copy.deepcopy(self._user) if self._user else None
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def session(self):
|
|
268
|
+
"""The signed-in session's tokens: .id_token.jwt_token, .access_token.jwt_token, .refresh_token."""
|
|
269
|
+
self._restore()
|
|
270
|
+
return self._session
|
skapi/errors.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""SkapiError: every error skapi-py raises carries a code and a message, the same as skapi-js."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SkapiError(Exception):
|
|
9
|
+
"""
|
|
10
|
+
code: a short name such as 'INVALID_PARAMETER', 'INVALID_REQUEST', 'NOT_EXISTS',
|
|
11
|
+
'INCORRECT_USERNAME_OR_PASSWORD' or 'MFA_REQUIRED', the same codes skapi-js uses.
|
|
12
|
+
message: what went wrong, in plain words.
|
|
13
|
+
cause: the underlying error, when there is one.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, message: str, code: str = "ERROR", cause: Optional[Any] = None):
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.message = message
|
|
19
|
+
self.code = code
|
|
20
|
+
self.cause = cause
|
|
21
|
+
|
|
22
|
+
def __str__(self) -> str:
|
|
23
|
+
return f"{self.code}: {self.message}"
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return f"SkapiError(code={self.code!r}, message={self.message!r})"
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: skapi
|
|
3
|
+
Version: 2.4.0
|
|
4
|
+
Summary: Serverless backend for Python: sign-in, users and a database, with the Skapi API.
|
|
5
|
+
Author: broadway Inc.
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://www.skapi.com
|
|
8
|
+
Project-URL: Documentation, https://docs.skapi.com
|
|
9
|
+
Keywords: backend,skapi,api,serverless,database,authentication
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Provides-Extra: encryption
|
|
19
|
+
Requires-Dist: cryptography>=3.4; extra == "encryption"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# skapi
|
|
23
|
+
|
|
24
|
+
The [Skapi](https://www.skapi.com) backend for Python: sign users in, keep their sessions, and read and write your project's database. Same API as [skapi-js](https://www.npmjs.com/package/skapi-js), in Python style.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install skapi
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from skapi import Skapi
|
|
32
|
+
|
|
33
|
+
skapi = Skapi("<Project ID>") # from your project's Settings page on skapi.com
|
|
34
|
+
|
|
35
|
+
skapi.login("user@example.com", "password")
|
|
36
|
+
record = skapi.post_record({"title": "Hello"}, {"table": {"name": "posts", "access_group": "public"}})
|
|
37
|
+
posts = skapi.get_records({"table": {"name": "posts", "access_group": "public"}})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- No dependencies: Python 3.9 or later, standard library only.
|
|
41
|
+
- Sign-in uses the same SRP exchange as skapi-js: the password never leaves your machine.
|
|
42
|
+
- Two-step login with an authenticator app, file attachments, and every query form of skapi-js.
|
|
43
|
+
- Realtime messages between users, in groups or one to one.
|
|
44
|
+
- Optional encryption of private records before upload, compatible with skapi-js: `pip install "skapi[encryption]"`.
|
|
45
|
+
|
|
46
|
+
Documentation: https://py.skapi.com
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
skapi/__init__.py,sha256=nDPDW7ayA0lUPeA1JJ2W5aQCqShUZPSgwiuWahNp9oA,472
|
|
2
|
+
skapi/_cognito.py,sha256=x_VHPaggnlcaczq37HIh2Fc6RcGJKxhCknvlduw4oy8,16594
|
|
3
|
+
skapi/_database.py,sha256=h429_2_c89dtqvmKupF8ovG_kK9dqUottyUaGtJayj8,74459
|
|
4
|
+
skapi/_encryption.py,sha256=dNktgtRclY-561o8P_BT4PLpFf7voqC2_JGeJOKW8dc,71726
|
|
5
|
+
skapi/_forward.py,sha256=JJbuSn8lkcfUP1TvF4_w3KawbpsMN_0RWM2_Q6Yjvns,26060
|
|
6
|
+
skapi/_http.py,sha256=_zEEVcgXShCqAmRrnCSydSVHEU6hWIlUbMDAntGa05A,17980
|
|
7
|
+
skapi/_md5.py,sha256=-YtMZA4X1Lzq1hHGo-MxjMlfexR3dMXjYwDaE8k5-nw,3840
|
|
8
|
+
skapi/_project.py,sha256=OqVsh8o6RmUzSO-kol0dNoYOILxycMMzJcJl0fyw_TE,2752
|
|
9
|
+
skapi/_realtime.py,sha256=O1K05oCxN19iQZmhSInR2am7xEaWtC2eWKf-y07OJXM,25310
|
|
10
|
+
skapi/_social.py,sha256=7jk2eYd4ChtK_dUGVZAuM6LdF-cTJGnBuj7UGZi2HpY,16694
|
|
11
|
+
skapi/_srp.py,sha256=_F0SEeoPZFZrs6mH4y7IxbgcYfaZVjd24J0mgC6xjaE,5354
|
|
12
|
+
skapi/_user.py,sha256=uif0V26anNvgvLzyzLnSI-fY2AMxAixyQdICkR8oiVA,45617
|
|
13
|
+
skapi/_ws.py,sha256=X1N0lcVsbQjwUpVz85HcXGP7QBDJffNMuoU_szZVoQQ,7151
|
|
14
|
+
skapi/client.py,sha256=Gc2mkVi90fYRqPCeftfvXcQ2-AP6pgSzgSil9CEFda4,13260
|
|
15
|
+
skapi/errors.py,sha256=CxYTMVsrJHcahlz0y2KjCvu4cGbwahyKqTmE3DJgoPM,874
|
|
16
|
+
skapi-2.4.0.dist-info/licenses/LICENSE,sha256=rK1WdcFr929rFadiAuI-YN9pQ5OOu-JIV9btHG8iI3o,11345
|
|
17
|
+
skapi-2.4.0.dist-info/METADATA,sha256=Nv65HgQFw-n7qIIO-oyyUYhNq1zMy1unv1PQSQY8SlA,1842
|
|
18
|
+
skapi-2.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
19
|
+
skapi-2.4.0.dist-info/top_level.txt,sha256=u8dWj6qHd4ZW9eXpJxaksg1EB6gdFGVWasUMXln5k88,6
|
|
20
|
+
skapi-2.4.0.dist-info/RECORD,,
|