Skip to content

Commit

Permalink
feat: Implement DownloadController for secure down
Browse files Browse the repository at this point in the history
  • Loading branch information
sweep-ai[bot] committed Mar 11, 2024
1 parent 496d499 commit edeabc3
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions app/Http/Controllers/DownloadController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Http\Controllers;

use App\Models\DownloadableProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DownloadController extends Controller
{
public function generateSecureLink(Request $request, $productId)
{
$downloadableProduct = DownloadableProduct::where('product_id', $productId)->firstOrFail();
if (!$this->checkDownloadLimits($downloadableProduct) || !$this->authorizeDownload($request->user(), $downloadableProduct)) {
abort(403, 'Download limit reached or not authorized.');
}
$temporaryUrl = Storage::disk('local')->temporaryUrl(
$downloadableProduct->file_url, now()->addMinutes(5)
);
return response()->json(['url' => $temporaryUrl]);
}

private function checkDownloadLimits(DownloadableProduct $downloadableProduct)
{
return $downloadableProduct->download_limit > $downloadableProduct->downloads_count && (!$downloadableProduct->expiration_time || $downloadableProduct->expiration_time->isFuture());
}

public function serveFile(Request $request, $productId)
{
$downloadableProduct = DownloadableProduct::where('product_id', $productId)->firstOrFail();
if (!$this->checkDownloadLimits($downloadableProduct) || !$this->authorizeDownload($request->user(), $downloadableProduct)) {
abort(403, 'Download limit reached or not authorized.');
}
$downloadableProduct->increment('downloads_count');
return Storage::disk('local')->download($downloadableProduct->file_url);
}

private function authorizeDownload($user, DownloadableProduct $downloadableProduct)
{
// Implement logic to verify user's purchase
return true; // Placeholder for purchase verification logic
}
}

0 comments on commit edeabc3

Please sign in to comment.