coolify/app/Livewire/Admin/Index.php
Aditya Tripathi e52390ec03 fix(team): resolve stored team on deletion and impersonation
Use resolveStoredTeam() instead of teams()->first() when picking the
next active team after a team deletion or when an admin switches into
a user's account, so a valid stored preference wins over an arbitrary
first team. DeleteTeam now returns null when the deletion leaves the
owner with multiple teams, deferring to the selection screen instead
of guessing. refreshSession also stops persisting current_team_id
while impersonating, so viewing another user's account no longer
overwrites their real last-active team.
2026-09-08 14:44:42 +02:00

97 lines
2.5 KiB
PHP

<?php
namespace App\Livewire\Admin;
use App\Models\Team;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Index extends Component
{
public int $activeSubscribers;
public int $inactiveSubscribers;
public Collection $foundUsers;
public string $search = '';
public function mount()
{
if (! isCloud() && ! isDev()) {
abort(403);
}
$this->authorizeAdminAccess();
$this->getSubscribers();
}
public function back()
{
$this->authorizeAdminAccess();
if (session('impersonating')) {
session()->forget('impersonating');
$user = User::find(0);
$team_to_switch_to = $user->resolveStoredTeam() ?? $user->teams->first();
Auth::login($user);
refreshSession($team_to_switch_to);
return redirect()->route('admin.index');
}
}
public function submitSearch()
{
$this->authorizeAdminAccess();
if ($this->search !== '') {
$this->foundUsers = User::where(function ($query) {
$query->where('name', 'like', "%{$this->search}%")
->orWhere('email', 'like', "%{$this->search}%");
})->get();
}
}
public function getSubscribers()
{
if (Auth::id() !== 0 && ! session('impersonating')) {
return redirect()->route('dashboard');
}
$this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count();
$this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count();
}
public function switchUser(int $user_id)
{
$this->authorizeRootOnly();
session(['impersonating' => true]);
$user = User::find($user_id);
if (! $user) {
abort(404);
}
$team_to_switch_to = $user->resolveStoredTeam() ?? $user->teams->first();
Auth::login($user);
refreshSession($team_to_switch_to);
return redirect()->route('dashboard');
}
private function authorizeAdminAccess(): void
{
if (! Auth::check() || (Auth::id() !== 0 && ! session('impersonating'))) {
abort(403);
}
}
private function authorizeRootOnly(): void
{
if (! Auth::check() || Auth::id() !== 0) {
abort(403);
}
}
public function render()
{
return view('livewire.admin.index');
}
}