cista 1.2.1__py3-none-any.whl → 1.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.
Files changed (79) hide show
  1. cista/__main__.py +7 -5
  2. cista/_version.py +1 -1
  3. cista/api.py +39 -10
  4. cista/app.py +32 -10
  5. cista/auth.py +262 -58
  6. cista/config.py +9 -1
  7. cista/frontend-build/assets/icons-DMD182WZ.js +1 -0
  8. cista/frontend-build/assets/index-D4WrmH4f.js +32 -0
  9. cista/frontend-build/assets/index-DQ2iYrs-.css +1 -0
  10. cista/{wwwroot → frontend-build}/index.html +5 -5
  11. cista/preview.py +71 -41
  12. cista/sso.py +324 -0
  13. cista/util/apphelpers.py +5 -2
  14. cista/watching.py +2 -2
  15. {cista-1.2.1.dist-info → cista-1.4.0.dist-info}/METADATA +6 -2
  16. cista-1.4.0.dist-info/RECORD +32 -0
  17. {cista-1.2.1.dist-info → cista-1.4.0.dist-info}/WHEEL +1 -1
  18. cista/wwwroot/assets/add-file-8c95935e.js +0 -1
  19. cista/wwwroot/assets/add-folder-86d38756.js +0 -1
  20. cista/wwwroot/assets/arrow-75fe0244.js +0 -1
  21. cista/wwwroot/assets/arrows-h-7cc7ed45.js +0 -1
  22. cista/wwwroot/assets/arrows-v-6ba20f93.js +0 -1
  23. cista/wwwroot/assets/check-2847ad21.js +0 -1
  24. cista/wwwroot/assets/code-a7719923.js +0 -1
  25. cista/wwwroot/assets/copy-3449d27d.js +0 -1
  26. cista/wwwroot/assets/create-file-a1cd75fd.js +0 -1
  27. cista/wwwroot/assets/create-folder-59db9ded.js +0 -1
  28. cista/wwwroot/assets/cross-38ada808.js +0 -1
  29. cista/wwwroot/assets/disk-39a6808b.js +0 -1
  30. cista/wwwroot/assets/download-dfa3cb2c.js +0 -1
  31. cista/wwwroot/assets/exclamation-1b2064ee.js +0 -1
  32. cista/wwwroot/assets/eye-8ad3b932.js +0 -1
  33. cista/wwwroot/assets/find-7e0bf1e0.js +0 -1
  34. cista/wwwroot/assets/fullscreen-e21f0ea1.js +0 -1
  35. cista/wwwroot/assets/github-33a0fb51.js +0 -1
  36. cista/wwwroot/assets/index-1cae47bc.css +0 -1
  37. cista/wwwroot/assets/index-5b083aad.js +0 -28
  38. cista/wwwroot/assets/info-f30cd4b4.js +0 -1
  39. cista/wwwroot/assets/link-3a6a01b8.js +0 -1
  40. cista/wwwroot/assets/logo-a02885a3.js +0 -1
  41. cista/wwwroot/assets/loop-17dda54a.js +0 -1
  42. cista/wwwroot/assets/menu-e088a6cc.js +0 -1
  43. cista/wwwroot/assets/next-c83214f4.js +0 -1
  44. cista/wwwroot/assets/open-bdcf30c3.js +0 -1
  45. cista/wwwroot/assets/paste-b1ebeeae.js +0 -1
  46. cista/wwwroot/assets/pause-c44d983d.js +0 -1
  47. cista/wwwroot/assets/pencil-70ceb3cc.js +0 -1
  48. cista/wwwroot/assets/play-38e640b3.js +0 -1
  49. cista/wwwroot/assets/plus-d2e20553.js +0 -1
  50. cista/wwwroot/assets/previous-78dea9b8.js +0 -1
  51. cista/wwwroot/assets/reload-61c8cee7.js +0 -1
  52. cista/wwwroot/assets/rename-202f8bc5.js +0 -1
  53. cista/wwwroot/assets/scissors-9235051c.js +0 -1
  54. cista/wwwroot/assets/shuffle-fd56ec51.js +0 -1
  55. cista/wwwroot/assets/signin-494e0573.js +0 -1
  56. cista/wwwroot/assets/signout-4047ccde.js +0 -1
  57. cista/wwwroot/assets/skip-bb8e721d.js +0 -1
  58. cista/wwwroot/assets/spinner-8c3861ee.js +0 -1
  59. cista/wwwroot/assets/stop-d670a372.js +0 -1
  60. cista/wwwroot/assets/trash-6a339a1b.js +0 -1
  61. cista/wwwroot/assets/triangle-9358f5e4.js +0 -1
  62. cista/wwwroot/assets/unfullscreen-792a694f.js +0 -1
  63. cista/wwwroot/assets/up-arrow-f518550f.js +0 -1
  64. cista/wwwroot/assets/upload-cloud-5f1a71c5.js +0 -1
  65. cista/wwwroot/assets/user-2d17adce.js +0 -1
  66. cista/wwwroot/assets/user-cog-5cefd313.js +0 -1
  67. cista/wwwroot/assets/volume-high-151aaf83.js +0 -1
  68. cista/wwwroot/assets/volume-low-8ffa3894.js +0 -1
  69. cista/wwwroot/assets/volume-medium-7b38c87d.js +0 -1
  70. cista/wwwroot/assets/volume-mute-4e81ae44.js +0 -1
  71. cista/wwwroot/assets/window-cross-ce8f66c3.js +0 -1
  72. cista/wwwroot/assets/window-dec8f28e.js +0 -1
  73. cista/wwwroot/assets/wordwrap-4618846d.js +0 -1
  74. cista/wwwroot/assets/zoomin-d821154d.js +0 -1
  75. cista/wwwroot/assets/zoomout-faf726ac.js +0 -1
  76. cista-1.2.1.dist-info/RECORD +0 -86
  77. /cista/{wwwroot/assets/logo-97d1d7eb.svg → frontend-build/assets/logo-ctv8tVwU.svg} +0 -0
  78. /cista/{wwwroot → frontend-build}/robots.txt +0 -0
  79. {cista-1.2.1.dist-info → cista-1.4.0.dist-info}/entry_points.txt +0 -0
