Refactor Member component to handle authorization checks and error handling

This commit is contained in:
Andras Bacsai
2024-10-28 10:47:29 +01:00
parent 66e9afd859
commit a4b4b93b30

View File

@@ -4,39 +4,65 @@ namespace App\Livewire\Team;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Livewire\Attributes\Locked;
use Livewire\Component; use Livewire\Component;
class Member extends Component class Member extends Component
{ {
#[Locked]
public User $member; public User $member;
public function makeAdmin() public function makeAdmin()
{ {
try {
if (! auth()->user()->isAdmin()) {
throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'admin']); $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'admin']);
$this->dispatch('reloadWindow'); $this->dispatch('reloadWindow');
} catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
} }
public function makeOwner() public function makeOwner()
{ {
try {
if (! auth()->user()->isOwner()) {
throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'owner']); $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'owner']);
$this->dispatch('reloadWindow'); $this->dispatch('reloadWindow');
} catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
} }
public function makeReadonly() public function makeReadonly()
{ {
try {
if (! auth()->user()->isAdmin()) {
throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'member']); $this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => 'member']);
$this->dispatch('reloadWindow'); $this->dispatch('reloadWindow');
} catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
} }
public function remove() public function remove()
{ {
try {
if (! auth()->user()->isAdmin()) {
throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->detach(currentTeam()); $this->member->teams()->detach(currentTeam());
Cache::forget("team:{$this->member->id}"); Cache::forget("team:{$this->member->id}");
Cache::remember('team:'.$this->member->id, 3600, function () { Cache::remember('team:'.$this->member->id, 3600, function () {
return $this->member->teams()->first(); return $this->member->teams()->first();
}); });
$this->dispatch('reloadWindow'); $this->dispatch('reloadWindow');
} catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
} }
} }