diff --git a/api/media.py b/api/media.py index a8530d3..b9a2b69 100644 --- a/api/media.py +++ b/api/media.py @@ -5,6 +5,7 @@ Symlinks are excluded entirely; media mounts must also be read-only in deploymen """ import os import stat +from contextlib import contextmanager, ExitStack from pathlib import Path from flask import current_app @@ -13,6 +14,18 @@ class MediaDenied(ValueError): pass +class InvalidFolderPath(MediaDenied): + pass + + +class FolderNotFound(MediaDenied): + pass + + +class MediaUnavailable(MediaDenied): + pass + + def media_root(): try: root = Path(current_app.config["MEDIA_ROOT"]).resolve(strict=True) @@ -23,12 +36,27 @@ def media_root(): raise MediaDenied() from None -def assigned_root(value): +def virtual_parts(value): if not isinstance(value, str) or not value.startswith("/"): - raise MediaDenied() + raise InvalidFolderPath() parts = value[1:].split("/") if value != "/" else [] - if any(part in ("", ".", "..") or "\\" in part or "%" in part or "\x00" in part for part in parts): + if any(part in ("", ".", "..") or "\x00" in part for part in parts): + raise InvalidFolderPath() + return parts + + +def _assignment_parts(value): + try: + parts = virtual_parts(value) + except InvalidFolderPath: + raise MediaDenied() from None + if "\\" in value or "%" in value: raise MediaDenied() + return parts + + +def assigned_root(value): + parts = _assignment_parts(value) root = media_root() path = root try: @@ -44,43 +72,81 @@ def assigned_root(value): raise MediaDenied() from None -def file_tree(root): - """List using anchored directory descriptors; never follow swapped links.""" - tree = [] +@contextmanager +def _open_directory(root, parts=()): flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW - - def visit(descriptor, virtual): - dirs, files, children = [], [], [] - with os.scandir(descriptor) as entries: - names = sorted(entry.name for entry in entries) - for name in names: - metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False) - if stat.S_ISDIR(metadata.st_mode): - dirs.append(name) - children.append(name) - elif stat.S_ISREG(metadata.st_mode): - files.append({"name": name, "size": metadata.st_size}) - tree.append({"root": virtual, "dirs": dirs, "files": files}) - for name in children: - child_fd = os.open(name, flags, dir_fd=descriptor) - try: - visit(child_fd, virtual.rstrip("/") + "/" + name) - finally: - os.close(child_fd) - - descriptor = None + descriptor = os.dup(root) if isinstance(root, int) else os.open(root, flags) try: - base = media_root() - parts = root.relative_to(base).parts - descriptor = os.open(base, flags) for part in parts: child_fd = os.open(part, flags, dir_fd=descriptor) os.close(descriptor) descriptor = child_fd - visit(descriptor, "/") + yield descriptor + finally: + os.close(descriptor) + + +def _folder_entries(descriptor): + dirs, files = [], [] + with os.scandir(descriptor) as entries: + names = sorted(entry.name for entry in entries) + for name in names: + try: + metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False) + except FileNotFoundError: + # The entry was removed between enumeration and the metadata read. + continue + if stat.S_ISDIR(metadata.st_mode): + dirs.append(name) + elif stat.S_ISREG(metadata.st_mode): + files.append({"name": name, "size": metadata.st_size}) + return dirs, files + + +def list_assigned_folder(assignment, virtual): + """List direct children within an assigned root, using virtual references.""" + assignment_parts = _assignment_parts(assignment) + parts = virtual_parts(virtual) + try: + root = media_root() + except MediaDenied: + raise MediaUnavailable() from None + + try: + with ExitStack() as stack: + base = stack.enter_context(_open_directory(root)) + try: + assigned = stack.enter_context(_open_directory(base, assignment_parts)) + except (FileNotFoundError, NotADirectoryError): + raise MediaDenied() from None + try: + folder = stack.enter_context(_open_directory(assigned, parts)) + except (FileNotFoundError, NotADirectoryError): + raise FolderNotFound() from None + dirs, files = _folder_entries(folder) + except OSError: + raise MediaUnavailable() from None + + for file in files: + file["ref"] = f"{virtual.rstrip('/')}/{file['name']}" + return {"root": virtual, "dirs": dirs, "files": files} + + +def file_tree(root): + """List using anchored directory descriptors; never follow swapped links.""" + tree = [] + + def visit(descriptor, virtual): + dirs, files = _folder_entries(descriptor) + tree.append({"root": virtual, "dirs": dirs, "files": files}) + for name in dirs: + with _open_directory(descriptor, (name,)) as child_fd: + visit(child_fd, virtual.rstrip("/") + "/" + name) + + try: + base = media_root() + with _open_directory(base, root.relative_to(base).parts) as descriptor: + visit(descriptor, "/") except (OSError, RuntimeError, ValueError): raise MediaDenied() from None - finally: - if descriptor is not None: - os.close(descriptor) return tree diff --git a/api/routes/file_routes.py b/api/routes/file_routes.py index d1ff33c..3e55fd0 100644 --- a/api/routes/file_routes.py +++ b/api/routes/file_routes.py @@ -1,8 +1,17 @@ """Media routes. Legacy client-directed downloads are deliberately disabled.""" +from flask import request from settings import app from auth import token_auth from errors import error_response -from media import media_root, file_tree, MediaDenied +from media import ( + FolderNotFound, + InvalidFolderPath, + MediaDenied, + MediaUnavailable, + file_tree, + list_assigned_folder, + media_root, +) @app.route("/api/file/root") @@ -16,6 +25,27 @@ def get_root_path(): return error_response(503, "Media unavailable") +@app.route("/api/file/browse") +@token_auth.login_required +def browse_files(): + user = token_auth.current_user() + if user.root is None: + return error_response(403, "No assigned folder") + + try: + folder = list_assigned_folder(user.root, request.args.get("path", "/")) + except InvalidFolderPath: + return error_response(400, "Invalid folder path") + except FolderNotFound: + return error_response(404, "Folder unavailable") + except MediaUnavailable: + return error_response(503, "Media unavailable") + except MediaDenied: + return error_response(403, "Assigned folder unavailable") + + return folder, 200, {"Cache-Control": "no-store"} + + @app.route("/api/file", methods=["POST"]) @token_auth.login_required def get_file(): diff --git a/api/routes/token_routes.py b/api/routes/token_routes.py index d65810a..31dd525 100644 --- a/api/routes/token_routes.py +++ b/api/routes/token_routes.py @@ -20,7 +20,7 @@ def get_token(): refresh_token = user.get_refresh_token() db.session.commit() response = make_response( - jsonify({**user.to_dict(rules=("is_admin", "token")), "user_id": user.id}) + jsonify({**user.to_dict(rules=("-root", "is_admin", "token")), "user_id": user.id}) ) response.set_cookie("refresh_token", value=refresh_token, httponly=True) return response diff --git a/api/tests/test_security.py b/api/tests/test_security.py index 3dfdaa5..26deef3 100644 --- a/api/tests/test_security.py +++ b/api/tests/test_security.py @@ -65,6 +65,15 @@ class SecurityTests(unittest.TestCase): self.assertEqual(data['user_id'], data['id']) self.assertEqual(self.client.get('/api/auth/refresh').get_json()['user_id'], data['user_id']) + def test_sign_in_keeps_stored_folder_assignment_on_server(self): + alice = db.session.get(User, self.alice_id) + alice.root = str(self.root / 'alice') + db.session.commit() + basic = base64.b64encode(b'alice:test-password').decode() + response = self.client.post('/api/auth/token', headers={'Authorization': 'Basic ' + basic}) + self.assertEqual(response.status_code, 200) + self.assertNotIn('root', response.get_json()) + def test_first_login_issues_usable_token(self): user = User(username='new-admin', is_admin=True, login_disabled=False) user.set_password('test-password') @@ -152,6 +161,71 @@ class SecurityTests(unittest.TestCase): nested.unlink() saved.rename(nested) + def test_browse_lists_one_folder_with_virtual_references(self): + url = '/api/file/browse' + headers = self.headers('alice') + response = self.client.get(url, headers=headers) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.cache_control.no_store) + self.assertEqual(response.get_json(), { + 'root': '/', + 'dirs': ['nested'], + 'files': [{'name': 'movie.mp4', 'size': 5, 'ref': '/movie.mp4'}], + }) + + response = self.client.get(url, query_string={'path': '/nested'}, headers=headers) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json(), { + 'root': '/nested', + 'dirs': [], + 'files': [{'name': 'other.mp4', 'size': 5, 'ref': '/nested/other.mp4'}], + }) + + with tempfile.TemporaryDirectory(prefix='Clips & 100% café ', dir=self.root / 'alice') as empty: + virtual = '/' + Path(empty).name + response = self.client.get(url, query_string={'path': virtual}, headers=headers) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json(), {'root': virtual, 'dirs': [], 'files': []}) + + def test_browse_requires_a_current_enabled_account_and_assignment(self): + url = '/api/file/browse' + self.assertEqual(self.client.get(url).status_code, 401) + for account, status in [('disabled', 401), ('empty', 403), ('admin', 403)]: + with self.subTest(account=account): + self.assertEqual(self.client.get(url, headers=self.headers(account)).status_code, status) + + self.client.patch(f'/api/user/{self.alice_id}', json={'root': '/bob'}, headers=self.headers('admin')) + response = self.client.get(url, headers=self.headers('alice')) + self.assertEqual(response.get_json(), {'root': '/', 'dirs': [], 'files': []}) + self.client.patch(f'/api/user/{self.alice_id}', json={'root': None}, headers=self.headers('admin')) + self.assertEqual(self.client.get(url, headers=self.headers('alice')).status_code, 403) + + def test_browse_keeps_navigation_inside_the_assigned_root(self): + url = '/api/file/browse' + headers = self.headers('alice') + for path in ['', 'nested', '//nested', '/nested/', '/nested/.', '/nested/..']: + with self.subTest(path=path): + response = self.client.get(url, query_string={'path': path}, headers=headers) + self.assertEqual(response.status_code, 400) + for path in ['/bob', '/sibling', '/escape', '/movie.mp4']: + with self.subTest(path=path): + response = self.client.get(url, query_string={'path': path}, headers=headers) + self.assertEqual(response.status_code, 404) + self.assertEqual(response.get_json()['message'], 'Folder unavailable') + + def test_browse_reports_unavailable_media_without_path_details(self): + url = '/api/file/browse' + headers = self.headers('alice') + with patch('media.os.scandir', side_effect=OSError('Internal storage detail')): + response = self.client.get(url, headers=headers) + self.assertEqual(response.status_code, 503) + self.assertEqual(response.get_json()['message'], 'Media unavailable') + + app.config['MEDIA_ROOT'] = str(self.root / 'unavailable') + response = self.client.get(url, headers=headers) + self.assertEqual(response.status_code, 503) + self.assertNotIn(str(self.root), response.get_data(as_text=True)) + def test_old_download_never_serves_files(self): for payload in [{'path':str(self.root / 'alice'),'filename':'movie.mp4'}, {'path':'/etc','filename':'passwd'}, {}, None]: self.assertEqual(self.client.post('/api/file',json=payload,headers=self.headers('alice')).status_code,410) diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index d30463a..ef1e72e 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,8 +1,8 @@ # Foldershare current state -- Updated: 2026-11-25 for TASK-002 integration -- Inspected worktree: `/home/rob/projects/foldershare` -- TASK-002 integration base: `codex` at `cd6d6b3` +- Updated: 2026-11-25 for TASK-003 acceptance and integration +- Inspected worktree: `/home/rob/projects/foldershare/.worktrees/TASK-003` +- TASK-003 base: `codex` at `549f11d` ## Verified repository state @@ -45,3 +45,11 @@ Captain accepted TASK-002 on 2026-11-07 and authorized its local integration int - The authentication checks require `login_disabled = false`. Rows left `NULL` by the old nullable migration are denied authentication. Existing invalid or host-absolute folder assignments require admin reassignment to virtual paths. TASK-002 includes no data migration, and local account and assignment data were not inspected. - On 2026-11-25, all ten API tests passed with disposable SQLite and media fixtures. Python syntax checks, frontend production build and diff checks passed. Frontend lint could not run because ESLint configuration is missing. Python datetime and Sass deprecation warnings remain. - TASK-003 covers ordinary-user browsing, TASK-004 covers download grants and resume, and TASK-005 covers the rest of the admin workflow. Target-Pi deployment and cookie/TLS configuration remain unverified. TASK-007's manual-test adapter awaits separate Captain validation in its own worktree. + +## TASK-003 assigned-folder browsing + +- Implemented in `task/TASK-003-secure-browsing`. Captain accepted the task and authorized its local integration into `codex` on 2026-11-25. +- Signed-in users can browse within their current assigned root. The homepage renders folder navigation, file metadata, and distinct messages for empty, unassigned and unavailable media. The admin folder picker continues to use the admin-only root API. Stored assignments are omitted from the sign-in response. +- The API returns one directory at a time and verifies the current assignment on each call. The server reports a missing media root or storage I/O errors as unavailable. Detecting a disconnected mount that still looks like a readable local directory requires deployment-level mount checks under TASK-006. +- All 15 API tests, Python syntax, production build and diff checks passed. Frontend lint is still blocked by the absent ESLint configuration. Chromium exercised the isolated snapshot at 1280 × 800 and 375 × 812. The existing header references a missing `/logo.png` asset in both views. +- The TASK-007 adapter produced and verified the snapshot. Its readiness HTTP check timed out on concurrent cold frontend and browser startup, so the successful QA run delayed the adapter's Firefox launch. The candidate passed Chromium browser QA and the disposable session cleaned up. The TASK-003 snapshot was absent at integration preflight. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index f79613d..cd72b0f 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -83,3 +83,14 @@ The 2026-11-04 snapshot references work on `codex` while the existing proposal s - `POST /api/file` returns authenticated 410 without reading its payload or filesystem until TASK-004 replaces downloads with authorized grants. Anonymous requests remain 401. - User POST/PATCH/DELETE require admin (authenticated non-admin 403); POST accepts username/password only, PATCH root/login_disabled only with validated types. Disabled/missing users cannot use Basic/access/refresh authentication; disabling revokes credentials so re-enabling does not restore them. - `FOLDERSHARE_DATABASE_URI` optionally overrides SQLite configuration for isolated tests; default database remains unchanged. `ROOT_PATH` still configures media, resolved from process working directory at startup. + +## WF-004: TASK-003 implementation location + +- Captain engaged the briefed task from `codex` at `549f11d`, using branch `task/TASK-003-secure-browsing` and worktree `.worktrees/TASK-003`. + +## TASK-003 browse API contract + +- `GET /api/file/browse?path=/folder` uses bearer authentication. The `path` query value defaults to `/` and is relative to the current user's assigned root. This applies to admin accounts on the browsing endpoint as well. The admin-only `GET /api/file/root` retains the existing assignable tree and response shape. +- Success returns `{root, dirs, files}` for the requested folder's direct children. `root` is the requested virtual path. `dirs` contains directory names. `files` contains `{name, size, ref}` entries with byte sizes and slash-delimited virtual references such as `/folder/video.mp4`. The client URL-encodes the query value once. The server resolves the assigned root and requested directory on each call without following symlinks. Success responses specify `Cache-Control: no-store`. +- The endpoint returns 401 for invalid authentication, 403 for a missing or unusable assignment, 400 for invalid virtual path structure, 404 for a folder missing within the assignment, and 503 for unavailable media or storage errors. A readable empty folder returns 200 with empty arrays. Sign-in omits the stored assignment from the session payload. +- TASK-004 may use `ref` as a file reference in its grant request body. The download-grant endpoint must recheck current ownership, containment and file existence. The opaque download URL follows PRD-003. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 26ea0ff..bb40902 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,9 +1,31 @@ # Foldershare handoff -Updated 2026-11-25. Captain accepted TASK-002 on 2026-11-07 and authorized committing it from `.worktrees/TASK-002` and integrating it locally into `codex` on 2026-11-25. +Updated 2026-11-25. **TASK-003 is Complete.** Captain accepted the task and authorized a local commit and merge into `codex`. -TASK-002 supplies the authorization and filesystem boundaries. Integration checks passed for ten API tests, Python syntax, the frontend production build and whitespace. The frontend lint script requires a missing ESLint configuration. Existing accounts with a `NULL` login flag are denied access, and existing host-absolute assignments need admin reassignment. +The implementation came from `.worktrees/TASK-003` on `task/TASK-003-secure-browsing`, based on `codex` at `549f11d`. It adds assigned-folder browsing, preserves the admin-only picker, and publishes virtual file references for TASK-004. See `DECISIONS.md` for the API contract. -Captain selected TASK-003 for briefing. It remains Accepted. Use the merged `codex` tip as the proposed base for `task/TASK-003-secure-browsing` in `.worktrees/TASK-003`, subject to approval when Captain engages the task. Reuse TASK-002's virtual roots and media containment for authenticated browsing. Preserve the admin-only folder picker and existing browser styling. Define the browse response and its stable file reference for TASK-004 during implementation. +## Repeatable browser check -Validate browse access and failure states with disposable media and user fixtures, then verify the browser flow for assigned, unassigned and admin users. TASK-007 has a separate manual-test adapter awaiting Captain validation. Its integration or use for a later handoff is a separate decision. +From the primary repository root, launch the exact candidate with the TASK-007 adapter. Both loopback ports 5502 and 5503 must be free. + +```bash +PATH="$HOME/.local/bin:$PATH" ./.worktrees/TASK-007/scripts/testtask.sh 003 +``` + +Choose Firefox and use the disposable accounts and password printed by the launcher at `http://127.0.0.1:5503/`. The adapter starts with `sample.txt` at the assigned root. To exercise nested and empty-folder navigation, add fixtures in a second terminal from the primary root after the adapter reports readiness. + +```bash +task_run=$(cat .worktrees/TASK-007/.test-worktrees/task-003/.testtask-owner) && + mkdir -p -- "$task_run/media/friends/Series/Season 1" "$task_run/media/friends/Empty" && + printf 'Disposable QA fixture\n' > "$task_run/media/friends/Series/Season 1/episode.txt" +``` + +1. Sign in as `friend`. Open `Series`, then `Season 1`. Check that the file appears, use the breadcrumb and parent button, then open `Empty` and confirm the empty message. +2. Sign in as `unassigned` and confirm the no-access message. +3. Sign in as `captain`, open **Users**, select `friend`, and verify that the assignable-folder tree opens at the assigned folder and navigates back to the media root. + +Stop the owned test session using Ctrl-C in its terminal. The adapter removes the disposable snapshot and fixtures. A new run captures the current task changes. + +## Validation + +All 15 API tests, Python syntax, production frontend build and whitespace checks passed again before integration. The build and tests retain existing Sass and datetime deprecation warnings. ESLint configuration is absent. Headless Chromium previously verified the disposable candidate at widths of 1280 and 375 pixels, including keyboard navigation, share outage and retry, a removed folder, unassigned access, and admin folder navigation. The header's existing `/logo.png` asset is missing. The adapter's cold startup can time out while Vite and Firefox start together. Agent QA delayed Firefox startup and verified adapter readiness and cleanup. TASK-007 still awaits separate Captain acceptance. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index 818b838..859cd93 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -1,6 +1,6 @@ # Foldershare project overview -Stable facts here are based on repository source and configuration as inspected on 2026-11-04. This is not a runtime or deployment verification record. +Stable facts here are based on repository source and configuration. Runtime and deployment evidence belongs in `CURRENT_STATE.md`. ## Product and architecture @@ -17,7 +17,7 @@ The repository contains a folder-sharing web application. `react/` is a React 18 - `react/package.json` defines `npm run dev`, `npm run build`, `npm run lint`, and `npm run preview`. - `react/vite.config.js` defines the development API proxy. -- `api/config/requirements.txt` lists Python dependencies. No repository-defined API test command or test suite is tracked. +- `api/config/requirements.txt` lists Python dependencies. Run `python -m unittest discover -s api/tests -v` from the repository root with the API environment to exercise the tracked API regression suite. - No tracked CI, container, deployment, Git workflow, or manual-test/testtask documentation was found during reconciliation. - Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked. diff --git a/docs/TASKS.md b/docs/TASKS.md index 3da18b8..fb7fe0d 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -50,7 +50,7 @@ The scopes below translate Captain's explicit product requirements into implemen ### TASK-003: Secure folder browsing for assigned users -- Status: Accepted; not started. +- Status: Complete. Captain accepted TASK-003 on 2026-11-25 and authorized the local commit and merge into `codex`. - Objective: Provide a usable browser rooted in each user's authorized directory without exposing real server paths. - Scope: Replace/adjust browsing API to return virtual paths or opaque IDs, list only authorized child folders/files and their safe metadata; wire navigation/breadcrumbs, empty/error states, and denied/unavailable-share behavior. Retain existing visual patterns unless specifically approved to redesign. - Non-goals: Upload, rename, delete, global search, multiple roots, ZIP selection. @@ -59,6 +59,8 @@ The scopes below translate Captain's explicit product requirements into implemen - Dependencies: TASK-002 shared authorization utilities; API shape documented during task. - Validation: API tests plus `npm run lint`, `npm run build`, manual navigation for admin/standard/no-root users. - Recommended specialist: Webapp Feature, Frontend Visual QA, Code Review. +- Implementation: Authenticated one-folder listings use the current assignment as `/`. The homepage provides breadcrumbs, parent navigation, and loading, empty, no-access, unavailable and retry states. The admin-only folder picker retains its separate tree. See `DECISIONS.md` for virtual file references and API statuses. +- Evidence: All 15 API tests, Python syntax, production build, and diff checks passed again before integration on 2026-11-25. Chromium previously verified keyboard navigation, responsive desktop and mobile layouts, share failure and recovery, unassigned access, and the admin picker using the exact task snapshot. Lint could not run because ESLint configuration is absent. ### TASK-004: Opaque single-file downloading with resume diff --git a/react/src/components/FileBrowser/FileBrowser.jsx b/react/src/components/FileBrowser/FileBrowser.jsx index 7577e7b..45f6aec 100644 --- a/react/src/components/FileBrowser/FileBrowser.jsx +++ b/react/src/components/FileBrowser/FileBrowser.jsx @@ -1,199 +1,141 @@ -import { useState, useEffect } from "react"; +import { useState } from "react"; import styles from "./FileBrowser.module.scss"; import { ListGroup, Breadcrumb } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { - faFolder, - faFile, - faFileVideo, - faDownload, - faSquare, - faSquareCheck, -} from "@fortawesome/free-solid-svg-icons"; +import { faFolder, faFile, faFileVideo, faSquare, faSquareCheck } from "@fortawesome/free-solid-svg-icons"; const videoExtensions = ["mkv", "avi", "mp4"]; -const apiBaseUrl = "http://localhost:5173"; -const FileIcon = ({ fileName }) => - videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? ( - - ) : ( - - ); +const FileIcon = ({ fileName }) => ( + fileName.endsWith(`.${ext}`)) ? faFileVideo : faFile} + /> +); -const FileSize = ({ file }) => ( +const FileSize = ({ size }) => (
- {parseInt(file.size / (1024 * 1024))} + {Math.floor(size / (1024 * 1024))} MB
); -const FileBrowser = ({ - tree, - defaultPath, - onDownloadFile, - onSetRootFolder, - onUnsetRootFolder -}) => { - const [currentPath, setCurrentPath] = useState(null); - - const isUserRoot = () => { - return true; - }; - - console.log(currentPath, defaultPath, tree); - - useEffect(() => { - if (!currentPath && tree) { - if (defaultPath) { - setCurrentPath(tree.find((p) => p.root === defaultPath)); - } else if (tree.length) { - setCurrentPath(tree[0]); - } - } - }, [tree, currentPath, defaultPath]); - - const handleSelectParentFolder = () => { - const pathArray = currentPath.root.split("/"); - pathArray.pop(); - const path = tree.find( - (f) => - f.root === (pathArray.length == 1 ? "/" : pathArray.join("/")) - ); - setCurrentPath(path); - }; - - const getDirPath = (dir) => - tree.find( - (f) => - f.root === - `${currentPath.root}${ - currentPath.root === "/" ? "" : "/" - }${dir}` - ); - - const handleSelectFolder = (dir) => { - const path = getDirPath(dir); - if (path) { - setCurrentPath(path); - } - }; - - const handleSelectFolderByDepth = (depth) => { - const newPath = `/${currentPath.root - .split("/") - .slice(1, depth + 1) - .join("/")}`; - const path = tree.find((f) => f.root === newPath); - setCurrentPath(path); - }; +const FileBrowser = ({ path, folder, onNavigate, assignedPath, onSetRootFolder, onUnsetRootFolder, children }) => { + const segments = path === "/" ? [] : path.slice(1).split("/"); + const breadcrumbs = [ + { name: "Shared Folder", target: "/" }, + ...segments.map((name, index) => ({ + name, + target: `/${segments.slice(0, index + 1).join("/")}`, + })), + ]; + const parent = breadcrumbs.at(-2); return (
- - handleSelectFolderByDepth(0)} - > - Shared Folder - - {currentPath?.root.split("/").map((bc, index) => - index > 0 ? ( - handleSelectFolderByDepth(index)} - > - {bc} - - ) : ( - "" - ) - )} + + {breadcrumbs.map(({ name, target }) => ( + onNavigate(target), + }} + > + {name} + + ))} - - {tree && currentPath?.root !== tree[0].root && ( + {children} + + {parent && ( onNavigate(parent.target)} className={styles.listItem} + aria-label="Parent folder" > .. )} - - {currentPath?.dirs?.map((dir, index) => { - const isSelected = getDirPath(dir).root === defaultPath; + {folder?.dirs.map((name) => { + const target = `${path === "/" ? "" : path}/${name}`; + const isAssigned = target === assignedPath; + const label = ( + <> + + {name} + + ); + if (onSetRootFolder) { + return ( + + + + + ); + } return ( handleSelectFolder(dir)} + type="button" + className={styles.listItem} + onClick={() => onNavigate(target)} variant="dark" - key={index} + key={name} > -
- -
-
{dir}
-
- {onSetRootFolder && isSelected && ( - onUnsetRootFolder(e)} - /> - )} - {onSetRootFolder && !isSelected && ( - - onSetRootFolder( - e, - currentPath.root, - dir - ) - } - /> - )} -
+ {label}
); })} - - {currentPath?.files?.map((file, index) => ( - -
- -
-
{file.name}
-
- - {onDownloadFile && ( - - )} -
+ {folder?.files.map((file) => ( + + + {file.name} + ))}
+ {folder && folder.dirs.length === 0 && folder.files.length === 0 && ( +

This folder is empty.

+ )}
); }; +export const FolderTreeBrowser = ({ tree, assignedPath, onSetRootFolder, onUnsetRootFolder }) => { + const [path, setPath] = useState(assignedPath); + const folder = tree.find((entry) => entry.root === path) ?? tree[0]; + return ( + + ); +}; + export default FileBrowser; diff --git a/react/src/components/FileBrowser/FileBrowser.module.scss b/react/src/components/FileBrowser/FileBrowser.module.scss index 765d542..7e19b81 100644 --- a/react/src/components/FileBrowser/FileBrowser.module.scss +++ b/react/src/components/FileBrowser/FileBrowser.module.scss @@ -1,47 +1,59 @@ @import "/src/styles/colors.scss"; .fileBrowser { - //background-color: map-get($theme-colors, primary); padding-top: 30px; - //border-radius: 5px; - .fileList { - .listItem { - display: flex; - flex-direction: row; - gap: 20px; - .icon { - &.dload, - &.setRoot { - cursor: pointer; - &:hover { - color: #2d3dd4; - } - } - } - .name { - width: 100%; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - } - .action { - width: 100px; - display: flex; - justify-content: flex-end; - gap: 10px; - .size { - span { - margin-left: 5px; - } - } - } - &.selected { - background-color: map-get($theme-colors, primary); - } - } - .disabled { - pointer-events: none; - cursor: auto; - } +} + +.listItem, +.folderButton { + display: flex; + align-items: center; + gap: 20px; + min-width: 0; +} + +.name { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.size { + flex-shrink: 0; + + span { + margin-left: 5px; } } + +.folderButton, +.assignmentButton { + color: inherit; + background: none; + border: 0; + padding: 0; +} + +.folderButton { + flex: 1; + text-align: left; +} + +.assignmentButton:hover { + color: #2d3dd4; +} + +.selected { + background-color: map-get($theme-colors, primary); +} + +.fileBrowser :global(.breadcrumb-item) { + overflow-wrap: anywhere; +} + +.breadcrumbButton { + text-align: left; + overflow-wrap: anywhere; +} diff --git a/react/src/contexts/AuthContext.jsx b/react/src/contexts/AuthContext.jsx index 170b29d..fe57feb 100644 --- a/react/src/contexts/AuthContext.jsx +++ b/react/src/contexts/AuthContext.jsx @@ -1,5 +1,5 @@ /* eslint-disable react-refresh/only-export-components */ -import { createContext, useContext, useReducer, useEffect } from "react"; +import { createContext, useContext, useReducer, useEffect, useCallback } from "react"; import PropTypes from "prop-types"; import { encode as base64_encode } from "base-64"; import { useLocalStorage } from "../hooks/useLocalStorage"; @@ -41,6 +41,21 @@ function reducer(state, action) { } } +function requestWithToken(url, token, options) { + if (!token) { + throw new Error("No bearer token"); + } + return fetch(`${BASE_URL}/${url}`, { + ...options, + credentials: "include", + headers: { + Authorization: `Bearer ${token}`, + "X-Requested-With": "XMLHttpRequest", + "Content-Type": "application/json", + }, + }); +} + function AuthProvider({ children }) { const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer( reducer, @@ -52,7 +67,7 @@ function AuthProvider({ children }) { useEffect(() => { const user = getLSItems(["user_id", "token", "username", "is_admin"]); if (!!user.token && !!user.username) { - dispatch({ type: "auth/login", payload: user }); + dispatch({ type: "auth/login", payload: { ...user, is_admin: user.is_admin === "true" } }); } }, []); @@ -89,31 +104,14 @@ function AuthProvider({ children }) { dispatch({ type: "auth/logout" }); } - async function requestWithToken(url, token, options = {}) { - const headers = new Headers(); - if (!token || token === "") { - throw new Error("No bearer token"); - } - headers.append("authorization", `Bearer ${token}`); - headers.append("X-Requested-With", "XMLHttpRequest"); - headers.append("Content-Type", "application/json"); - const res = await fetch( - `${BASE_URL}/${url}`, - { - ...options, - credentials: "include", - headers, - }, - true - ); - return res; - } - - async function request(url, options = {}, reauth = false) { + const request = useCallback(async function request(url, options = {}, reauth = false) { let token = user.token; if (reauth) { - const res = await fetch(`${BASE_URL}/auth/refresh`); + const res = await fetch(`${BASE_URL}/auth/refresh`, { signal: options.signal }); const data = await res.json(); + if (options.signal?.aborted) { + throw options.signal.reason; + } if ( res.status == 400 && data.message === "Bad request, no refresh token" @@ -131,18 +129,16 @@ function AuthProvider({ children }) { } } const res = await requestWithToken(url, token, options); - if (res.status == 401) { - if (reauth) { - throw new Error("Unauthorized"); - } + if (res.status === 401 && !reauth) { return request(url, options, true); } - if (!res.ok && !reauth) { - throw new Error("Error fetching data"); + if (!res.ok) { + const failure = new Error("Error fetching data"); + failure.status = res.status; + throw failure; } - const data = await res.json(); - return data; - } + return res.json(); + }, [user, navigate]); return ( { + const [location, setLocation] = useState({ path: "/" }); + const [result, setResult] = useState(null); + const current = result?.location === location ? result : null; + + useEffect(() => { + const controller = new AbortController(); + const query = new URLSearchParams({ path: location.path }); + + async function loadFolder() { + try { + const folder = await request(`file/browse?${query}`, { signal: controller.signal }); + if (!controller.signal.aborted) { + setResult({ location, folder }); + } + } catch (error) { + if (!controller.signal.aborted) { + setResult({ location, error }); + } + } + } + + loadFolder(); + return () => controller.abort(); + }, [location, request]); + + if (current?.error?.status === 403) { + return You don’t have access to a shared folder.; + } + + return ( + setLocation({ path })}> + {!current &&

Loading folder…

} + {current?.error && ( + + {loadErrors[current.error.status] ?? "Unable to load this folder."}{" "} + + + )} +
+ ); +}; + const Homepage = () => { - const { user } = useAuth(); + const { user, request } = useAuth(); const navigate = useNavigate(); useEffect(() => { if (!user) { navigate("/login"); } - }, [user]); + }, [user, navigate]); if (user) { return ( -
+
- +
); - } + } + return null; }; export default Homepage; diff --git a/react/src/views/User/User.jsx b/react/src/views/User/User.jsx index 9629425..f0ad0c0 100644 --- a/react/src/views/User/User.jsx +++ b/react/src/views/User/User.jsx @@ -1,22 +1,28 @@ import styles from "./User.module.scss"; import { useNavigate, useParams } from "react-router"; import { useState, useEffect } from "react"; -import { Row, Col, Container, Button, Form } from "react-bootstrap"; -import FileBrowser from "../../components/FileBrowser/FileBrowser"; +import { Alert, Row, Col, Container, Button, Form } from "react-bootstrap"; +import { FolderTreeBrowser } from "../../components/FileBrowser/FileBrowser"; import { useAPI } from "../../hooks/useAPI"; const User = () => { const [user, setUser] = useState(null); const { get, patch, remove, isLoading } = useAPI(); const [rootPath, setRootPath] = useState(null); + const [rootError, setRootError] = useState(false); const { userId } = useParams(null); const navigate = useNavigate() useEffect(() => { const getRootPath = async () => { - const rootPath = await get("file/root"); - if (rootPath) { - setRootPath(rootPath); + try { + const tree = await get("file/root"); + if (!Array.isArray(tree) || !tree.length) { + throw new Error("Invalid folder tree"); + } + setRootPath(tree); + } catch { + setRootError(true); } }; const getUser = async () => { @@ -29,17 +35,14 @@ const User = () => { getRootPath(); }, []); - const handleSetRootFolder = async (e, path, dir) => { - e.stopPropagation(); - const root = `${path}${path === "/" ? "" : "/"}${dir}`; + const handleSetRootFolder = async (root) => { const patchedUser = await patch("user", userId, { root }); if (patchedUser) { setUser(patchedUser); } }; - const handleUnsetRootFolder = async (e) => { - e.stopPropagation(); + const handleUnsetRootFolder = async () => { const patchedUser = await patch("user", userId, { root: null }); if (patchedUser) { setUser(patchedUser); @@ -96,10 +99,13 @@ const User = () => { - {user && ( - Unable to load assignable folders.} + {user && !rootPath && !rootError &&

Loading assignable folders…

} + {user && rootPath && ( +