Download with auth
Middleware
import express, { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
const authenticate = (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Unauthorized: No token provided' });
}
try {
// Replace 'your_secret_key' with your actual JWT secret key
const user = jwt.verify(token, 'your_secret_key');
req.user = user;
next();
} catch (error) {
res.status(403).json({ message: 'Forbidden: Invalid token' });
}
};
Route with protection
app.get('/download/:fileName', authenticate, (req: Request, res: Response) => {
const { fileName } = req.params;
const filePath = path.join(__dirname, 'uploads', fileName);
// Check if file exists
if (!fs.existsSync(filePath)) {
return res.status(404).send('File not found');
}
// Send the file as a response
res.download(filePath, (err) => {
if (err) {
console.error('Error sending file:', err);
res.status(500).send('Error downloading file');
}
});
});
curl command with auth header
wget --header="Authorization: Bearer YOUR_TOKEN" http://localhost:3000/download/filename.pdf