TASK-003 Add secure assigned-folder browsing
This commit is contained in:
+99
-33
@@ -5,6 +5,7 @@ Symlinks are excluded entirely; media mounts must also be read-only in deploymen
|
|||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import stat
|
import stat
|
||||||
|
from contextlib import contextmanager, ExitStack
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
@@ -13,6 +14,18 @@ class MediaDenied(ValueError):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidFolderPath(MediaDenied):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FolderNotFound(MediaDenied):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MediaUnavailable(MediaDenied):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def media_root():
|
def media_root():
|
||||||
try:
|
try:
|
||||||
root = Path(current_app.config["MEDIA_ROOT"]).resolve(strict=True)
|
root = Path(current_app.config["MEDIA_ROOT"]).resolve(strict=True)
|
||||||
@@ -23,12 +36,27 @@ def media_root():
|
|||||||
raise MediaDenied() from None
|
raise MediaDenied() from None
|
||||||
|
|
||||||
|
|
||||||
def assigned_root(value):
|
def virtual_parts(value):
|
||||||
if not isinstance(value, str) or not value.startswith("/"):
|
if not isinstance(value, str) or not value.startswith("/"):
|
||||||
raise MediaDenied()
|
raise InvalidFolderPath()
|
||||||
parts = value[1:].split("/") if value != "/" else []
|
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()
|
raise MediaDenied()
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
def assigned_root(value):
|
||||||
|
parts = _assignment_parts(value)
|
||||||
root = media_root()
|
root = media_root()
|
||||||
path = root
|
path = root
|
||||||
try:
|
try:
|
||||||
@@ -44,43 +72,81 @@ def assigned_root(value):
|
|||||||
raise MediaDenied() from None
|
raise MediaDenied() from None
|
||||||
|
|
||||||
|
|
||||||
def file_tree(root):
|
@contextmanager
|
||||||
"""List using anchored directory descriptors; never follow swapped links."""
|
def _open_directory(root, parts=()):
|
||||||
tree = []
|
|
||||||
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||||
|
descriptor = os.dup(root) if isinstance(root, int) else os.open(root, flags)
|
||||||
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:
|
try:
|
||||||
visit(child_fd, virtual.rstrip("/") + "/" + name)
|
|
||||||
finally:
|
|
||||||
os.close(child_fd)
|
|
||||||
|
|
||||||
descriptor = None
|
|
||||||
try:
|
|
||||||
base = media_root()
|
|
||||||
parts = root.relative_to(base).parts
|
|
||||||
descriptor = os.open(base, flags)
|
|
||||||
for part in parts:
|
for part in parts:
|
||||||
child_fd = os.open(part, flags, dir_fd=descriptor)
|
child_fd = os.open(part, flags, dir_fd=descriptor)
|
||||||
os.close(descriptor)
|
os.close(descriptor)
|
||||||
descriptor = child_fd
|
descriptor = child_fd
|
||||||
|
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, "/")
|
visit(descriptor, "/")
|
||||||
except (OSError, RuntimeError, ValueError):
|
except (OSError, RuntimeError, ValueError):
|
||||||
raise MediaDenied() from None
|
raise MediaDenied() from None
|
||||||
finally:
|
|
||||||
if descriptor is not None:
|
|
||||||
os.close(descriptor)
|
|
||||||
return tree
|
return tree
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
"""Media routes. Legacy client-directed downloads are deliberately disabled."""
|
"""Media routes. Legacy client-directed downloads are deliberately disabled."""
|
||||||
|
from flask import request
|
||||||
from settings import app
|
from settings import app
|
||||||
from auth import token_auth
|
from auth import token_auth
|
||||||
from errors import error_response
|
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")
|
@app.route("/api/file/root")
|
||||||
@@ -16,6 +25,27 @@ def get_root_path():
|
|||||||
return error_response(503, "Media unavailable")
|
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"])
|
@app.route("/api/file", methods=["POST"])
|
||||||
@token_auth.login_required
|
@token_auth.login_required
|
||||||
def get_file():
|
def get_file():
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ def get_token():
|
|||||||
refresh_token = user.get_refresh_token()
|
refresh_token = user.get_refresh_token()
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
response = make_response(
|
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)
|
response.set_cookie("refresh_token", value=refresh_token, httponly=True)
|
||||||
return response
|
return response
|
||||||
|
|||||||
@@ -65,6 +65,15 @@ class SecurityTests(unittest.TestCase):
|
|||||||
self.assertEqual(data['user_id'], data['id'])
|
self.assertEqual(data['user_id'], data['id'])
|
||||||
self.assertEqual(self.client.get('/api/auth/refresh').get_json()['user_id'], data['user_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):
|
def test_first_login_issues_usable_token(self):
|
||||||
user = User(username='new-admin', is_admin=True, login_disabled=False)
|
user = User(username='new-admin', is_admin=True, login_disabled=False)
|
||||||
user.set_password('test-password')
|
user.set_password('test-password')
|
||||||
@@ -152,6 +161,71 @@ class SecurityTests(unittest.TestCase):
|
|||||||
nested.unlink()
|
nested.unlink()
|
||||||
saved.rename(nested)
|
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):
|
def test_old_download_never_serves_files(self):
|
||||||
for payload in [{'path':str(self.root / 'alice'),'filename':'movie.mp4'}, {'path':'/etc','filename':'passwd'}, {}, None]:
|
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)
|
self.assertEqual(self.client.post('/api/file',json=payload,headers=self.headers('alice')).status_code,410)
|
||||||
|
|||||||
+11
-3
@@ -1,8 +1,8 @@
|
|||||||
# Foldershare current state
|
# Foldershare current state
|
||||||
|
|
||||||
- Updated: 2026-11-25 for TASK-002 integration
|
- Updated: 2026-11-25 for TASK-003 acceptance and integration
|
||||||
- Inspected worktree: `/home/rob/projects/foldershare`
|
- Inspected worktree: `/home/rob/projects/foldershare/.worktrees/TASK-003`
|
||||||
- TASK-002 integration base: `codex` at `cd6d6b3`
|
- TASK-003 base: `codex` at `549f11d`
|
||||||
|
|
||||||
## Verified repository state
|
## 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.
|
- 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.
|
- 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 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.
|
||||||
|
|||||||
@@ -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.
|
- `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.
|
- 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.
|
- `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.
|
||||||
|
|||||||
+26
-4
@@ -1,9 +1,31 @@
|
|||||||
# Foldershare handoff
|
# 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.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Foldershare project overview
|
# 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
|
## 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/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.
|
- `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.
|
- 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.
|
- Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked.
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -50,7 +50,7 @@ The scopes below translate Captain's explicit product requirements into implemen
|
|||||||
|
|
||||||
### TASK-003: Secure folder browsing for assigned users
|
### 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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
|
### TASK-004: Opaque single-file downloading with resume
|
||||||
|
|
||||||
|
|||||||
@@ -1,199 +1,141 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState } from "react";
|
||||||
import styles from "./FileBrowser.module.scss";
|
import styles from "./FileBrowser.module.scss";
|
||||||
import { ListGroup, Breadcrumb } from "react-bootstrap";
|
import { ListGroup, Breadcrumb } from "react-bootstrap";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import {
|
import { faFolder, faFile, faFileVideo, faSquare, faSquareCheck } from "@fortawesome/free-solid-svg-icons";
|
||||||
faFolder,
|
|
||||||
faFile,
|
|
||||||
faFileVideo,
|
|
||||||
faDownload,
|
|
||||||
faSquare,
|
|
||||||
faSquareCheck,
|
|
||||||
} from "@fortawesome/free-solid-svg-icons";
|
|
||||||
|
|
||||||
const videoExtensions = ["mkv", "avi", "mp4"];
|
const videoExtensions = ["mkv", "avi", "mp4"];
|
||||||
const apiBaseUrl = "http://localhost:5173";
|
|
||||||
|
|
||||||
const FileIcon = ({ fileName }) =>
|
const FileIcon = ({ fileName }) => (
|
||||||
videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? (
|
<FontAwesomeIcon
|
||||||
<FontAwesomeIcon icon={faFileVideo} className={styles.icon} />
|
icon={videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? faFileVideo : faFile}
|
||||||
) : (
|
/>
|
||||||
<FontAwesomeIcon icon={faFile} className={styles.icon} />
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const FileSize = ({ file }) => (
|
const FileSize = ({ size }) => (
|
||||||
<div className={styles.size}>
|
<div className={styles.size}>
|
||||||
{parseInt(file.size / (1024 * 1024))}
|
{Math.floor(size / (1024 * 1024))}
|
||||||
<span>MB</span>
|
<span>MB</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
const FileBrowser = ({
|
const FileBrowser = ({ path, folder, onNavigate, assignedPath, onSetRootFolder, onUnsetRootFolder, children }) => {
|
||||||
tree,
|
const segments = path === "/" ? [] : path.slice(1).split("/");
|
||||||
defaultPath,
|
const breadcrumbs = [
|
||||||
onDownloadFile,
|
{ name: "Shared Folder", target: "/" },
|
||||||
onSetRootFolder,
|
...segments.map((name, index) => ({
|
||||||
onUnsetRootFolder
|
name,
|
||||||
}) => {
|
target: `/${segments.slice(0, index + 1).join("/")}`,
|
||||||
const [currentPath, setCurrentPath] = useState(null);
|
})),
|
||||||
|
];
|
||||||
const isUserRoot = () => {
|
const parent = breadcrumbs.at(-2);
|
||||||
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);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.fileBrowser}>
|
<div className={styles.fileBrowser}>
|
||||||
<Breadcrumb>
|
<Breadcrumb label="Folder path">
|
||||||
|
{breadcrumbs.map(({ name, target }) => (
|
||||||
<Breadcrumb.Item
|
<Breadcrumb.Item
|
||||||
active={currentPath?.root === "/"}
|
key={target}
|
||||||
onClick={() => handleSelectFolderByDepth(0)}
|
active={target === path}
|
||||||
|
linkAs="button"
|
||||||
|
linkProps={{
|
||||||
|
type: "button",
|
||||||
|
className: `btn btn-link p-0 align-baseline ${styles.breadcrumbButton}`,
|
||||||
|
onClick: () => onNavigate(target),
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
Shared Folder
|
{name}
|
||||||
</Breadcrumb.Item>
|
</Breadcrumb.Item>
|
||||||
{currentPath?.root.split("/").map((bc, index) =>
|
))}
|
||||||
index > 0 ? (
|
|
||||||
<Breadcrumb.Item
|
|
||||||
key={index}
|
|
||||||
active={
|
|
||||||
index ===
|
|
||||||
currentPath?.root.split("/").length - 1
|
|
||||||
}
|
|
||||||
onClick={() => handleSelectFolderByDepth(index)}
|
|
||||||
>
|
|
||||||
{bc}
|
|
||||||
</Breadcrumb.Item>
|
|
||||||
) : (
|
|
||||||
""
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</Breadcrumb>
|
</Breadcrumb>
|
||||||
<ListGroup className={styles.fileList}>
|
{children}
|
||||||
{tree && currentPath?.root !== tree[0].root && (
|
<ListGroup>
|
||||||
|
{parent && (
|
||||||
<ListGroup.Item
|
<ListGroup.Item
|
||||||
action
|
action
|
||||||
onClick={handleSelectParentFolder}
|
type="button"
|
||||||
|
onClick={() => onNavigate(parent.target)}
|
||||||
className={styles.listItem}
|
className={styles.listItem}
|
||||||
|
aria-label="Parent folder"
|
||||||
>
|
>
|
||||||
..
|
..
|
||||||
</ListGroup.Item>
|
</ListGroup.Item>
|
||||||
)}
|
)}
|
||||||
|
{folder?.dirs.map((name) => {
|
||||||
{currentPath?.dirs?.map((dir, index) => {
|
const target = `${path === "/" ? "" : path}/${name}`;
|
||||||
const isSelected = getDirPath(dir).root === defaultPath;
|
const isAssigned = target === assignedPath;
|
||||||
|
const label = (
|
||||||
|
<>
|
||||||
|
<FontAwesomeIcon icon={faFolder} />
|
||||||
|
<span className={styles.name}>{name}</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
if (onSetRootFolder) {
|
||||||
|
return (
|
||||||
|
<ListGroup.Item
|
||||||
|
className={`${styles.listItem} ${isAssigned ? styles.selected : ""}`}
|
||||||
|
variant="dark"
|
||||||
|
key={name}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={styles.folderButton}
|
||||||
|
onClick={() => onNavigate(target)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={styles.assignmentButton}
|
||||||
|
aria-label={isAssigned ? `Unassign ${name}` : `Assign ${name}`}
|
||||||
|
onClick={isAssigned ? onUnsetRootFolder : () => onSetRootFolder(target)}
|
||||||
|
>
|
||||||
|
<FontAwesomeIcon icon={isAssigned ? faSquareCheck : faSquare} />
|
||||||
|
</button>
|
||||||
|
</ListGroup.Item>
|
||||||
|
);
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<ListGroup.Item
|
<ListGroup.Item
|
||||||
action
|
action
|
||||||
className={`${styles.listItem} ${styles.dir} ${
|
type="button"
|
||||||
isSelected ? styles.selected : ""
|
className={styles.listItem}
|
||||||
}`}
|
onClick={() => onNavigate(target)}
|
||||||
onClick={() => handleSelectFolder(dir)}
|
|
||||||
variant="dark"
|
variant="dark"
|
||||||
key={index}
|
key={name}
|
||||||
>
|
>
|
||||||
<div className={styles.iconHolder}>
|
{label}
|
||||||
<FontAwesomeIcon
|
|
||||||
icon={faFolder}
|
|
||||||
className={styles.icon}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className={styles.name}>{dir}</div>
|
|
||||||
<div className={styles.action}>
|
|
||||||
{onSetRootFolder && isSelected && (
|
|
||||||
<FontAwesomeIcon
|
|
||||||
icon={faSquareCheck}
|
|
||||||
className={`${styles.icon} ${styles.setRoot}`}
|
|
||||||
onClick={(e) => onUnsetRootFolder(e)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{onSetRootFolder && !isSelected && (
|
|
||||||
<FontAwesomeIcon
|
|
||||||
icon={faSquare}
|
|
||||||
className={`${styles.icon} ${styles.setRoot}`}
|
|
||||||
onClick={(e) =>
|
|
||||||
onSetRootFolder(
|
|
||||||
e,
|
|
||||||
currentPath.root,
|
|
||||||
dir
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</ListGroup.Item>
|
</ListGroup.Item>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{folder?.files.map((file) => (
|
||||||
{currentPath?.files?.map((file, index) => (
|
<ListGroup.Item className={styles.listItem} variant="secondary" key={file.name}>
|
||||||
<ListGroup.Item
|
|
||||||
className={`${styles.listItem} ${styles.file}`}
|
|
||||||
variant="secondary"
|
|
||||||
key={index}
|
|
||||||
>
|
|
||||||
<div className={styles.iconHolder}>
|
|
||||||
<FileIcon fileName={file.name} />
|
<FileIcon fileName={file.name} />
|
||||||
</div>
|
<span className={styles.name}>{file.name}</span>
|
||||||
<div className={styles.name}>{file.name}</div>
|
<FileSize size={file.size} />
|
||||||
<div className={styles.action}>
|
|
||||||
<FileSize file={file} />
|
|
||||||
{onDownloadFile && (
|
|
||||||
<FontAwesomeIcon
|
|
||||||
icon={faDownload}
|
|
||||||
className={`${styles.icon} ${styles.dload}`}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</ListGroup.Item>
|
</ListGroup.Item>
|
||||||
))}
|
))}
|
||||||
</ListGroup>
|
</ListGroup>
|
||||||
|
{folder && folder.dirs.length === 0 && folder.files.length === 0 && (
|
||||||
|
<p className="mt-3" role="status">This folder is empty.</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const FolderTreeBrowser = ({ tree, assignedPath, onSetRootFolder, onUnsetRootFolder }) => {
|
||||||
|
const [path, setPath] = useState(assignedPath);
|
||||||
|
const folder = tree.find((entry) => entry.root === path) ?? tree[0];
|
||||||
|
return (
|
||||||
|
<FileBrowser
|
||||||
|
folder={folder}
|
||||||
|
path={folder.root}
|
||||||
|
assignedPath={assignedPath}
|
||||||
|
onNavigate={setPath}
|
||||||
|
onSetRootFolder={onSetRootFolder}
|
||||||
|
onUnsetRootFolder={onUnsetRootFolder}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default FileBrowser;
|
export default FileBrowser;
|
||||||
|
|||||||
@@ -1,47 +1,59 @@
|
|||||||
@import "/src/styles/colors.scss";
|
@import "/src/styles/colors.scss";
|
||||||
|
|
||||||
.fileBrowser {
|
.fileBrowser {
|
||||||
//background-color: map-get($theme-colors, primary);
|
|
||||||
padding-top: 30px;
|
padding-top: 30px;
|
||||||
//border-radius: 5px;
|
}
|
||||||
.fileList {
|
|
||||||
.listItem {
|
.listItem,
|
||||||
|
.folderButton {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
align-items: center;
|
||||||
gap: 20px;
|
gap: 20px;
|
||||||
.icon {
|
min-width: 0;
|
||||||
&.dload,
|
|
||||||
&.setRoot {
|
|
||||||
cursor: pointer;
|
|
||||||
&:hover {
|
|
||||||
color: #2d3dd4;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.name {
|
.name {
|
||||||
width: 100%;
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
.action {
|
|
||||||
width: 100px;
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 10px;
|
|
||||||
.size {
|
.size {
|
||||||
|
flex-shrink: 0;
|
||||||
|
|
||||||
span {
|
span {
|
||||||
margin-left: 5px;
|
margin-left: 5px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.folderButton,
|
||||||
|
.assignmentButton {
|
||||||
|
color: inherit;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
}
|
}
|
||||||
&.selected {
|
|
||||||
|
.folderButton {
|
||||||
|
flex: 1;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assignmentButton:hover {
|
||||||
|
color: #2d3dd4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selected {
|
||||||
background-color: map-get($theme-colors, primary);
|
background-color: map-get($theme-colors, primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fileBrowser :global(.breadcrumb-item) {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
.disabled {
|
|
||||||
pointer-events: none;
|
.breadcrumbButton {
|
||||||
cursor: auto;
|
text-align: left;
|
||||||
}
|
overflow-wrap: anywhere;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/* eslint-disable react-refresh/only-export-components */
|
/* 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 PropTypes from "prop-types";
|
||||||
import { encode as base64_encode } from "base-64";
|
import { encode as base64_encode } from "base-64";
|
||||||
import { useLocalStorage } from "../hooks/useLocalStorage";
|
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 }) {
|
function AuthProvider({ children }) {
|
||||||
const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer(
|
const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer(
|
||||||
reducer,
|
reducer,
|
||||||
@@ -52,7 +67,7 @@ function AuthProvider({ children }) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const user = getLSItems(["user_id", "token", "username", "is_admin"]);
|
const user = getLSItems(["user_id", "token", "username", "is_admin"]);
|
||||||
if (!!user.token && !!user.username) {
|
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" });
|
dispatch({ type: "auth/logout" });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function requestWithToken(url, token, options = {}) {
|
const request = useCallback(async function request(url, options = {}, reauth = false) {
|
||||||
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) {
|
|
||||||
let token = user.token;
|
let token = user.token;
|
||||||
if (reauth) {
|
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();
|
const data = await res.json();
|
||||||
|
if (options.signal?.aborted) {
|
||||||
|
throw options.signal.reason;
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
res.status == 400 &&
|
res.status == 400 &&
|
||||||
data.message === "Bad request, no refresh token"
|
data.message === "Bad request, no refresh token"
|
||||||
@@ -131,18 +129,16 @@ function AuthProvider({ children }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const res = await requestWithToken(url, token, options);
|
const res = await requestWithToken(url, token, options);
|
||||||
if (res.status == 401) {
|
if (res.status === 401 && !reauth) {
|
||||||
if (reauth) {
|
|
||||||
throw new Error("Unauthorized");
|
|
||||||
}
|
|
||||||
return request(url, options, true);
|
return request(url, options, true);
|
||||||
}
|
}
|
||||||
if (!res.ok && !reauth) {
|
if (!res.ok) {
|
||||||
throw new Error("Error fetching data");
|
const failure = new Error("Error fetching data");
|
||||||
}
|
failure.status = res.status;
|
||||||
const data = await res.json();
|
throw failure;
|
||||||
return data;
|
|
||||||
}
|
}
|
||||||
|
return res.json();
|
||||||
|
}, [user, navigate]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
|
|||||||
@@ -1,19 +1,69 @@
|
|||||||
import styles from "./Homepage.module.scss";
|
import styles from "./Homepage.module.scss";
|
||||||
import { useAuth } from "../../contexts/AuthContext";
|
import { useAuth } from "../../contexts/AuthContext";
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
import { useEffect } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { Container, Row, Col } from "react-bootstrap";
|
import { Alert, Button, Container, Row, Col } from "react-bootstrap";
|
||||||
import FileBrowser from "../../components/FileBrowser/FileBrowser";
|
import FileBrowser from "../../components/FileBrowser/FileBrowser";
|
||||||
|
|
||||||
|
const loadErrors = {
|
||||||
|
404: "This folder is no longer available.",
|
||||||
|
503: "The shared folder is temporarily unavailable.",
|
||||||
|
};
|
||||||
|
|
||||||
|
const AssignedFolderBrowser = ({ request }) => {
|
||||||
|
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 <Alert variant="secondary" className="mt-4">You don’t have access to a shared folder.</Alert>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FileBrowser path={location.path} folder={current?.folder} onNavigate={(path) => setLocation({ path })}>
|
||||||
|
{!current && <p role="status">Loading folder…</p>}
|
||||||
|
{current?.error && (
|
||||||
|
<Alert variant="danger">
|
||||||
|
{loadErrors[current.error.status] ?? "Unable to load this folder."}{" "}
|
||||||
|
<Button variant="link" className="p-0" onClick={() => setLocation({ path: location.path })}>
|
||||||
|
Try again
|
||||||
|
</Button>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</FileBrowser>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const Homepage = () => {
|
const Homepage = () => {
|
||||||
const { user } = useAuth();
|
const { user, request } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
navigate("/login");
|
navigate("/login");
|
||||||
}
|
}
|
||||||
}, [user]);
|
}, [user, navigate]);
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
return (
|
return (
|
||||||
@@ -21,13 +71,14 @@ const Homepage = () => {
|
|||||||
<Container>
|
<Container>
|
||||||
<Row>
|
<Row>
|
||||||
<Col>
|
<Col>
|
||||||
<FileBrowser />
|
<AssignedFolderBrowser key={user.user_id ?? user.username} request={request} />
|
||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
</Container>
|
</Container>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Homepage;
|
export default Homepage;
|
||||||
|
|||||||
@@ -1,22 +1,28 @@
|
|||||||
import styles from "./User.module.scss";
|
import styles from "./User.module.scss";
|
||||||
import { useNavigate, useParams } from "react-router";
|
import { useNavigate, useParams } from "react-router";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Row, Col, Container, Button, Form } from "react-bootstrap";
|
import { Alert, Row, Col, Container, Button, Form } from "react-bootstrap";
|
||||||
import FileBrowser from "../../components/FileBrowser/FileBrowser";
|
import { FolderTreeBrowser } from "../../components/FileBrowser/FileBrowser";
|
||||||
import { useAPI } from "../../hooks/useAPI";
|
import { useAPI } from "../../hooks/useAPI";
|
||||||
|
|
||||||
const User = () => {
|
const User = () => {
|
||||||
const [user, setUser] = useState(null);
|
const [user, setUser] = useState(null);
|
||||||
const { get, patch, remove, isLoading } = useAPI();
|
const { get, patch, remove, isLoading } = useAPI();
|
||||||
const [rootPath, setRootPath] = useState(null);
|
const [rootPath, setRootPath] = useState(null);
|
||||||
|
const [rootError, setRootError] = useState(false);
|
||||||
const { userId } = useParams(null);
|
const { userId } = useParams(null);
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getRootPath = async () => {
|
const getRootPath = async () => {
|
||||||
const rootPath = await get("file/root");
|
try {
|
||||||
if (rootPath) {
|
const tree = await get("file/root");
|
||||||
setRootPath(rootPath);
|
if (!Array.isArray(tree) || !tree.length) {
|
||||||
|
throw new Error("Invalid folder tree");
|
||||||
|
}
|
||||||
|
setRootPath(tree);
|
||||||
|
} catch {
|
||||||
|
setRootError(true);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const getUser = async () => {
|
const getUser = async () => {
|
||||||
@@ -29,17 +35,14 @@ const User = () => {
|
|||||||
getRootPath();
|
getRootPath();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSetRootFolder = async (e, path, dir) => {
|
const handleSetRootFolder = async (root) => {
|
||||||
e.stopPropagation();
|
|
||||||
const root = `${path}${path === "/" ? "" : "/"}${dir}`;
|
|
||||||
const patchedUser = await patch("user", userId, { root });
|
const patchedUser = await patch("user", userId, { root });
|
||||||
if (patchedUser) {
|
if (patchedUser) {
|
||||||
setUser(patchedUser);
|
setUser(patchedUser);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUnsetRootFolder = async (e) => {
|
const handleUnsetRootFolder = async () => {
|
||||||
e.stopPropagation();
|
|
||||||
const patchedUser = await patch("user", userId, { root: null });
|
const patchedUser = await patch("user", userId, { root: null });
|
||||||
if (patchedUser) {
|
if (patchedUser) {
|
||||||
setUser(patchedUser);
|
setUser(patchedUser);
|
||||||
@@ -96,10 +99,13 @@ const User = () => {
|
|||||||
</Row>
|
</Row>
|
||||||
<Row>
|
<Row>
|
||||||
<Col>
|
<Col>
|
||||||
{user && (
|
{user && rootError && <Alert variant="danger">Unable to load assignable folders.</Alert>}
|
||||||
<FileBrowser
|
{user && !rootPath && !rootError && <p role="status">Loading assignable folders…</p>}
|
||||||
|
{user && rootPath && (
|
||||||
|
<FolderTreeBrowser
|
||||||
|
key={userId}
|
||||||
tree={rootPath}
|
tree={rootPath}
|
||||||
defaultPath={user?.root}
|
assignedPath={user.root}
|
||||||
onSetRootFolder={handleSetRootFolder}
|
onSetRootFolder={handleSetRootFolder}
|
||||||
onUnsetRootFolder={handleUnsetRootFolder}
|
onUnsetRootFolder={handleUnsetRootFolder}
|
||||||
/>
|
/>
|
||||||
|
|||||||
Reference in New Issue
Block a user