TASK-003 Add secure assigned-folder browsing

This commit is contained in:
rob
2026-11-25 20:54:05 +00:00
parent 549f11d9f4
commit 68335d629b
14 changed files with 520 additions and 300 deletions
+102 -160
View File
@@ -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}`)) ? (
<FontAwesomeIcon icon={faFileVideo} className={styles.icon} />
) : (
<FontAwesomeIcon icon={faFile} className={styles.icon} />
);
const FileIcon = ({ fileName }) => (
<FontAwesomeIcon
icon={videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? faFileVideo : faFile}
/>
);
const FileSize = ({ file }) => (
const FileSize = ({ size }) => (
<div className={styles.size}>
{parseInt(file.size / (1024 * 1024))}
{Math.floor(size / (1024 * 1024))}
<span>MB</span>
</div>
);
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 (
<div className={styles.fileBrowser}>
<Breadcrumb>
<Breadcrumb.Item
active={currentPath?.root === "/"}
onClick={() => handleSelectFolderByDepth(0)}
>
Shared Folder
</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 label="Folder path">
{breadcrumbs.map(({ name, target }) => (
<Breadcrumb.Item
key={target}
active={target === path}
linkAs="button"
linkProps={{
type: "button",
className: `btn btn-link p-0 align-baseline ${styles.breadcrumbButton}`,
onClick: () => onNavigate(target),
}}
>
{name}
</Breadcrumb.Item>
))}
</Breadcrumb>
<ListGroup className={styles.fileList}>
{tree && currentPath?.root !== tree[0].root && (
{children}
<ListGroup>
{parent && (
<ListGroup.Item
action
onClick={handleSelectParentFolder}
type="button"
onClick={() => onNavigate(parent.target)}
className={styles.listItem}
aria-label="Parent folder"
>
..
</ListGroup.Item>
)}
{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 = (
<>
<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 (
<ListGroup.Item
action
className={`${styles.listItem} ${styles.dir} ${
isSelected ? styles.selected : ""
}`}
onClick={() => handleSelectFolder(dir)}
type="button"
className={styles.listItem}
onClick={() => onNavigate(target)}
variant="dark"
key={index}
key={name}
>
<div className={styles.iconHolder}>
<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>
{label}
</ListGroup.Item>
);
})}
{currentPath?.files?.map((file, index) => (
<ListGroup.Item
className={`${styles.listItem} ${styles.file}`}
variant="secondary"
key={index}
>
<div className={styles.iconHolder}>
<FileIcon fileName={file.name} />
</div>
<div className={styles.name}>{file.name}</div>
<div className={styles.action}>
<FileSize file={file} />
{onDownloadFile && (
<FontAwesomeIcon
icon={faDownload}
className={`${styles.icon} ${styles.dload}`}
/>
)}
</div>
{folder?.files.map((file) => (
<ListGroup.Item className={styles.listItem} variant="secondary" key={file.name}>
<FileIcon fileName={file.name} />
<span className={styles.name}>{file.name}</span>
<FileSize size={file.size} />
</ListGroup.Item>
))}
</ListGroup>
{folder && folder.dirs.length === 0 && folder.files.length === 0 && (
<p className="mt-3" role="status">This folder is empty.</p>
)}
</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;
@@ -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;
}
+29 -33
View File
@@ -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 (
<AuthContext.Provider
+58 -7
View File
@@ -1,33 +1,84 @@
import styles from "./Homepage.module.scss";
import { useAuth } from "../../contexts/AuthContext";
import { useNavigate } from "react-router";
import { useEffect } from "react";
import { Container, Row, Col } from "react-bootstrap";
import { useEffect, useState } from "react";
import { Alert, Button, Container, Row, Col } from "react-bootstrap";
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 { user } = useAuth();
const { user, request } = useAuth();
const navigate = useNavigate();
useEffect(() => {
if (!user) {
navigate("/login");
}
}, [user]);
}, [user, navigate]);
if (user) {
return (
<main className={styles.homepage}>
<main className={styles.homepage}>
<Container>
<Row>
<Col>
<FileBrowser />
<AssignedFolderBrowser key={user.user_id ?? user.username} request={request} />
</Col>
</Row>
</Container>
</main>
);
}
}
return null;
};
export default Homepage;
+19 -13
View File
@@ -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 = () => {
</Row>
<Row>
<Col>
{user && (
<FileBrowser
{user && rootError && <Alert variant="danger">Unable to load assignable folders.</Alert>}
{user && !rootPath && !rootError && <p role="status">Loading assignable folders…</p>}
{user && rootPath && (
<FolderTreeBrowser
key={userId}
tree={rootPath}
defaultPath={user?.root}
assignedPath={user.root}
onSetRootFolder={handleSetRootFolder}
onUnsetRootFolder={handleUnsetRootFolder}
/>