prettynb-web 0.1.0__tar.gz

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.
Files changed (121) hide show
  1. prettynb_web-0.1.0/LICENSE +22 -0
  2. prettynb_web-0.1.0/MANIFEST.in +5 -0
  3. prettynb_web-0.1.0/PKG-INFO +35 -0
  4. prettynb_web-0.1.0/README.md +10 -0
  5. prettynb_web-0.1.0/__init__.py +1 -0
  6. prettynb_web-0.1.0/api/atomic_io.py +78 -0
  7. prettynb_web-0.1.0/api/auth_api.py +267 -0
  8. prettynb_web-0.1.0/api/catalog.py +517 -0
  9. prettynb_web-0.1.0/api/forms.py +31 -0
  10. prettynb_web-0.1.0/api/health.py +16 -0
  11. prettynb_web-0.1.0/api/layout_api.py +169 -0
  12. prettynb_web-0.1.0/api/notebooks.py +130 -0
  13. prettynb_web-0.1.0/api/operation_logs.py +88 -0
  14. prettynb_web-0.1.0/api/permissions.py +136 -0
  15. prettynb_web-0.1.0/api/png.py +93 -0
  16. prettynb_web-0.1.0/api/process_lock.py +50 -0
  17. prettynb_web-0.1.0/api/public_index.py +241 -0
  18. prettynb_web-0.1.0/api/public_navigation.py +155 -0
  19. prettynb_web-0.1.0/api/publish_api.py +178 -0
  20. prettynb_web-0.1.0/api/publishing_api.py +159 -0
  21. prettynb_web-0.1.0/api/schema.py +164 -0
  22. prettynb_web-0.1.0/api/search_api.py +35 -0
  23. prettynb_web-0.1.0/api/site_api.py +104 -0
  24. prettynb_web-0.1.0/assets.py +99 -0
  25. prettynb_web-0.1.0/expose_web.py +161 -0
  26. prettynb_web-0.1.0/install_assets.py +50 -0
  27. prettynb_web-0.1.0/launch.py +75 -0
  28. prettynb_web-0.1.0/main.py +48 -0
  29. prettynb_web-0.1.0/native_assets.py +97 -0
  30. prettynb_web-0.1.0/native_publishing.py +133 -0
  31. prettynb_web-0.1.0/native_requests.py +254 -0
  32. prettynb_web-0.1.0/native_routes.py +246 -0
  33. prettynb_web-0.1.0/openapi.json +1836 -0
  34. prettynb_web-0.1.0/prettynb_web.egg-info/PKG-INFO +35 -0
  35. prettynb_web-0.1.0/prettynb_web.egg-info/SOURCES.txt +193 -0
  36. prettynb_web-0.1.0/prettynb_web.egg-info/dependency_links.txt +1 -0
  37. prettynb_web-0.1.0/prettynb_web.egg-info/entry_points.txt +2 -0
  38. prettynb_web-0.1.0/prettynb_web.egg-info/requires.txt +13 -0
  39. prettynb_web-0.1.0/prettynb_web.egg-info/top_level.txt +1 -0
  40. prettynb_web-0.1.0/pyproject.toml +46 -0
  41. prettynb_web-0.1.0/setup.cfg +4 -0
  42. prettynb_web-0.1.0/static/THIRD_PARTY_NOTICES.md +12 -0
  43. prettynb_web-0.1.0/static/asset-manifest.json +37 -0
  44. prettynb_web-0.1.0/static/css/appearance-preferences.css +58 -0
  45. prettynb_web-0.1.0/static/css/site.css +177 -0
  46. prettynb_web-0.1.0/static/css/themes/dark.css +31 -0
  47. prettynb_web-0.1.0/static/css/themes/forest.css +31 -0
  48. prettynb_web-0.1.0/static/css/themes/midnight.css +31 -0
  49. prettynb_web-0.1.0/static/css/themes/outside.css +35 -0
  50. prettynb_web-0.1.0/static/css/themes/paper.css +31 -0
  51. prettynb_web-0.1.0/static/css/themes/slate.css +31 -0
  52. prettynb_web-0.1.0/static/icons/appearance.svg +16 -0
  53. prettynb_web-0.1.0/static/js/appearance-preferences.js +115 -0
  54. prettynb_web-0.1.0/static/js/appearance.js +26 -0
  55. prettynb_web-0.1.0/static/js/code-tools.js +162 -0
  56. prettynb_web-0.1.0/static/js/diagram-loader.js +156 -0
  57. prettynb_web-0.1.0/static/js/notebook-navigation.js +22 -0
  58. prettynb_web-0.1.0/static/js/site-navigation.js +24 -0
  59. prettynb_web-0.1.0/static/vendor/highlight.js/10.7.2/LICENSE +29 -0
  60. prettynb_web-0.1.0/static/vendor/highlight.js/10.7.2/default.min.css +1 -0
  61. prettynb_web-0.1.0/static/vendor/highlight.js/10.7.2/highlight.min.js +1358 -0
  62. prettynb_web-0.1.0/static/vendor/highlight.js/10.7.2/xt256.min.css +1 -0
  63. prettynb_web-0.1.0/static/vendor/mermaid/12.0.0/LICENSE +21 -0
  64. prettynb_web-0.1.0/static/vendor/mermaid/12.0.0/mermaid.min.js +4376 -0
  65. prettynb_web-0.1.0/templates/home/appearance.html +87 -0
  66. prettynb_web-0.1.0/templates/home/contact.html +18 -0
  67. prettynb_web-0.1.0/templates/home/home.html +9 -0
  68. prettynb_web-0.1.0/templates/home/notebook.html +8 -0
  69. prettynb_web-0.1.0/templates/home/search.html +45 -0
  70. prettynb_web-0.1.0/templates/shared/404.html +15 -0
  71. prettynb_web-0.1.0/templates/shared/layout.html +47 -0
  72. prettynb_web-0.1.0/templates/shared/navbar.html +35 -0
  73. prettynb_web-0.1.0/templates/shared/notebook-index.html +21 -0
  74. prettynb_web-0.1.0/templates/shared/published.html +53 -0
  75. prettynb_web-0.1.0/tests/test_appearance.py +147 -0
  76. prettynb_web-0.1.0/tests/test_assets.py +163 -0
  77. prettynb_web-0.1.0/tests/test_atomic_io.py +186 -0
  78. prettynb_web-0.1.0/tests/test_auth_api.py +441 -0
  79. prettynb_web-0.1.0/tests/test_backup_recovery.py +101 -0
  80. prettynb_web-0.1.0/tests/test_catalog.py +265 -0
  81. prettynb_web-0.1.0/tests/test_checked_publishing.py +188 -0
  82. prettynb_web-0.1.0/tests/test_code_tools.py +62 -0
  83. prettynb_web-0.1.0/tests/test_deployment.py +143 -0
  84. prettynb_web-0.1.0/tests/test_diagrams.py +70 -0
  85. prettynb_web-0.1.0/tests/test_failure_paths.py +148 -0
  86. prettynb_web-0.1.0/tests/test_framework_factory.py +62 -0
  87. prettynb_web-0.1.0/tests/test_framework_pilot.py +54 -0
  88. prettynb_web-0.1.0/tests/test_icons.py +33 -0
  89. prettynb_web-0.1.0/tests/test_layout_and_views.py +355 -0
  90. prettynb_web-0.1.0/tests/test_namespace.py +19 -0
  91. prettynb_web-0.1.0/tests/test_native_publishing.py +149 -0
  92. prettynb_web-0.1.0/tests/test_native_routes.py +91 -0
  93. prettynb_web-0.1.0/tests/test_native_runtime.py +102 -0
  94. prettynb_web-0.1.0/tests/test_notebook_ownership.py +165 -0
  95. prettynb_web-0.1.0/tests/test_operation_logs.py +108 -0
  96. prettynb_web-0.1.0/tests/test_permissions.py +112 -0
  97. prettynb_web-0.1.0/tests/test_presentation.py +79 -0
  98. prettynb_web-0.1.0/tests/test_process_lock.py +40 -0
  99. prettynb_web-0.1.0/tests/test_public_navigation.py +184 -0
  100. prettynb_web-0.1.0/tests/test_public_search.py +183 -0
  101. prettynb_web-0.1.0/tests/test_publication_lifecycle.py +123 -0
  102. prettynb_web-0.1.0/tests/test_publish_api.py +228 -0
  103. prettynb_web-0.1.0/tests/test_publishing_client.py +126 -0
  104. prettynb_web-0.1.0/tests/test_remote_lifecycle_client.py +192 -0
  105. prettynb_web-0.1.0/tests/test_responsive_navigation.py +43 -0
  106. prettynb_web-0.1.0/tests/test_routes.py +179 -0
  107. prettynb_web-0.1.0/tests/test_schema.py +240 -0
  108. prettynb_web-0.1.0/tests/test_site_identity.py +243 -0
  109. prettynb_web-0.1.0/tests/test_worker_deployment.py +142 -0
  110. prettynb_web-0.1.0/views/forms.py +79 -0
  111. prettynb_web-0.1.0/views/home.py +201 -0
  112. prettynb_web-0.1.0/views/navigation.py +23 -0
  113. prettynb_web-0.1.0/views/search.py +37 -0
  114. prettynb_web-0.1.0/web-settings.json +22 -0
  115. prettynb_web-0.1.0/web_config.py +62 -0
  116. prettynb_web-0.1.0/web_errors.py +7 -0
  117. prettynb_web-0.1.0/web_hosts.py +30 -0
  118. prettynb_web-0.1.0/web_reference.py +33 -0
  119. prettynb_web-0.1.0/web_routing.py +57 -0
  120. prettynb_web-0.1.0/web_templates.py +27 -0
  121. prettynb_web-0.1.0/worker.py +49 -0
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 prettynb
4
+ Copyright (c) 2026 wispsy
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ include openapi.json web-settings.json
2
+ recursive-include templates *.html
3
+ graft static
4
+ prune static/imgs
5
+ global-exclude .gitignore
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: prettynb-web
3
+ Version: 0.1.0
4
+ Summary: Installable web publisher for Pretty Notebook
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/wispsy/prettynb
7
+ Project-URL: Issues, https://github.com/wispsy/prettynb/issues
8
+ Requires-Python: >=3.14
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: prettynb<0.16,>=0.15
12
+ Requires-Dist: aiofiles==25.1.0
13
+ Requires-Dist: backpack-store==0.2.0
14
+ Requires-Dist: bcrypt==3.2.0
15
+ Requires-Dist: expose-api==0.2.0
16
+ Requires-Dist: Jinja2==3.1.6
17
+ Requires-Dist: passlib==1.7.4
18
+ Requires-Dist: pydantic==2.13.4
19
+ Requires-Dist: PyJWT==2.15.1
20
+ Requires-Dist: python-decouple==3.8
21
+ Requires-Dist: tortoise-orm==1.1.7
22
+ Requires-Dist: serve-asgi==1.0.0
23
+ Requires-Dist: serve-runner==1.0.0
24
+ Dynamic: license-file
25
+
26
+ # Pretty Notebook web publisher
27
+
28
+ Install with `python -m pip install prettynb-web` or
29
+ `python -m pip install 'prettynb[web]'`. Both install this publisher and
30
+ a compatible Pretty Notebook client.
31
+
32
+ Configure a private state directory and deployment environment before running
33
+ `prettynb-web --workers 4 --port 8000`. The listener binds to loopback. See the
34
+ [deployment guide](https://github.com/wispsy/prettynb/blob/main/docs/web.md)
35
+ for environment settings, the supported reverse proxy, and backup and restore.
@@ -0,0 +1,10 @@
1
+ # Pretty Notebook web publisher
2
+
3
+ Install with `python -m pip install prettynb-web` or
4
+ `python -m pip install 'prettynb[web]'`. Both install this publisher and
5
+ a compatible Pretty Notebook client.
6
+
7
+ Configure a private state directory and deployment environment before running
8
+ `prettynb-web --workers 4 --port 8000`. The listener binds to loopback. See the
9
+ [deployment guide](https://github.com/wispsy/prettynb/blob/main/docs/web.md)
10
+ for environment settings, the supported reverse proxy, and backup and restore.
@@ -0,0 +1 @@
1
+ """The installable Pretty Notebook web publisher."""
@@ -0,0 +1,78 @@
1
+ """Atomic replacement for the web app's small text files."""
2
+
3
+ from os import fchmod, fdopen, replace, fsync, link
4
+ from pathlib import Path
5
+ from stat import S_IMODE
6
+ from tempfile import mkstemp
7
+
8
+ import aiofiles
9
+
10
+
11
+ def create_text_once(target: Path, content: str) -> bool:
12
+ """Publish complete private defaults atomically; an existing target wins."""
13
+ descriptor, name = mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)
14
+ temporary = Path(name)
15
+ try:
16
+ with fdopen(descriptor, "w", encoding="utf-8") as pending:
17
+ pending.write(content)
18
+ pending.flush()
19
+ fsync(pending.fileno())
20
+ try:
21
+ link(temporary, target)
22
+ except FileExistsError:
23
+ return False
24
+ return True
25
+ finally:
26
+ temporary.unlink(missing_ok=True)
27
+
28
+
29
+ async def atomic_write_text(target: Path, content: str) -> None:
30
+ """Write a sibling file, then publish it with one filesystem replacement.
31
+
32
+ Concurrent writers each use a separate temporary file. The last successful
33
+ replacement wins; readers see one complete version of the target.
34
+ """
35
+ try:
36
+ existing_mode = S_IMODE(target.stat().st_mode)
37
+ except FileNotFoundError:
38
+ existing_mode = None
39
+
40
+ descriptor, name = mkstemp(
41
+ prefix=f".{target.name}.", suffix=".tmp", dir=target.parent
42
+ )
43
+ temporary = Path(name)
44
+
45
+ try:
46
+ with fdopen(descriptor, "wb") as pending:
47
+ if existing_mode is not None:
48
+ fchmod(pending.fileno(), existing_mode)
49
+
50
+ async with aiofiles.open(temporary, "w", encoding="utf-8") as output:
51
+ await output.write(content)
52
+ replace(temporary, target)
53
+ finally:
54
+ temporary.unlink(missing_ok=True)
55
+
56
+
57
+ async def atomic_write_bytes(target: Path, content: bytes) -> None:
58
+ """Atomically replace a small binary file while preserving its mode."""
59
+ try:
60
+ existing_mode = S_IMODE(target.stat().st_mode)
61
+ except FileNotFoundError:
62
+ existing_mode = None
63
+
64
+ descriptor, name = mkstemp(
65
+ prefix=f".{target.name}.", suffix=".tmp", dir=target.parent
66
+ )
67
+ temporary = Path(name)
68
+
69
+ try:
70
+ with fdopen(descriptor, "wb") as pending:
71
+ if existing_mode is not None:
72
+ fchmod(pending.fileno(), existing_mode)
73
+
74
+ async with aiofiles.open(temporary, "wb") as output:
75
+ await output.write(content)
76
+ replace(temporary, target)
77
+ finally:
78
+ temporary.unlink(missing_ok=True)
@@ -0,0 +1,267 @@
1
+ """Bearer authentication and single-use owner bootstrap."""
2
+
3
+ from prettynb_web.native_requests import ResponseMetadata
4
+ from expose_api import HTTPException
5
+ from prettynb_web.native_requests import ApplicationRequest as Request
6
+
7
+ import secrets
8
+ from datetime import UTC, datetime, timedelta
9
+
10
+ import jwt
11
+ from decouple import config
12
+ from passlib.hash import bcrypt
13
+ from pydantic import BaseModel, Field, field_validator
14
+ from tortoise import connections, fields
15
+ from tortoise.contrib.pydantic import pydantic_model_creator
16
+ from tortoise.models import Model
17
+ from tortoise.transactions import in_transaction
18
+
19
+
20
+ JWT_SECRET = config("JWT_SECRET")
21
+ JWT_ALGO = config("JWT_ALGO", default="HS256")
22
+ TOKEN_LIFETIME = timedelta(days=30)
23
+ BOOTSTRAP_HEADER = "X-PRETTYNB-Bootstrap-Token"
24
+ MIN_SECRET_BYTES = 32
25
+ MIN_PASSWORD_CHARACTERS = 12
26
+ MAX_PASSWORD_BYTES = 72
27
+
28
+
29
+ def validate_jwt_settings(secret: str, algorithm: str) -> None:
30
+ """Reject weak or unexpectedly configured signing settings at startup."""
31
+ if algorithm != "HS256":
32
+ raise RuntimeError("JWT_ALGO must be HS256")
33
+ if len(secret.encode("utf-8")) < MIN_SECRET_BYTES:
34
+ raise RuntimeError("JWT_SECRET must contain at least 32 bytes")
35
+
36
+
37
+ validate_jwt_settings(JWT_SECRET, JWT_ALGO)
38
+
39
+
40
+ class User(Model):
41
+ id = fields.IntField(primary_key=True)
42
+ username = fields.CharField(max_length=50, unique=True)
43
+ password_hash = fields.CharField(max_length=128)
44
+ tok_uuid = fields.TextField(default=lambda: secrets.token_urlsafe(32))
45
+
46
+ def verify_password(self, password: str) -> bool:
47
+ return bcrypt.verify(password, self.password_hash)
48
+
49
+
50
+ class PasswordInput(BaseModel):
51
+ password_hash: str = Field(min_length=MIN_PASSWORD_CHARACTERS, max_length=128)
52
+
53
+ @field_validator("password_hash")
54
+ @classmethod
55
+ def supported_bcrypt_length(cls, value: str) -> str:
56
+ if len(value.encode("utf-8")) > MAX_PASSWORD_BYTES:
57
+ raise ValueError("Password may contain at most 72 UTF-8 bytes")
58
+ return value
59
+
60
+
61
+ class UserInput(PasswordInput):
62
+ username: str = Field(min_length=1, max_length=50)
63
+
64
+ @field_validator("username")
65
+ @classmethod
66
+ def nonblank_username(cls, value: str) -> str:
67
+ value = value.strip()
68
+ if not value:
69
+ raise ValueError("Username cannot be blank")
70
+ return value
71
+
72
+
73
+ User_Pydantic = pydantic_model_creator(
74
+ User,
75
+ name="User",
76
+ exclude=("password_hash", "tok_uuid"),
77
+ )
78
+
79
+
80
+ async def get_optional_user(
81
+ token: str | None = None,
82
+ ):
83
+ """Authenticate a supplied token while allowing a genuinely absent token."""
84
+ if token is None:
85
+ return None
86
+ return await get_current_user(token)
87
+
88
+
89
+ async def _has_ever_created_user() -> bool:
90
+ """Keep anonymous bootstrap closed after the first user is deleted."""
91
+ if await User.all().exists():
92
+ return True
93
+
94
+ connection = connections.get("default")
95
+ rows = await connection.execute_query_dict(
96
+ "SELECT seq FROM sqlite_sequence WHERE name = ? LIMIT 1",
97
+ [User._meta.db_table],
98
+ )
99
+ return bool(rows)
100
+
101
+
102
+ def _require_bootstrap_token(request: Request) -> None:
103
+ expected = config("PRETTYNB_BOOTSTRAP_TOKEN", default="")
104
+ supplied = request.headers.get(BOOTSTRAP_HEADER, "")
105
+ configured_safely = len(expected.encode("utf-8")) >= MIN_SECRET_BYTES
106
+ if (
107
+ not configured_safely
108
+ or not supplied
109
+ or not secrets.compare_digest(supplied, expected)
110
+ ):
111
+ raise HTTPException(
112
+ status=403,
113
+ detail="A valid bootstrap token is required.",
114
+ )
115
+
116
+
117
+ async def _save_user(user: UserInput, *, role='reader') -> User_Pydantic:
118
+ user_obj = User(
119
+ username=user.username,
120
+ password_hash=bcrypt.hash(user.password_hash),
121
+ )
122
+ async with in_transaction() as connection:
123
+ await user_obj.save(using_db=connection)
124
+ await connection.execute_query('INSERT INTO prettynb_roles VALUES (?,?)', [user_obj.id, role])
125
+ if role == 'owner':
126
+ await connection.execute_query("UPDATE prettynb_notebooks SET owner_id=? WHERE slot='default' AND owner_id IS NULL", [user_obj.id])
127
+ return await User_Pydantic.from_tortoise_orm(user_obj)
128
+
129
+
130
+ async def create_user(
131
+ user: UserInput,
132
+ request: Request,
133
+ curr_user: User_Pydantic | None,
134
+ ):
135
+ """Allow one secret-authorized owner claim, then owner-created accounts."""
136
+ if curr_user is None:
137
+ async with request.app.state.bootstrap_lock:
138
+ if await _has_ever_created_user():
139
+ raise HTTPException(
140
+ status=401,
141
+ detail="Cannot access.",
142
+ )
143
+ _require_bootstrap_token(request)
144
+ return await _save_user(user, role='owner')
145
+
146
+ if curr_user.role != 'owner' or 'admin' not in curr_user.scopes:
147
+ raise HTTPException(
148
+ status=401,
149
+ detail="Not allowed.",
150
+ )
151
+
152
+ return await _save_user(user)
153
+
154
+
155
+ def _password_supported(password: str) -> bool:
156
+ byte_length = len(password.encode("utf-8"))
157
+ return (
158
+ MIN_PASSWORD_CHARACTERS <= len(password) and byte_length <= MAX_PASSWORD_BYTES
159
+ )
160
+
161
+
162
+ async def authenticate_user(username: str, password: str):
163
+ if not _password_supported(password):
164
+ return False
165
+ user = await User.filter(username=username.strip()).first()
166
+ if not user or not user.verify_password(password=password):
167
+ return False
168
+ return user
169
+
170
+
171
+ async def _generate_token(user: User) -> str:
172
+ now = datetime.now(UTC)
173
+ token_id = secrets.token_urlsafe(32)
174
+ user.tok_uuid = token_id
175
+ await user.save(update_fields=["tok_uuid"])
176
+
177
+ payload = {
178
+ "sub": str(user.id),
179
+ "username": user.username,
180
+ "tok_uuid": token_id,
181
+ "iat": now,
182
+ "exp": now + TOKEN_LIFETIME,
183
+ }
184
+ return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGO)
185
+
186
+
187
+ async def generate_token(
188
+ response: ResponseMetadata,
189
+ form_data,
190
+ ):
191
+ user = await authenticate_user(
192
+ username=form_data.username,
193
+ password=form_data.password,
194
+ )
195
+ if not user:
196
+ raise HTTPException(
197
+ status=401,
198
+ detail="Invalid username or password",
199
+ )
200
+
201
+ token = await _generate_token(user)
202
+ response.headers["Cache-Control"] = "no-store"
203
+ response.headers["Pragma"] = "no-cache"
204
+ return {"access_token": token, "token_type": "bearer"}
205
+
206
+
207
+ def unauthorized(detail: str) -> HTTPException:
208
+ return HTTPException(
209
+ status=401,
210
+ detail=detail,
211
+ headers={"WWW-Authenticate": "Bearer"},
212
+ )
213
+
214
+
215
+ async def get_current_user(token: str):
216
+ from .permissions import authenticate_credential, principal_for
217
+ if token.startswith('prettynb_'):
218
+ return await authenticate_credential(token)
219
+ try:
220
+ payload = jwt.decode(
221
+ token,
222
+ JWT_SECRET,
223
+ algorithms=[JWT_ALGO],
224
+ options={"require": ["sub", "tok_uuid", "iat", "exp"]},
225
+ )
226
+ except jwt.ExpiredSignatureError as exc:
227
+ raise unauthorized("Token expired") from exc
228
+ except jwt.InvalidTokenError as exc:
229
+ raise unauthorized("Could not validate credentials") from exc
230
+
231
+ try:
232
+ user_id = int(payload["sub"])
233
+ token_id = payload["tok_uuid"]
234
+ except (KeyError, TypeError, ValueError) as exc:
235
+ raise unauthorized("Could not validate credentials") from exc
236
+
237
+ user = await User.get_or_none(id=user_id)
238
+ if user is None or not isinstance(token_id, str):
239
+ raise unauthorized("Could not validate credentials")
240
+ if not secrets.compare_digest(token_id, user.tok_uuid):
241
+ raise unauthorized("Token revoked or superseded")
242
+
243
+ return await principal_for(user)
244
+
245
+
246
+ async def get_user(user: User_Pydantic):
247
+ return {"id": user.id, "username": user.username}
248
+
249
+
250
+ async def reset_password(
251
+ password: PasswordInput,
252
+ user: User_Pydantic,
253
+ ):
254
+ from .permissions import authorize
255
+ orm_user = await User.get_or_none(id=user.id)
256
+ if orm_user is None:
257
+ raise unauthorized("Could not validate credentials")
258
+ await authorize(user, 'account')
259
+
260
+ orm_user.password_hash = bcrypt.hash(password.password_hash)
261
+ orm_user.tok_uuid = secrets.token_urlsafe(32)
262
+ await orm_user.save(update_fields=["password_hash", "tok_uuid"])
263
+ return await User_Pydantic.from_tortoise_orm(orm_user)
264
+
265
+
266
+ async def api_index(user: User_Pydantic):
267
+ return {"authenticated": True, "username": user.username}