SPB Git

Repository Public

route.ts 4.4 KB 115 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPB Private Cloud8 * File             : app/api/v1/files/route.ts9 * Module           : app10 * Repository       : https://git.spboucher.ai/spb-cloud11 * Project Website  : https://cloud.spboucher.ai12 * Created          : 2026-02-1813 * Last Modified    : 2026-02-2114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { NextRequest, NextResponse } from "next/server";43import { prisma } from "@/lib/prisma";44import { saveFile } from "@/lib/storage";45import { createHash } from "crypto";46import mime from "mime-types";4748async function validateApiKey(request: NextRequest) {49  const auth = request.headers.get("authorization");50  if (!auth?.startsWith("Bearer ")) return null;51  const rawKey = auth.substring(7);52  const keyHash = createHash("sha256").update(rawKey).digest("hex");53  const apiKey = await prisma.apiKey.findUnique({ where: { keyHash } });54  if (!apiKey) return null;55  if (apiKey.expiresAt && apiKey.expiresAt < new Date()) return null;56  await prisma.apiKey.update({ where: { id: apiKey.id }, data: { lastUsedAt: new Date() } });57  return apiKey;58}5960export async function GET(request: NextRequest) {61  const apiKey = await validateApiKey(request);62  if (!apiKey) return NextResponse.json({ error: "Invalid API key" }, { status: 401 });6364  const { searchParams } = new URL(request.url);65  const folderId = searchParams.get("folderId");66  const where: Record<string, unknown> = {};67  if (folderId && folderId !== "root") where.folderId = folderId;68  else if (!folderId) where.folderId = null;6970  const files = await prisma.file.findMany({71    where,72    select: { id: true, name: true, size: true, mimeType: true, createdAt: true, folderId: true },73    orderBy: { createdAt: "desc" },74    take: 100,75  });7677  return NextResponse.json({ files: files.map((f) => ({ ...f, size: Number(f.size) })) });78}7980export async function POST(request: NextRequest) {81  const apiKey = await validateApiKey(request);82  if (!apiKey) return NextResponse.json({ error: "Invalid API key" }, { status: 401 });83  if (!apiKey.permissions.includes("write") && !apiKey.permissions.includes("admin")) {84    return NextResponse.json({ error: "API key does not have write permission" }, { status: 403 });85  }8687  const formData = await request.formData();88  const file = formData.get("file") as File | null;89  const folderId = formData.get("folderId") as string | null;9091  if (!file) return NextResponse.json({ error: "No file provided" }, { status: 400 });9293  const maxSize = parseInt(process.env.MAX_FILE_SIZE || "524288000");94  if (file.size > maxSize) {95    return NextResponse.json({ error: `File too large. Max ${Math.round(maxSize / 1024 / 1024)}MB` }, { status: 413 });96  }9798  const buffer = Buffer.from(await file.arrayBuffer());99  const mimeType = mime.lookup(file.name) || file.type || "application/octet-stream";100  const { storagePath, size } = await saveFile(buffer, file.name);101102  const dbFile = await prisma.file.create({103    data: {104      name: file.name,105      storagePath,106      size: BigInt(size),107      mimeType,108      userId: apiKey.userId,109      folderId: folderId && folderId !== "root" ? folderId : null,110    },111  });112113  return NextResponse.json({ ...dbFile, size: Number(dbFile.size) }, { status: 201 });114}115
Files main
Menu

Theme