cista/__main__.py CHANGED
@@ -42,13 +42,17 @@ Options:
42
42
  --import-droppy Import Droppy config from ~/.droppy/config
43
43
  --dev Developer mode (reloads, friendlier crashes, more logs)
44
44
 
45
- Listen address, path and imported options are preserved in config, and only
46
- custom config dir and dev mode need to be specified on subsequent runs.
45
+ Listen address and path are preserved in config,
46
+ and only config dir and dev mode need to be specified on subsequent runs.
47
47
 
48
48
  User management:
49
49
  --user NAME Create or modify user
50
50
  --privileged Give the user full admin rights
51
51
  --password Reset password
52
+
53
+ Environment:
54
+ PASKIA_BACKEND_URL Paskia single sign-on (e.g. http://localhost:4401)
55
+ https://git.zi.fi/leovasanko/paskia
52
56
  """
53
57
 
54
58
  first_time_help = """\
@@ -107,6 +111,7 @@ def _main():
107
111
  f"Importing Droppy: First remove the existing configuration:\n rm {config.conffile}",
108
112
  )
109
113
  settings = droppy.readconf()
114
+ # Droppy's public flag is kept as-is (same name in our config)
110
115
  if path:
111
116
  settings["path"] = path
112
117
  elif not exists:
@@ -115,9 +120,6 @@ def _main():
115
120
  settings["listen"] = listen
116
121
  elif not exists:
117
122
  settings["listen"] = ":8000"
118
- if not exists and not import_droppy:
119
- # We have no users, so make it public
120
- settings["public"] = True
121
123
  operation = config.update_config(settings)
122
124
  sys.stderr.write(f"Config {operation}: {config.conffile}\n")
123
125
  # Prepare to serve
cista/_version.py CHANGED
@@ -1,2 +1,2 @@
1
1
  # This file is automatically generated by hatch build.
2
- __version__ = '1.2.1'
2
+ __version__ = '1.4.0'
cista/api.py CHANGED
@@ -3,9 +3,10 @@ import typing
3
3
  from secrets import token_bytes
4
4
 
5
5
  import msgspec
6
- from sanic import Blueprint
6
+ from sanic import Blueprint, json
7
+ from sanic.exceptions import BadRequest
7
8
 
8
- from cista import __version__, config, watching
9
+ from cista import __version__, auth, config, sso, watching
9
10
  from cista.fileio import FileServer
10
11
  from cista.protocol import ControlTypes, FileRange, StatusMsg
11
12
  from cista.util.apphelpers import asend, websocket_wrapper
