Add shared file storage with folder tree, permissions, and file manager UI

New document hub for centralized file storage — replaces scattered
drives and USB sticks for non-technical SMBs. Three new tables:
storage_folder (nested hierarchy), storage_folder_permission (role
and user-level access control), storage_file.

Backend: folder CRUD with nested paths, file upload/download via
signed URLs, permission checks (view/edit/admin with inheritance
from parent folders), public/private toggle, breadcrumb navigation,
file search.

Frontend: two-panel file manager — collapsible folder tree on left,
icon grid view on right. Folder icons by type, file size display,
upload button, context menu for download/delete. Breadcrumb nav.
Files sidebar link added.
This commit is contained in:
Ryan Moon
2026-03-29 15:31:20 -05:00
parent d36c6f7135
commit 0f6cc104d2
13 changed files with 1093 additions and 1 deletions

View File

@@ -0,0 +1,277 @@
import { eq, and, count, ilike, inArray, or, isNull, type Column } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import { storageFolders, storageFolderPermissions, storageFiles } from '../db/schema/storage.js'
import { userRoles } from '../db/schema/rbac.js'
import type { StorageProvider } from '../storage/index.js'
import { randomUUID } from 'crypto'
import { withPagination, withSort, buildSearchCondition, paginatedResponse } from '../utils/pagination.js'
import type { PaginationInput } from '@forte/shared/schemas'
function getExtension(contentType: string): string {
const map: Record<string, string> = {
'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp',
'application/pdf': 'pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/msword': 'doc', 'application/vnd.ms-excel': 'xls',
'text/plain': 'txt', 'text/csv': 'csv',
}
return map[contentType] ?? contentType.split('/')[1] ?? 'bin'
}
// --- Permission Service ---
export const StoragePermissionService = {
async canAccess(db: PostgresJsDatabase<any>, folderId: string, userId: string): Promise<boolean> {
// Check if folder is public
const [folder] = await db.select({ isPublic: storageFolders.isPublic }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (!folder) return false
if (folder.isPublic) return true
// Check direct user permission
const [userPerm] = await db.select({ id: storageFolderPermissions.id }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
.limit(1)
if (userPerm) return true
// Check role-based permission
const userRoleIds = await db.select({ roleId: userRoles.roleId }).from(userRoles).where(eq(userRoles.userId, userId))
if (userRoleIds.length > 0) {
const roleIds = userRoleIds.map((r) => r.roleId)
const [rolePerm] = await db.select({ id: storageFolderPermissions.id }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), inArray(storageFolderPermissions.roleId, roleIds)))
.limit(1)
if (rolePerm) return true
}
// Check parent folder (inherited permissions)
const [parentFolder] = await db.select({ parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (parentFolder?.parentId) {
return this.canAccess(db, parentFolder.parentId, userId)
}
return false
},
async getAccessLevel(db: PostgresJsDatabase<any>, folderId: string, userId: string): Promise<'admin' | 'edit' | 'view' | null> {
const [folder] = await db.select({ isPublic: storageFolders.isPublic, createdBy: storageFolders.createdBy }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (!folder) return null
// Creator always has admin
if (folder.createdBy === userId) return 'admin'
// Check direct user permission
const [userPerm] = await db.select({ accessLevel: storageFolderPermissions.accessLevel }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
.limit(1)
if (userPerm) return userPerm.accessLevel
// Check role-based permission
const userRoleIds = await db.select({ roleId: userRoles.roleId }).from(userRoles).where(eq(userRoles.userId, userId))
if (userRoleIds.length > 0) {
const roleIds = userRoleIds.map((r) => r.roleId)
const [rolePerm] = await db.select({ accessLevel: storageFolderPermissions.accessLevel }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), inArray(storageFolderPermissions.roleId, roleIds)))
.limit(1)
if (rolePerm) return rolePerm.accessLevel
}
// Check parent (inherited)
const [parentFolder] = await db.select({ parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (parentFolder?.parentId) {
return this.getAccessLevel(db, parentFolder.parentId, userId)
}
// Public folders give view access
if (folder.isPublic) return 'view'
return null
},
async listPermissions(db: PostgresJsDatabase<any>, folderId: string) {
return db.select().from(storageFolderPermissions).where(eq(storageFolderPermissions.folderId, folderId))
},
async setPermission(db: PostgresJsDatabase<any>, folderId: string, roleId: string | undefined, userId: string | undefined, accessLevel: string) {
// Remove existing permission for this role/user on this folder
if (roleId) {
await db.delete(storageFolderPermissions).where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.roleId, roleId)))
}
if (userId) {
await db.delete(storageFolderPermissions).where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
}
const [perm] = await db.insert(storageFolderPermissions).values({
folderId,
roleId: roleId ?? null,
userId: userId ?? null,
accessLevel: accessLevel as any,
}).returning()
return perm
},
async removePermission(db: PostgresJsDatabase<any>, permissionId: string) {
const [perm] = await db.delete(storageFolderPermissions).where(eq(storageFolderPermissions.id, permissionId)).returning()
return perm ?? null
},
}
// --- Folder Service ---
export const StorageFolderService = {
async create(db: PostgresJsDatabase<any>, input: { name: string; parentId?: string; isPublic?: boolean; createdBy?: string }) {
// Build materialized path
let path = '/'
if (input.parentId) {
const [parent] = await db.select({ path: storageFolders.path, name: storageFolders.name }).from(storageFolders).where(eq(storageFolders.id, input.parentId)).limit(1)
if (parent) path = `${parent.path}${parent.name}/`
}
const [folder] = await db.insert(storageFolders).values({
name: input.name,
parentId: input.parentId ?? null,
path,
isPublic: input.isPublic ?? true,
createdBy: input.createdBy ?? null,
}).returning()
return folder
},
async getById(db: PostgresJsDatabase<any>, id: string) {
const [folder] = await db.select().from(storageFolders).where(eq(storageFolders.id, id)).limit(1)
return folder ?? null
},
async listChildren(db: PostgresJsDatabase<any>, parentId: string | null) {
const where = parentId ? eq(storageFolders.parentId, parentId) : isNull(storageFolders.parentId)
return db.select().from(storageFolders).where(where).orderBy(storageFolders.name)
},
async listAllAccessible(db: PostgresJsDatabase<any>, userId: string) {
// Get all folders and filter by access — for the tree view
const allFolders = await db.select().from(storageFolders).orderBy(storageFolders.name)
// For each folder, check access (this is simplified — in production you'd optimize with a single query)
const accessible = []
for (const folder of allFolders) {
if (folder.isPublic || folder.createdBy === userId) {
accessible.push(folder)
continue
}
const hasAccess = await StoragePermissionService.canAccess(db, folder.id, userId)
if (hasAccess) accessible.push(folder)
}
return accessible
},
async update(db: PostgresJsDatabase<any>, id: string, input: { name?: string; isPublic?: boolean }) {
const [folder] = await db.update(storageFolders).set({ ...input, updatedAt: new Date() }).where(eq(storageFolders.id, id)).returning()
return folder ?? null
},
async delete(db: PostgresJsDatabase<any>, id: string) {
// CASCADE handles permissions and files via FK
const [folder] = await db.delete(storageFolders).where(eq(storageFolders.id, id)).returning()
return folder ?? null
},
async getBreadcrumbs(db: PostgresJsDatabase<any>, folderId: string): Promise<{ id: string; name: string }[]> {
const crumbs: { id: string; name: string }[] = []
let currentId: string | null = folderId
while (currentId) {
const [folder] = await db.select({ id: storageFolders.id, name: storageFolders.name, parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, currentId)).limit(1)
if (!folder) break
crumbs.unshift({ id: folder.id, name: folder.name })
currentId = folder.parentId
}
return crumbs
},
}
// --- File Service ---
export const StorageFileService = {
async upload(db: PostgresJsDatabase<any>, storage: StorageProvider, input: {
folderId: string
data: Buffer
filename: string
contentType: string
uploadedBy?: string
}) {
const fileId = randomUUID()
const ext = getExtension(input.contentType)
const storagePath = `storage/${input.folderId}/${fileId}.${ext}`
await storage.put(storagePath, input.data, input.contentType)
const [file] = await db.insert(storageFiles).values({
id: fileId,
folderId: input.folderId,
filename: input.filename,
path: storagePath,
contentType: input.contentType,
sizeBytes: input.data.length,
uploadedBy: input.uploadedBy ?? null,
}).returning()
return file
},
async listByFolder(db: PostgresJsDatabase<any>, folderId: string, params: PaginationInput) {
const baseWhere = eq(storageFiles.folderId, folderId)
const searchCondition = params.q
? buildSearchCondition(params.q, [storageFiles.filename])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
filename: storageFiles.filename,
size_bytes: storageFiles.sizeBytes,
created_at: storageFiles.createdAt,
}
let query = db.select().from(storageFiles).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, storageFiles.filename)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(storageFiles).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async getById(db: PostgresJsDatabase<any>, id: string) {
const [file] = await db.select().from(storageFiles).where(eq(storageFiles.id, id)).limit(1)
return file ?? null
},
async delete(db: PostgresJsDatabase<any>, storage: StorageProvider, id: string) {
const file = await this.getById(db, id)
if (!file) return null
await storage.delete(file.path)
const [deleted] = await db.delete(storageFiles).where(eq(storageFiles.id, id)).returning()
return deleted ?? null
},
async search(db: PostgresJsDatabase<any>, query: string, params: PaginationInput) {
const searchCondition = buildSearchCondition(query, [storageFiles.filename])
if (!searchCondition) return paginatedResponse([], 0, params.page, params.limit)
const sortableColumns: Record<string, Column> = {
filename: storageFiles.filename,
created_at: storageFiles.createdAt,
}
let q = db.select().from(storageFiles).where(searchCondition).$dynamic()
q = withSort(q, params.sort, params.order, sortableColumns, storageFiles.filename)
q = withPagination(q, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
q,
db.select({ total: count() }).from(storageFiles).where(searchCondition),
])
return paginatedResponse(data, total, params.page, params.limit)
},
}