69 lines
1.8 KiB
PHP
69 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Policies;
|
|
|
|
use App\Models\Attachment;
|
|
use App\Models\User;
|
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
|
|
|
class AttachmentPolicy
|
|
{
|
|
use HandlesAuthorization;
|
|
|
|
/**
|
|
* Determine whether the user can view the attachment.
|
|
*/
|
|
public function view(User $user, Attachment $attachment): bool
|
|
{
|
|
// Admin can view all
|
|
if ($user->hasRole('admin')) {
|
|
return true;
|
|
}
|
|
|
|
// Check tenant scope
|
|
if ($attachment->tenant_id && $attachment->tenant_id !== session('tenant_id')) {
|
|
return false;
|
|
}
|
|
|
|
// Check if user can view the parent model
|
|
if ($attachment->attachable) {
|
|
try {
|
|
return $user->can('view', $attachment->attachable);
|
|
} catch (\Throwable $e) {
|
|
return true; // If no policy exists for parent model, allow
|
|
}
|
|
}
|
|
|
|
// User who uploaded can view
|
|
return $attachment->user_id === $user->id;
|
|
}
|
|
|
|
/**
|
|
* Determine whether the user can delete the attachment.
|
|
*/
|
|
public function delete(User $user, Attachment $attachment): bool
|
|
{
|
|
// Admin can delete all
|
|
if ($user->hasRole('admin')) {
|
|
return true;
|
|
}
|
|
|
|
// Check tenant scope
|
|
if ($attachment->tenant_id && $attachment->tenant_id !== session('tenant_id')) {
|
|
return false;
|
|
}
|
|
|
|
// Check if user can update the parent model
|
|
if ($attachment->attachable) {
|
|
try {
|
|
return $user->can('update', $attachment->attachable);
|
|
} catch (\Throwable $e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// User who uploaded can delete
|
|
return $attachment->user_id === $user->id;
|
|
}
|
|
}
|