@@ -15,12 +16,12 @@ fileserver = FileServer()
15
16
 
16
17
 
17
18
  @bp.before_server_start
18
- async def start_fileserver(app, _):
19
+ async def start_fileserver(app):
19
20
  await fileserver.start()
20
21
 
21
22
 
22
23
  @bp.after_server_stop
23
- async def stop_fileserver(app, _):
24
+ async def stop_fileserver(app):
24
25
  await fileserver.stop()
25
26
 
26
27
 
@@ -92,6 +93,23 @@ async def control(req, ws):
92
93
  @bp.websocket("watch")
93
94
  @websocket_wrapper
94
95
  async def watch(req, ws):
96
+ # Build user info from either built-in auth or SSO
97
+ user_info = None
98
+ if sso_user := getattr(req.ctx, "sso_user", None):
99
+ # SSO auth (paskia mode): extract from validation response
100
+ ctx = sso_user.get("ctx", {})
101
+ perms = ctx.get("permissions", [])
102
+ user_info = {
103
+ "username": ctx.get("user", {}).get("display_name", ""),
104
+ "privileged": "cista:admin" in perms,
105
+ }
106
+ elif req.ctx.user:
107
+ # Built-in auth: use local user database
108
+ user_info = {
109
+ "username": req.ctx.username,
110
+ "privileged": req.ctx.user.privileged,
111
+ }
112
+
95
113
  await ws.send(
96
114
  msgspec.json.encode(
97
115
  {
@@ -99,13 +117,9 @@ async def watch(req, ws):
99
117
  "name": config.config.name or config.config.path.name,
100
118
  "version": __version__,
101
119
  "public": config.config.public,
120
+ "paskia": sso.paskia_enabled(),
102
121
  },
103
- "user": {
104
- "username": req.ctx.username,
105
- "privileged": req.ctx.user.privileged,
106
- }
107
- if req.ctx.user
108
- else None,
122
+ "user": user_info,
109
123
  }
110
124
  ).decode()
111
125
  )
@@ -136,3 +150,18 @@ def subscribe(uuid, ws):
136
150
  watching.format_space(watching.state.space),
137
151
  watching.format_root(watching.state.root),
138
152
  )
153
+
154
+
155
+ @bp.put("config/public")
156
+ async def update_public(request):
157
+ await auth.verify(request, privileged=True)
158
+ try:
159
+ public = request.json["public"]
160
+ if not isinstance(public, bool):
161
+ raise ValueError("public must be a boolean")
162
+ except KeyError:
163
+ raise BadRequest("Missing public field") from None
164
+ except ValueError as e:
165
+ raise BadRequest(str(e)) from None
166
+ config.update_config({"public": public})
167
+ return json({"message": "Public access setting updated", "public": public})
cista/app.py CHANGED
@@ -18,7 +18,7 @@ from setproctitle import setproctitle
18
18
  from stream_zip import ZIP_AUTO, stream_zip
19
19
  from zstandard import ZstdCompressor
20
20
 
21
- from cista import auth, config, preview, session, watching
21
+ from cista import auth, config, preview, session, sso, watching
22
22
  from cista.api import bp
23
23
  from cista.util.apphelpers import handle_sanic_exception
24
24
 
@@ -26,7 +26,11 @@ from cista.util.apphelpers import handle_sanic_exception
26
26
  sanic.helpers._ENTITY_HEADERS = frozenset()
27
27
 
28
28
  app = Sanic("cista", strict_slashes=True)
29
- app.blueprint(auth.bp)
29
+ # Register either SSO proxy or built-in auth routes based on PASKIA_BACKEND_URL
30
+ if sso.paskia_enabled():
31
+ app.blueprint(sso.bp) # SSO proxy for /auth/* routes
32
+ else:
33
+ app.blueprint(auth.bp) # Built-in auth routes
30
34
  app.blueprint(preview.bp)
31
35
  app.blueprint(bp)
32
36
  app.exception(Exception)(handle_sanic_exception)
@@ -36,22 +40,23 @@ setproctitle("cista-main")
36
40
 
37
41
 
38
42
  @app.before_server_start
39
- async def main_start(app, loop):
43
+ async def main_start(app):
40
44
  config.load_config()
41
45
  setproctitle(f"cista {config.config.path.name}")
42
46
  workers = max(2, min(8, cpu_count()))
43
47
  app.ctx.threadexec = ThreadPoolExecutor(
44
48
  max_workers=workers, thread_name_prefix="cista-ioworker"
45
49
  )
