mirror of
https://git.v0id.ovh/n3wt-innov/n3wt-school.git
synced 2026-04-06 13:11:25 +00:00
feat: Securisation du téléchargement de fichier
This commit is contained in:
54
Front-End/src/pages/api/download.js
Normal file
54
Front-End/src/pages/api/download.js
Normal file
@ -0,0 +1,54 @@
|
||||
import { getToken } from 'next-auth/jwt';
|
||||
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
|
||||
export default async function handler(req, res) {
|
||||
if (req.method !== 'GET') {
|
||||
return res.status(405).json({ error: 'Method not allowed' });
|
||||
}
|
||||
|
||||
const token = await getToken({
|
||||
req,
|
||||
secret: process.env.AUTH_SECRET,
|
||||
cookieName: 'n3wtschool_session_token',
|
||||
});
|
||||
if (!token?.token) {
|
||||
return res.status(401).json({ error: 'Non authentifié' });
|
||||
}
|
||||
|
||||
const { path } = req.query;
|
||||
if (!path) {
|
||||
return res.status(400).json({ error: 'Le paramètre "path" est requis' });
|
||||
}
|
||||
|
||||
try {
|
||||
const backendUrl = `${BACKEND_URL}/Common/serve-file/?path=${encodeURIComponent(path)}`;
|
||||
|
||||
const backendRes = await fetch(backendUrl, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token.token}`,
|
||||
Connection: 'close',
|
||||
},
|
||||
});
|
||||
|
||||
if (!backendRes.ok) {
|
||||
return res.status(backendRes.status).json({
|
||||
error: `Erreur backend: ${backendRes.status}`,
|
||||
});
|
||||
}
|
||||
|
||||
const contentType =
|
||||
backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
const contentDisposition = backendRes.headers.get('content-disposition');
|
||||
|
||||
res.setHeader('Content-Type', contentType);
|
||||
if (contentDisposition) {
|
||||
res.setHeader('Content-Disposition', contentDisposition);
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await backendRes.arrayBuffer());
|
||||
return res.send(buffer);
|
||||
} catch {
|
||||
return res.status(500).json({ error: 'Erreur lors du téléchargement' });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user