netgescon-day0/app/Http/Controllers/Admin/TicketAttachmentViewController.php

52 lines
1.5 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\TicketAttachment;
use App\Models\User;
use App\Support\StabileContext;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
class TicketAttachmentViewController extends Controller
{
public function show(TicketAttachment $attachment): Response
{
$user = Auth::user();
if (! $user instanceof User) {
abort(403);
}
if (! $user->hasAnyRole(['super-admin', 'admin', 'amministratore', 'collaboratore'])) {
abort(403);
}
$ticket = $attachment->ticket;
if (! $ticket) {
abort(404);
}
$stabileId = StabileContext::resolveActiveStabileId($user);
if (! $stabileId || (int) $ticket->stabile_id !== (int) $stabileId) {
abort(403);
}
$disk = Storage::disk('public');
$path = (string) $attachment->file_path;
if (! $disk->exists($path)) {
abort(404);
}
$absolutePath = $disk->path($path);
$mime = (string) ($attachment->mime_type ?: $disk->mimeType($path) ?: 'application/octet-stream');
return response()->file($absolutePath, [
'Content-Type' => $mime,
'Cache-Control' => 'private, max-age=300',
'Content-Disposition' => 'inline; filename="' . addslashes((string) ($attachment->original_file_name ?: basename($path))) . '"',
]);
}
}