This is a WIP for advanced file sharing, but I won't pursue this for now since using symlinks in the file system works for me, and this is adding a ton of complexity I don't want or need right now.
64 lines
1.9 KiB
TypeScript
64 lines
1.9 KiB
TypeScript
import { Handlers } from 'fresh/server.ts';
|
|
|
|
import { FreshContextState } from '/lib/types.ts';
|
|
import { getFile, getDirectoryAccess, getFileAccess } from '/lib/data/files.ts';
|
|
|
|
interface Data {}
|
|
|
|
export const handler: Handlers<Data, FreshContextState> = {
|
|
async GET(request, context) {
|
|
if (!context.state.user) {
|
|
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
|
|
}
|
|
|
|
const { fileName } = context.params;
|
|
|
|
if (!fileName) {
|
|
return new Response('Not Found', { status: 404 });
|
|
}
|
|
|
|
const searchParams = new URL(request.url).searchParams;
|
|
|
|
let currentPath = searchParams.get('path') || '/';
|
|
|
|
// Send invalid paths back to root
|
|
if (!currentPath.startsWith('/') || currentPath.includes('../')) {
|
|
currentPath = '/';
|
|
}
|
|
|
|
// Always append a trailing slash
|
|
if (!currentPath.endsWith('/')) {
|
|
currentPath = `${currentPath}/`;
|
|
}
|
|
|
|
let { hasWriteAccess, ownerUserId, ownerParentPath } = await getFileAccess(
|
|
context.state.user.id,
|
|
currentPath,
|
|
decodeURIComponent(fileName),
|
|
);
|
|
|
|
if (!hasWriteAccess) {
|
|
const directoryAccessResult = await getDirectoryAccess(context.state.user.id, currentPath);
|
|
|
|
hasWriteAccess = directoryAccessResult.hasWriteAccess;
|
|
ownerUserId = directoryAccessResult.ownerUserId;
|
|
ownerParentPath = directoryAccessResult.ownerParentPath;
|
|
|
|
if (!hasWriteAccess) {
|
|
return new Response('Forbidden', { status: 403 });
|
|
}
|
|
}
|
|
|
|
const fileResult = await getFile(ownerUserId, ownerParentPath, decodeURIComponent(fileName));
|
|
|
|
if (!fileResult.success) {
|
|
return new Response('Not Found', { status: 404 });
|
|
}
|
|
|
|
return new Response(fileResult.contents!, {
|
|
status: 200,
|
|
headers: { 'cache-control': 'no-cache, no-store, must-revalidate', 'content-type': fileResult.contentType! },
|
|
});
|
|
},
|
|
};
|