46
- watching.start(app, loop)
50
+ watching.start(app)
47
51
 
48
52
 
49
53
  # Sanic sometimes fails to execute after_server_stop, so we do it before instead (potentially interrupting handlers)
50
54
  @app.before_server_stop
51
- async def main_stop(app, loop):
55
+ async def main_stop(app):
52
56
  quit.set()
53
57
  watching.stop(app)
54
58
  app.ctx.threadexec.shutdown()
59
+ await sso.close_client()
55
60
  logger.debug("Cista worker threads all finished")
56
61
 
57
62
 
@@ -74,10 +79,23 @@ async def use_session(req):
74
79
  raise Forbidden("Invalid origin: Cross-Site requests not permitted")
75
80
 
76
81
 
82
+ @app.on_response
83
+ async def forward_sso_cookies(req, res):
84
+ """Forward Set-Cookie headers from SSO validation to client."""
85
+ if cookies := getattr(req.ctx, "sso_cookies", None):
86
+ for cookie in cookies:
87
+ res.headers.add("set-cookie", cookie)
88
+
89
+
77
90
  @app.before_server_start
78
- def http_fileserver(app, _):
91
+ def http_fileserver(app):
79
92
  bp = Blueprint("fileserver")
80
- bp.on_request(auth.verify)
93
+
94
+ @bp.on_request
95
+ async def verify_fileserver(request):
96
+ """Verify access to file server routes."""
97
+ await auth.verify(request)
98
+
81
99
  bp.static(
82
100
  "/files/",
83
101
  config.config.path,
@@ -93,9 +111,9 @@ www = {}
93
111
 
94
112
  def _load_wwwroot(www):
95
113
  wwwnew = {}
96
- base = Path(__file__).with_name("wwwroot")
114
+ base = Path(__file__).with_name("frontend-build")
97
115
  paths = [PurePath()]
98
- zstd = ZstdCompressor(level=10)
116
+ zstd = ZstdCompressor(level=18)
99
117
  while paths:
100
118
  path = paths.pop(0)
101
119
  current = base / path
@@ -211,7 +229,7 @@ async def wwwroot(req, path=""):
211
229
  @app.route("/favicon.ico", methods=["GET", "HEAD"])
212
230
  async def favicon(req):
213
231
  # Browsers keep asking for it when viewing files (not HTML with icon link)
214
- return redirect("/assets/logo-97d1d7eb.svg", status=308)
232
+ return redirect("/assets/logo-ctv8tVwU.svg", status=308)
215
233
 
216
234
 
217
235
  def get_files(wanted: set) -> list[tuple[PurePosixPath, Path]]:
@@ -239,6 +257,10 @@ def get_files(wanted: set) -> list[tuple[PurePosixPath, Path]]:
239
257
  @app.get("/zip/<keys>/<zipfile:ext=zip>")
240
258
  async def zip_download(req, keys, zipfile, ext):
241
259
  """Download a zip archive of the given keys"""
260
+ if config.config.authentication == "paskia":
261
+ await auth.verify_sso(req)
262
+ else:
263
+ auth.verify(req)
242
264
 
243
265
  wanted = set(keys.split("+"))
244
266
  files = get_files(wanted)
cista/auth.py CHANGED
@@ -12,6 +12,174 @@ from sanic.exceptions import BadRequest, Forbidden, Unauthorized
12
12
  from cista import config, session
13
13
  from cista.util import pwgen
14
14
 
15
+ _LOGIN_PAGE_CSS = """\
16
+ /* ===========================================
17
+ LOGIN PAGE STYLES
18
+ Must match ModalDialog.vue global styles.
19
+ =========================================== */
20
+ * { box-sizing: border-box; }
21
+ body {
22
+ font-family: 'Roboto', system-ui, -apple-system, sans-serif;
23
+ font-size: 1rem;
24
+ margin: 0;
25
+ min-height: 100vh;
26
+ display: flex;
27
+ align-items: center;
28
+ justify-content: center;
29
+ background: transparent;
30
+ }
31
+ .login-card {
32
+ background: #ddd;
33
+ color: #000;
34
+ border-radius: 0.5rem;
35
+ box-shadow: 0 0 1rem #0008;
36
+ width: 100%;
37
+ max-width: 320px;
38
+ }
39
+ h1 {
40
+ background: #146;
41
+ color: #fff;
42
+ margin: 0;
43
+ padding: 0.5rem 1rem;
44
+ font-size: 1.2rem;
45
+ font-weight: normal;
46
+ border-radius: 0.5rem 0.5rem 0 0;
47
+ }
48
+ .content {
49
+ padding: 1rem;
50
+ }
51
+ .message {
52
+ color: #444;
53
+ margin: 0 0 0.5rem 0;
54
+ font-size: 0.875rem;
55
+ }
56
+ form {
57
+ display: grid;
58
+ grid-template-columns: auto 1fr;
59
+ gap: 0.5rem 1rem;
60
+ align-items: center;
61
+ }
62
+ label {
63
+ font-size: 1rem;
64
+ }
65
+ input[type="text"],
66
+ input[type="password"] {
67
+ font: inherit;
68
+ font-size: 1rem;
69
+ padding: 0.5rem;
70
+ border: 2px solid #888;
71
+ border-radius: 0.25rem;
72
+ background: #fff;
73
+ color: #000;
74
+ min-width: 0;
75
+ }
76
+ input:focus {
77
+ outline: none;
78
+ border-color: #f80;
79
+ }
80
+ .button-row {
81
+ grid-column: 1 / -1;
82
+ display: flex;
83
+ justify-content: flex-end;
84
+ margin-top: 0.5rem;
85
+ }
86
+ button {
87
+ font: inherit;
88
+ font-size: 1rem;
89
+ padding: 0.5rem 1rem;
90
+ background: #146;
91
+ color: #fff;
92
+ border: none;
93
+ border-radius: 0.25rem;
94
+ cursor: pointer;
95
+ }
96
+ button:hover { background: #f80; }
97
+ button:disabled {
98
+ background: #888;
99
+ cursor: not-allowed;
100
+ }
101
+ .error {
102
+ grid-column: 1 / -1;
103
+ color: #c00;
104
+ font-size: 0.875rem;
105
+ min-height: 1.2em;
106
+ margin: 0;
107
+ }
108
+ """
109
+
110
+ _LOGIN_PAGE_JS = """\
111
+ const form = document.getElementById('loginForm');
112
+ const error = document.getElementById('error');
113
+ const submitBtn = document.getElementById('submitBtn');
114
+ const usernameField = document.getElementById('username');
115
+ const passwordField = document.getElementById('password');
116
+ const isInIframe = window.parent !== window;
117
+
118
+ // Focus username field on load
119
+ usernameField.focus();
120
+
121
+ const showError = (msg) => {
122
+ error.textContent = msg;
123
+ submitBtn.disabled = false;
124
+ submitBtn.textContent = 'Log in';
125
+ // Focus and select the relevant field
126
+ if (msg.toLowerCase().includes('password')) {
127
+ passwordField.focus();
128
+ passwordField.select();
129
+ } else {
130
+ usernameField.focus();
131
+ usernameField.select();
132
+ }
133
+ };
134
+
135
+ form.onsubmit = async (e) => {
136
+ e.preventDefault();
137
+ error.textContent = '';
138
+ submitBtn.disabled = true;
139
+ submitBtn.textContent = 'Logging in...';
140
+
141
+ try {
142
+ const res = await fetch('/auth/login', {
143
+ method: 'POST',
144
+ headers: {
145
+ 'Content-Type': 'application/json',
146
+ 'Accept': 'application/json'
147
+ },
148
+ body: JSON.stringify({
149
+ username: usernameField.value,
150
+ password: passwordField.value
151
+ })
152
+ });
153
+
154
+ if (res.ok) {
155
+ if (isInIframe) {
156
+ window.parent.postMessage({type: 'auth-success'}, '*');
157
+ } else {
158
+ window.location.href = '/';
159
+ }
160
+ } else {
161
+ const data = await res.json();
162
+ showError(data.message || data.detail || 'Login failed');
163
+ }
164
+ } catch (err) {
165
+ showError('Connection error. Please try again.');
166
+ }
167
+ };
168
+ """
169
+
170
+ # Import for SSO validation (lazily loaded to avoid circular imports)
171
+ _sso_module = None
172
+
173
+
174
+ def _get_sso():
175
+ global _sso_module
176
+ if _sso_module is None:
177
+ from cista import sso
178
+
179
+ _sso_module = sso
180
+ return _sso_module
181
+
182
+
15
183
  _argon = argon2.PasswordHasher()
16
184
  _droppyhash = re.compile(r"^([a-f0-9]{64})\$([a-f0-9]{8})$")
17
185
 
@@ -63,62 +231,109 @@ class LoginResponse(msgspec.Struct):
63
231
  error: str = ""
64
232
 
65
233
 
66
- def verify(request, *, privileged=False):
67
- """Raise Unauthorized or Forbidden if the request is not authorized"""
234
+ async def verify(request, *, privileged=False):
235
+ """Verify that the request is authorized.
236
+
237
+ For paskia mode (PASKIA_BACKEND_URL set), validates against the SSO backend.
238
+ For built-in mode, checks session-based authentication.
239
+ For public mode (config.public=True), allows all requests.
240
+
241
+ All 401/403 responses include auth.iframe URL for consistent frontend handling
242
+ via the paskia library's showAuthIframe().
243
+
244
+ Args:
245
+ request: The Sanic request object
246
+ privileged: If True, requires admin privileges
247
+
248
+ Raises:
249
+ Unauthorized: If authentication is required
250
+ Forbidden: If access is denied
251
+ """
252
+ sso = _get_sso()
253
+ if sso.paskia_enabled():
254
+ # SSO validation against auth backend
255
+ # Always check cista:login; privileged flag comes from response perm list
256
+ perm = "cista:admin" if privileged else "cista:login"
257
+ await sso.validate_sso_request(request, perm=perm)
258
+ return
259
+
260
+ user = getattr(request.ctx, "user", None)
68
261
  if privileged:
69
- if request.ctx.user:
70
- if request.ctx.user.privileged:
262
+ if user:
263
+ if user.privileged:
71
264
  return
72
- raise Forbidden("Access Forbidden: Only for privileged users", quiet=True)
73
- elif config.config.public or request.ctx.user:
265
+ raise Forbidden(
266
+ "Access Forbidden: Only for privileged users",
267
+ quiet=True,
268
+ )
269
+ elif config.config.public or user:
74
270
  return
75
- raise Unauthorized(f"Login required for {request.path}", "cookie", quiet=True)
271
+ # Return iframe URL for paskia library to show login dialog
272
+ raise Unauthorized(
273
+ f"Login required for {request.path}",
274
+ "cookie",
275
+ context={"auth": {"iframe": "/auth/restricted"}},
276
+ quiet=True,
277
+ )
76
278
 
77
279
 
78
- bp = Blueprint("auth")
280
+ # Blueprint for built-in auth (only registered when paskia is NOT enabled)
281
+ bp = Blueprint("auth", url_prefix="/auth")
79
282
 
80
283
 
81
- @bp.get("/login")
284
+ @bp.get("/restricted")
82
285
  async def login_page(request):
83
- doc = Document("Cista Login")
84
- with doc.div(id="login"):
85
- with doc.form(method="POST", autocomplete="on"):
86
- doc.h1("Login")
87
- doc.input(
88
- name="username",
89
- placeholder="Username",
90
- autocomplete="username",
91
- required=True,
92
- ).br
93
- doc.input(
94
- type="password",
95
- name="password",
96
- placeholder="Password",
97
- autocomplete="current-password",
98
- required=True,
99
- ).br
100
- doc.input(type="submit", value="Login")
101
- s = session.get(request)
102
- if s:
103
- name = s["username"]
104
- with doc.form(method="POST", action="/logout"):
105
- doc.input(type="submit", value=f"Logout {name}")
106
- flash = request.cookies.message
107
- if flash:
108
- doc.dialog(
109
- flash,
110
- id="flash",
111
- open=True,
112
- style="position: fixed; top: 0; left: 0; width: 100%; opacity: .8",
113
- )
286
+ """Login page that works both standalone and in paskia iframe."""
287
+ s = session.get(request)
288
+
289
+ # Check if already logged in
290
+ if s:
291
+ # Already authenticated - signal success if in iframe
292
+ return html(_login_success_page(s["username"]))
293
+
294
+ doc = Document("Cista - Login")
295
+ # Add paskia-compatible styling and scripts
296
+ doc.style(_LOGIN_PAGE_CSS)
297
+ with doc.div(class_="login-card"):
298
+ doc.h1("Authentication Required")
299
+ with doc.div(class_="content"):
300
+ with doc.form(method="POST", id="loginForm", autocomplete="on"):
301
+ doc.label("Username:", for_="username")
302
+ doc.input(
303
+ type="text",
304
+ id="username",
305
+ name="username",
306
+ autocomplete="username webauthn",
307
+ required=True,
308
+ )
309
+ doc.label("Password:", for_="password")
310
+ doc.input(
311
+ type="password",
312
+ id="password",
313
+ name="password",
314
+ autocomplete="current-password webauthn",
315
+ required=True,
316
+ )
317
+ with doc.div(class_="button-row"):
318
+ doc.button("Log in", type="submit", id="submitBtn")
319
+ doc.p("", class_="error", id="error")
320
+
321
+ # JavaScript for AJAX login and postMessage communication
322
+ doc.script_(_LOGIN_PAGE_JS)
323
+
114
324
  res = html(doc)
115
- if flash:
116
- res.cookies.delete_cookie("flash")
117
325
  if s is False:
118
326
  session.delete(res)
119
327
  return res
120
328
 
121
329
 
330
+ def _login_success_page(username: str) -> str:
331
+ """Minimal page that signals auth-success to parent iframe."""
332
+ return str(
333
+ Document().script_("window.parent.postMessage({type:'auth-success'},'*')")
334
+ )
335
+
336
+
122
337
  @bp.post("/login")
123
338
  async def login_post(request):
124
339
  try:
@@ -149,7 +364,7 @@ async def login_post(request):
149
364
  return res
150
365
 
151
366
 
152
- @bp.post("/logout")
367
+ @bp.post("/api/logout")
153
368
  async def logout_post(request):
154
369
  s = request.ctx.session
155
370
  msg = "Logged out" if s else "Not logged in"
@@ -196,7 +411,7 @@ async def change_password(request):
196
411
 
197
412
  @bp.get("/users")
198
413
  async def list_users(request):
199
- verify(request, privileged=True)
414
+ await verify(request, privileged=True)
200
415
  users = []
201
416
  for name, user in config.config.users.items():
202
417
  users.append(
@@ -211,7 +426,7 @@ async def list_users(request):
211
426
 
212
427
  @bp.post("/users")
213
428
  async def create_user(request):
214
- verify(request, privileged=True)
429
+ await verify(request, privileged=True)
215
430
  try:
216
431
  if request.headers.content_type == "application/json":
217
432
  username = request.json["username"]
@@ -240,7 +455,7 @@ async def create_user(request):
240
455
 
241
456
  @bp.put("/users/<username>")
242
457
  async def update_user(request, username):
243
- verify(request, privileged=True)
458
+ await verify(request, privileged=True)
244
459
  try:
245
460
  if request.headers.content_type == "application/json":
246
461
  changes = request.json
@@ -273,7 +488,7 @@ async def update_user(request, username):
273
488
 
274
489
  @bp.delete("/users/<username>")
275
490
  async def delete_user(request, username):
276
- verify(request, privileged=True)
491
+ await verify(request, privileged=True)
277
492
  if username not in config.config.users:
278
493
  raise BadRequest("User does not exist")
279
494
  try:
@@ -281,14 +496,3 @@ async def delete_user(request, username):
281
496
  except Exception as e:
282
497
  raise BadRequest(str(e)) from e
283
498
  return json({"message": f"User {username} deleted"})
284
-
285
-
286
- @bp.put("/config/public")
287
- async def update_public(request):
288
- verify(request, privileged=True)
289
- try:
290
- public = request.json["public"]
291
- except KeyError:
292
- raise BadRequest("Missing public field") from None
293
- config.update_config({"public": public})
294
- return json({"message": "Public setting updated"})
cista/config.py CHANGED
@@ -152,7 +152,15 @@ def modifies_config(
152
152
  def load_config():
153
153
  global config
154
154
  init_confdir()
155
- config = msgspec.toml.decode(conffile.read_bytes(), type=Config, dec_hook=dec_hook)
155
+ raw = conffile.read_bytes()
156
+ config = msgspec.toml.decode(raw, type=Config, dec_hook=dec_hook)
157
+ # Migrate from old authentication field if present
158
+ raw_dict = msgspec.toml.decode(raw)
159
+ if "authentication" in raw_dict and "public" not in raw_dict:
160
+ # Old config with authentication mode: migrate to public bool
161
+ new_public = raw_dict["authentication"] == "none"
162
+ config = msgspec.structs.replace(config, public=new_public)
163
+ update_config({}) # Save the migrated config
156
164
 
157
165
 
158
166
  @modifies_config