Working on presigned urls in local.

This commit is contained in:
charles-gauthereau
2024-11-28 20:28:00 +01:00
parent 319662e39c
commit feb10603e9
9 changed files with 134 additions and 7 deletions
+9 -3
View File
@@ -1,6 +1,7 @@
import {prisma} from "@/prisma";
import {NextResponse} from "next/server";
import {NextRequest, NextResponse} from "next/server";
import {Dbms} from "@prisma/client";
import {getFileUrlPresignedLocal} from "@/features/upload/private/upload.action";
// Regular expression for UUIDv4
const uuidv4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -19,7 +20,12 @@ export type Body = {
dbms: Dbms,
generatedId: string
}
export async function GET(request: Request) {
const url = await getFileUrlPresignedLocal("d4a7fa35-2506-4d01-a612-a8ef2e2cc1c5.dump")
return Response.json({
message: url
})
}
export async function POST(
request: Request,
@@ -52,7 +58,7 @@ export async function POST(
const database = await prisma.database.findFirst({
where: {
generatedId: body.name,
generatedId: body.generatedId,
}
})
+61
View File
@@ -0,0 +1,61 @@
import * as fs from "node:fs";
import {NextResponse} from "next/server";
import path from "path";
export async function GET(
request: Request,
{params}: { params: Promise<{ fileName: string }> }
) {
// Retrieve params
const {searchParams} = new URL(request.url);
const token = searchParams.get('token');
const expires = searchParams.get('expires');
const fileName = (await params).fileName
const privateLocalDir = "private/uploads/";
const filePath = path.join(privateLocalDir, fileName);
const crypto = require('crypto');
if (!fs.existsSync(filePath)) {
return NextResponse.json(
{error: 'File not found'},
{status: 404}
);
}
const expectedToken = crypto.createHash('sha256').update(`${fileName}${expires}`).digest('hex');
if (token !== expectedToken) {
return NextResponse.json(
{error: 'Invalid signed token'},
{status: 403}
);
}
const expiresAt = parseInt(expires, 10);
if (Date.now() > expiresAt) {
return NextResponse.json(
{error: 'Signed token expired'},
{status: 403}
);
}
const fileStream = fs.createReadStream(filePath);
const stream = new ReadableStream({
start(controller) {
fileStream.on('data', (chunk) => controller.enqueue(chunk));
fileStream.on('end', () => controller.close());
fileStream.on('error', (err) => controller.error(err));
},
});
return new NextResponse(stream, {
headers: {
'Content-Disposition': `attachment; filename="${fileName}"`,
'Content-Type': 'application/octet-stream',
},
});
}
+14 -2
View File
@@ -4,7 +4,14 @@ import {errorHandler} from "@/middleware/errorHandler";
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone();
// Exclude `/api/auth` and its subpaths
if (url.pathname.startsWith('/api/auth')) {
return NextResponse.next();
}
if (url.pathname.startsWith('/api')) {
const routeExists = checkRouteExists(url.pathname);
// If the route does not exist, return a 404 JSON response
if (!routeExists) {
@@ -31,10 +38,15 @@ function checkRouteExists(pathname) {
// /^\/api\/auth\/\w+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123)
// /^\/api\/agent\/healthcheck\/\w+$/, // Dynamic route with an alphanumeric parameter (e.g., /api/user/username)
/^\/api\/agent\/[^/]+\/status\/?$/, // Dynamic route for /api/agent/[id]/status
/^\/api\/logs\$/,
/^\/api\/files\/[^/]+\/?$/,
];
return routePatterns.some(pattern => pattern.test(pathname));
}
export const config = {
matcher: ['/api/agent/:path*'],
matcher: [
// '/api/agent/:path*',
'/api/:path*',
],
};
@@ -3,7 +3,7 @@ import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import {User} from "@prisma/client";
import {UploadIcon} from "lucide-react";
import {toast} from "sonner";
import {uploadImageAction} from "@/features/upload/upload.action";
import {uploadImageAction} from "@/features/upload/public/upload.action";
import {useMutation} from "@tanstack/react-query";
import {prisma} from "@/prisma";
import {updateImageUserAction} from "@/components/wrappers/Dashboard/Profile/Avatar/avatar.action";
@@ -7,7 +7,7 @@ import {useState} from "react";
import {Settings} from "@prisma/client";
import {ButtonWithLoading} from "@/components/wrappers/Button/ButtonWithLoading/ButtonWithLoading";
import {useMutation} from "@tanstack/react-query";
import {checkConnexionToS3} from "@/features/upload/upload.action";
import {checkConnexionToS3} from "@/features/upload/public/upload.action";
import {toast} from "sonner";
import {updateUserAction} from "@/components/wrappers/Dashboard/Profile/UserForm/user-form.action";
import {useRouter} from "next/navigation";
@@ -0,0 +1,45 @@
"use server"
import {mkdir} from "fs/promises";
import path from "path";
import * as fs from "node:fs";
import {getServerUrl} from "@/utils/get-server-url";
// async function uploadLocalPrivate(fileName: string, buffer: any) {
// const localDir = "public/uploads/"
// try {
// await mkdir(path.join(process.cwd(), localDir), { recursive: true });
// return await writeFile(
// path.join(process.cwd(), localDir + fileName),
// buffer
// )
//
// } catch (error) {
// console.log("Error occured ", error);
// throw new Error('An error occured while importing image');
//
// }
// }
const privateLocalDir = "private/uploads/";
export async function getFileUrlPresignedLocal(fileName: string) {
try {
const filePath = path.join(privateLocalDir, fileName);
await mkdir(path.join(process.cwd(), privateLocalDir), { recursive: true });
if (!fs.existsSync(filePath)) {
console.error('File not found at:', filePath);
return `File not found at: ${filePath}`
}
const crypto = require('crypto');
const baseUrl = getServerUrl();
const expiresAt = Date.now() + 60 * 1000; // expires in 1 minute
const token = crypto.createHash('sha256').update(`${fileName}${expiresAt}`).digest('hex');
return `${baseUrl}/api/files/${fileName}?token=${token}&expires=${expiresAt}`;
} catch (error) {
throw error;
}
}
+3
View File
@@ -4,5 +4,8 @@ export const getServerUrl = () => {
if (typeof window !== 'undefined') {
return window.location.origin;
}
if(env.NODE_ENV === 'development') {
return `http://${env.NEXT_PUBLIC_DOMAIN_NAME}`;
}
return `https://${env.NEXT_PUBLIC_DOMAIN_NAME}`;
}