Compare commits
2 Commits
dev
...
069-tenant
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21df2056f1 | ||
|
|
458a94c6e9 |
@ -1,6 +1,5 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
vendor/
|
vendor/
|
||||||
coverage/
|
|
||||||
.git/
|
.git/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|||||||
4
.github/agents/copilot-instructions.md
vendored
4
.github/agents/copilot-instructions.md
vendored
@ -14,8 +14,6 @@ ## Active Technologies
|
|||||||
- PHP 8.4.15 (Laravel 12.47.0) + Filament v5.0.0, Livewire v4.0.1 (058-tenant-ui-polish)
|
- PHP 8.4.15 (Laravel 12.47.0) + Filament v5.0.0, Livewire v4.0.1 (058-tenant-ui-polish)
|
||||||
- PHP 8.4 (per repo guidelines) + Laravel 12, Filament v5, Livewire v4 (067-rbac-troubleshooting)
|
- PHP 8.4 (per repo guidelines) + Laravel 12, Filament v5, Livewire v4 (067-rbac-troubleshooting)
|
||||||
- PostgreSQL (via Laravel Sail) (067-rbac-troubleshooting)
|
- PostgreSQL (via Laravel Sail) (067-rbac-troubleshooting)
|
||||||
- PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x (073-unified-managed-tenant-onboarding-wizard)
|
|
||||||
- PostgreSQL (Sail) + SQLite in tests where applicable (073-unified-managed-tenant-onboarding-wizard)
|
|
||||||
|
|
||||||
- PHP 8.4.15 (feat/005-bulk-operations)
|
- PHP 8.4.15 (feat/005-bulk-operations)
|
||||||
|
|
||||||
@ -35,9 +33,9 @@ ## Code Style
|
|||||||
PHP 8.4.15: Follow standard conventions
|
PHP 8.4.15: Follow standard conventions
|
||||||
|
|
||||||
## Recent Changes
|
## Recent Changes
|
||||||
- 073-unified-managed-tenant-onboarding-wizard: Added PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x
|
|
||||||
- 067-rbac-troubleshooting: Added PHP 8.4 (per repo guidelines) + Laravel 12, Filament v5, Livewire v4
|
- 067-rbac-troubleshooting: Added PHP 8.4 (per repo guidelines) + Laravel 12, Filament v5, Livewire v4
|
||||||
- 058-tenant-ui-polish: Added PHP 8.4.15 (Laravel 12.47.0) + Filament v5.0.0, Livewire v4.0.1
|
- 058-tenant-ui-polish: Added PHP 8.4.15 (Laravel 12.47.0) + Filament v5.0.0, Livewire v4.0.1
|
||||||
|
- 058-tenant-ui-polish: Added [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
|
||||||
|
|
||||||
|
|
||||||
<!-- MANUAL ADDITIONS START -->
|
<!-- MANUAL ADDITIONS START -->
|
||||||
|
|||||||
@ -34,6 +34,6 @@ private function resolveTenant(): Tenant
|
|||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Tenant::currentOrFail();
|
return Tenant::current();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -138,7 +138,7 @@ private function resolveTenants()
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return collect([Tenant::currentOrFail()]);
|
return collect([Tenant::current()]);
|
||||||
} catch (RuntimeException) {
|
} catch (RuntimeException) {
|
||||||
return collect();
|
return collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,172 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Pages;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Actions\Action;
|
|
||||||
use Filament\Forms\Components\TextInput;
|
|
||||||
use Filament\Notifications\Notification;
|
|
||||||
use Filament\Pages\Page;
|
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
|
||||||
|
|
||||||
class ChooseWorkspace extends Page
|
|
||||||
{
|
|
||||||
protected static string $layout = 'filament-panels::components.layout.simple';
|
|
||||||
|
|
||||||
protected static bool $shouldRegisterNavigation = false;
|
|
||||||
|
|
||||||
protected static bool $isDiscovered = false;
|
|
||||||
|
|
||||||
protected static ?string $slug = 'choose-workspace';
|
|
||||||
|
|
||||||
protected static ?string $title = 'Choose workspace';
|
|
||||||
|
|
||||||
protected string $view = 'filament.pages.choose-workspace';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<Action>
|
|
||||||
*/
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
Action::make('createWorkspace')
|
|
||||||
->label('Create workspace')
|
|
||||||
->modalHeading('Create workspace')
|
|
||||||
->form([
|
|
||||||
TextInput::make('name')
|
|
||||||
->required()
|
|
||||||
->maxLength(255),
|
|
||||||
TextInput::make('slug')
|
|
||||||
->helperText('Optional. Used in URLs if set.')
|
|
||||||
->maxLength(255)
|
|
||||||
->rules(['nullable', 'string', 'max:255', 'alpha_dash', 'unique:workspaces,slug'])
|
|
||||||
->dehydrateStateUsing(fn ($state) => filled($state) ? $state : null)
|
|
||||||
->dehydrated(fn ($state) => filled($state)),
|
|
||||||
])
|
|
||||||
->action(fn (array $data) => $this->createWorkspace($data)),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return Collection<int, Workspace>
|
|
||||||
*/
|
|
||||||
public function getWorkspaces(): Collection
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
return Workspace::query()->whereRaw('1 = 0')->get();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Workspace::query()
|
|
||||||
->whereIn('id', function ($query) use ($user): void {
|
|
||||||
$query->from('workspace_memberships')
|
|
||||||
->select('workspace_id')
|
|
||||||
->where('user_id', $user->getKey());
|
|
||||||
})
|
|
||||||
->whereNull('archived_at')
|
|
||||||
->orderBy('name')
|
|
||||||
->get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function selectWorkspace(int $workspaceId): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! empty($workspace->archived_at)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$context = app(WorkspaceContext::class);
|
|
||||||
|
|
||||||
if (! $context->isMember($user, $workspace)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$context->setCurrentWorkspace($workspace, $user, request());
|
|
||||||
|
|
||||||
$this->redirect($this->redirectAfterWorkspaceSelected($user));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array{name: string, slug?: string|null} $data
|
|
||||||
*/
|
|
||||||
public function createWorkspace(array $data): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->create([
|
|
||||||
'name' => $data['name'],
|
|
||||||
'slug' => $data['slug'] ?? null,
|
|
||||||
]);
|
|
||||||
|
|
||||||
WorkspaceMembership::query()->create([
|
|
||||||
'workspace_id' => $workspace->getKey(),
|
|
||||||
'user_id' => $user->getKey(),
|
|
||||||
'role' => 'owner',
|
|
||||||
]);
|
|
||||||
|
|
||||||
app(WorkspaceContext::class)->setCurrentWorkspace($workspace, $user, request());
|
|
||||||
|
|
||||||
Notification::make()
|
|
||||||
->title('Workspace created')
|
|
||||||
->success()
|
|
||||||
->send();
|
|
||||||
|
|
||||||
$this->redirect($this->redirectAfterWorkspaceSelected($user));
|
|
||||||
}
|
|
||||||
|
|
||||||
private function redirectAfterWorkspaceSelected(User $user): string
|
|
||||||
{
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
return self::getUrl();
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return self::getUrl();
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenantsQuery = $user->tenants()
|
|
||||||
->where('workspace_id', $workspace->getKey())
|
|
||||||
->where('status', 'active');
|
|
||||||
|
|
||||||
$tenantCount = (int) $tenantsQuery->count();
|
|
||||||
|
|
||||||
if ($tenantCount === 0) {
|
|
||||||
return route('admin.workspace.managed-tenants.index', ['workspace' => $workspace->slug ?? $workspace->getKey()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenantCount === 1) {
|
|
||||||
$tenant = $tenantsQuery->first();
|
|
||||||
|
|
||||||
if ($tenant !== null) {
|
|
||||||
return TenantDashboard::getUrl(tenant: $tenant);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ChooseTenant::getUrl();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -4,13 +4,6 @@
|
|||||||
|
|
||||||
namespace App\Filament\Pages;
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Actions\Action;
|
|
||||||
use Filament\Forms\Components\TextInput;
|
|
||||||
use Filament\Notifications\Notification;
|
|
||||||
use Filament\Pages\Page;
|
use Filament\Pages\Page;
|
||||||
|
|
||||||
class NoAccess extends Page
|
class NoAccess extends Page
|
||||||
@ -26,60 +19,4 @@ class NoAccess extends Page
|
|||||||
protected static ?string $title = 'No access';
|
protected static ?string $title = 'No access';
|
||||||
|
|
||||||
protected string $view = 'filament.pages.no-access';
|
protected string $view = 'filament.pages.no-access';
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<Action>
|
|
||||||
*/
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
Action::make('createWorkspace')
|
|
||||||
->label('Create workspace')
|
|
||||||
->modalHeading('Create workspace')
|
|
||||||
->form([
|
|
||||||
TextInput::make('name')
|
|
||||||
->required()
|
|
||||||
->maxLength(255),
|
|
||||||
TextInput::make('slug')
|
|
||||||
->helperText('Optional. Used in URLs if set.')
|
|
||||||
->maxLength(255)
|
|
||||||
->rules(['nullable', 'string', 'max:255', 'alpha_dash', 'unique:workspaces,slug'])
|
|
||||||
->dehydrateStateUsing(fn ($state) => filled($state) ? $state : null)
|
|
||||||
->dehydrated(fn ($state) => filled($state)),
|
|
||||||
])
|
|
||||||
->action(fn (array $data) => $this->createWorkspace($data)),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array{name: string, slug?: string|null} $data
|
|
||||||
*/
|
|
||||||
public function createWorkspace(array $data): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->create([
|
|
||||||
'name' => $data['name'],
|
|
||||||
'slug' => $data['slug'] ?? null,
|
|
||||||
]);
|
|
||||||
|
|
||||||
WorkspaceMembership::query()->create([
|
|
||||||
'workspace_id' => $workspace->getKey(),
|
|
||||||
'user_id' => $user->getKey(),
|
|
||||||
'role' => 'owner',
|
|
||||||
]);
|
|
||||||
|
|
||||||
app(WorkspaceContext::class)->setCurrentWorkspace($workspace, $user, request());
|
|
||||||
|
|
||||||
Notification::make()
|
|
||||||
->title('Workspace created')
|
|
||||||
->success()
|
|
||||||
->send();
|
|
||||||
|
|
||||||
$this->redirect(ChooseTenant::getUrl());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
358
app/Filament/Pages/Onboarding/TenantOnboardingTaskBoard.php
Normal file
358
app/Filament/Pages/Onboarding/TenantOnboardingTaskBoard.php
Normal file
@ -0,0 +1,358 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Filament\Pages\Onboarding;
|
||||||
|
|
||||||
|
use App\Jobs\Onboarding\OnboardingConnectionDiagnosticsJob;
|
||||||
|
use App\Jobs\Onboarding\OnboardingConsentStatusJob;
|
||||||
|
use App\Jobs\Onboarding\OnboardingInitialSyncJob;
|
||||||
|
use App\Jobs\Onboarding\OnboardingVerifyPermissionsJob;
|
||||||
|
use App\Models\OnboardingEvidence;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\CapabilityResolver;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Auth\Capabilities;
|
||||||
|
use App\Support\Badges\BadgeCatalog;
|
||||||
|
use App\Support\Badges\BadgeDomain;
|
||||||
|
use App\Support\Onboarding\OnboardingFixHints;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskCatalog;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunLinks;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Pages\Page;
|
||||||
|
|
||||||
|
class TenantOnboardingTaskBoard extends Page
|
||||||
|
{
|
||||||
|
protected static bool $shouldRegisterNavigation = false;
|
||||||
|
|
||||||
|
protected static ?string $slug = 'onboarding/tasks';
|
||||||
|
|
||||||
|
protected static ?string $title = 'Onboarding task board';
|
||||||
|
|
||||||
|
protected string $view = 'filament.pages.onboarding.tenant-onboarding-task-board';
|
||||||
|
|
||||||
|
public ?OnboardingSession $session = null;
|
||||||
|
|
||||||
|
public bool $canStartProviderTasks = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
public array $runUrls = [];
|
||||||
|
|
||||||
|
public function mount(): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var CapabilityResolver $resolver */
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
$this->canStartProviderTasks = $resolver->can($user, $tenant, Capabilities::PROVIDER_RUN);
|
||||||
|
|
||||||
|
$activeSession = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereIn('status', ['draft', 'in_progress'])
|
||||||
|
->latest('id')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $activeSession instanceof OnboardingSession) {
|
||||||
|
$this->redirect(TenantOnboardingWizard::getUrl(tenant: $tenant));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session = $activeSession;
|
||||||
|
|
||||||
|
if ($activeSession->current_step < 4) {
|
||||||
|
$this->redirect(TenantOnboardingWizard::getUrl(tenant: $tenant));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function latestEvidenceStatusByTaskType(): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$evidence = OnboardingEvidence::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereIn('task_type', OnboardingTaskType::all())
|
||||||
|
->orderByDesc('recorded_at')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$byTask = [];
|
||||||
|
|
||||||
|
foreach ($evidence as $row) {
|
||||||
|
if (! isset($byTask[$row->task_type])) {
|
||||||
|
$byTask[$row->task_type] = $row->status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $byTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, OnboardingEvidence>
|
||||||
|
*/
|
||||||
|
public function latestEvidenceByTaskType(): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$evidence = OnboardingEvidence::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereIn('task_type', OnboardingTaskType::all())
|
||||||
|
->orderByDesc('recorded_at')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$byTask = [];
|
||||||
|
|
||||||
|
foreach ($evidence as $row) {
|
||||||
|
if (! isset($byTask[$row->task_type])) {
|
||||||
|
$byTask[$row->task_type] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $byTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{
|
||||||
|
* task_type: string,
|
||||||
|
* title: string,
|
||||||
|
* step: int,
|
||||||
|
* prerequisites: array<int, string>,
|
||||||
|
* status: string,
|
||||||
|
* badge: \App\Support\Badges\BadgeSpec,
|
||||||
|
* evidence: OnboardingEvidence|null,
|
||||||
|
* prerequisites_met: bool,
|
||||||
|
* unmet_prerequisites: array<int, string>,
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
public function taskRows(): array
|
||||||
|
{
|
||||||
|
$statuses = $this->latestEvidenceStatusByTaskType();
|
||||||
|
$evidenceByTask = $this->latestEvidenceByTaskType();
|
||||||
|
|
||||||
|
return collect(OnboardingTaskCatalog::all())
|
||||||
|
->map(function (array $task) use ($statuses, $evidenceByTask): array {
|
||||||
|
$taskType = $task['task_type'];
|
||||||
|
$status = $statuses[$taskType] ?? 'unknown';
|
||||||
|
|
||||||
|
$unmet = OnboardingTaskCatalog::unmetPrerequisites($taskType, $statuses);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
'title' => $task['title'],
|
||||||
|
'step' => $task['step'],
|
||||||
|
'prerequisites' => $task['prerequisites'],
|
||||||
|
'status' => $status,
|
||||||
|
'badge' => BadgeCatalog::spec(BadgeDomain::OnboardingTaskStatus, $status),
|
||||||
|
'evidence' => $evidenceByTask[$taskType] ?? null,
|
||||||
|
'prerequisites_met' => count($unmet) === 0,
|
||||||
|
'unmet_prerequisites' => $unmet,
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function fixHintsFor(?string $reasonCode): array
|
||||||
|
{
|
||||||
|
return OnboardingFixHints::forReason($reasonCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{
|
||||||
|
* recorded_at: string,
|
||||||
|
* task_type: string,
|
||||||
|
* status: string,
|
||||||
|
* badge: \App\Support\Badges\BadgeSpec,
|
||||||
|
* reason_code: string|null,
|
||||||
|
* message: string|null,
|
||||||
|
* run_url: string|null,
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
public function recentEvidenceRows(int $limit = 20): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$evidence = OnboardingEvidence::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->orderByDesc('recorded_at')
|
||||||
|
->limit($limit)
|
||||||
|
->with('operationRun')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return $evidence
|
||||||
|
->map(function (OnboardingEvidence $row) use ($tenant): array {
|
||||||
|
$runUrl = null;
|
||||||
|
|
||||||
|
if ($row->operationRun) {
|
||||||
|
$runUrl = OperationRunLinks::view($row->operationRun, $tenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'recorded_at' => $row->recorded_at?->toDateTimeString() ?? '',
|
||||||
|
'task_type' => $row->task_type,
|
||||||
|
'status' => $row->status,
|
||||||
|
'badge' => BadgeCatalog::spec(BadgeDomain::OnboardingTaskStatus, $row->status),
|
||||||
|
'reason_code' => $row->reason_code,
|
||||||
|
'message' => $row->message,
|
||||||
|
'run_url' => $runUrl,
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function startTask(string $taskType): void
|
||||||
|
{
|
||||||
|
if (! $this->canStartProviderTasks) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
$user = auth()->user();
|
||||||
|
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
Notification::make()
|
||||||
|
->title('No onboarding session')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->session->current_step < 4) {
|
||||||
|
$this->redirect(TenantOnboardingWizard::getUrl(tenant: $tenant));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($taskType, OnboardingTaskType::all(), true)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Unknown task')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$latestStatuses = $this->latestEvidenceStatusByTaskType();
|
||||||
|
|
||||||
|
if (! OnboardingTaskCatalog::prerequisitesMet($taskType, $latestStatuses)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Prerequisites not met')
|
||||||
|
->body('Complete required tasks first.')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connectionId = $this->session->provider_connection_id;
|
||||||
|
|
||||||
|
if (! is_int($connectionId)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Select a provider connection first')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($connectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Selected provider connection not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var OperationRunService $runs */
|
||||||
|
$runs = app(OperationRunService::class);
|
||||||
|
|
||||||
|
$run = $runs->ensureRunWithIdentity(
|
||||||
|
tenant: $tenant,
|
||||||
|
type: $taskType,
|
||||||
|
identityInputs: ['task_type' => $taskType],
|
||||||
|
context: [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
'onboarding_session_id' => (int) $this->session->getKey(),
|
||||||
|
'provider_connection_id' => (int) $connection->getKey(),
|
||||||
|
],
|
||||||
|
initiator: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->runUrls[$taskType] = OperationRunLinks::view($run, $tenant);
|
||||||
|
|
||||||
|
if (! $run->wasRecentlyCreated) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Task already queued')
|
||||||
|
->body('A run is already queued or running. Use the link to monitor progress.')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match ($taskType) {
|
||||||
|
OnboardingTaskType::VerifyPermissions => OnboardingVerifyPermissionsJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
),
|
||||||
|
OnboardingTaskType::ConsentStatus => OnboardingConsentStatusJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
),
|
||||||
|
OnboardingTaskType::ConnectionDiagnostics => OnboardingConnectionDiagnosticsJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
),
|
||||||
|
OnboardingTaskType::InitialSync => OnboardingInitialSyncJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Task queued')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
}
|
||||||
863
app/Filament/Pages/Onboarding/TenantOnboardingWizard.php
Normal file
863
app/Filament/Pages/Onboarding/TenantOnboardingWizard.php
Normal file
@ -0,0 +1,863 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Filament\Pages\Onboarding;
|
||||||
|
|
||||||
|
use App\Filament\Resources\ProviderConnectionResource\Pages\CreateProviderConnection;
|
||||||
|
use App\Jobs\Onboarding\OnboardingConsentStatusJob;
|
||||||
|
use App\Jobs\Onboarding\OnboardingVerifyPermissionsJob;
|
||||||
|
use App\Models\OnboardingEvidence;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\CapabilityResolver;
|
||||||
|
use App\Services\Intune\AuditLogger;
|
||||||
|
use App\Services\Onboarding\LegacyTenantCredentialMigrator;
|
||||||
|
use App\Services\Onboarding\OnboardingLockService;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Auth\Capabilities;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskCatalog;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunLinks;
|
||||||
|
use App\Support\Rbac\UiEnforcement;
|
||||||
|
use App\Support\Rbac\UiTooltips;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Notifications\Notification;
|
||||||
|
use Filament\Pages\Page;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
|
||||||
|
class TenantOnboardingWizard extends Page
|
||||||
|
{
|
||||||
|
protected static bool $shouldRegisterNavigation = false;
|
||||||
|
|
||||||
|
protected static ?string $slug = 'onboarding';
|
||||||
|
|
||||||
|
protected static ?string $title = 'Onboarding';
|
||||||
|
|
||||||
|
protected string $view = 'filament.pages.onboarding.tenant-onboarding-wizard';
|
||||||
|
|
||||||
|
public ?OnboardingSession $session = null;
|
||||||
|
|
||||||
|
public bool $canStartProviderTasks = false;
|
||||||
|
|
||||||
|
public bool $canManageProviderConnections = false;
|
||||||
|
|
||||||
|
public bool $canManageTenant = false;
|
||||||
|
|
||||||
|
public bool $hasSessionLock = false;
|
||||||
|
|
||||||
|
public bool $sessionLockedByOther = false;
|
||||||
|
|
||||||
|
public ?string $sessionLockedByLabel = null;
|
||||||
|
|
||||||
|
public ?string $sessionLockedUntil = null;
|
||||||
|
|
||||||
|
public ?int $selectedProviderConnectionId = null;
|
||||||
|
|
||||||
|
public ?string $verifyPermissionsRunUrl = null;
|
||||||
|
|
||||||
|
public ?string $consentStatusRunUrl = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<int, string>
|
||||||
|
*/
|
||||||
|
public array $handoffUserOptions = [];
|
||||||
|
|
||||||
|
public function mount(): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var CapabilityResolver $resolver */
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
$this->canStartProviderTasks = $resolver->can($user, $tenant, Capabilities::PROVIDER_RUN);
|
||||||
|
$this->canManageProviderConnections = $resolver->can($user, $tenant, Capabilities::PROVIDER_MANAGE);
|
||||||
|
$this->canManageTenant = $resolver->can($user, $tenant, Capabilities::TENANT_MANAGE);
|
||||||
|
|
||||||
|
$activeSession = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereIn('status', ['draft', 'in_progress'])
|
||||||
|
->latest('id')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $activeSession instanceof OnboardingSession && $this->canStartProviderTasks) {
|
||||||
|
$activeSession = OnboardingSession::query()->create([
|
||||||
|
'tenant_id' => $tenant->getKey(),
|
||||||
|
'status' => 'draft',
|
||||||
|
'current_step' => 1,
|
||||||
|
'assigned_to_user_id' => $user->getKey(),
|
||||||
|
'metadata' => [],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session = $activeSession;
|
||||||
|
|
||||||
|
$defaultConnectionId = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->where('is_default', true)
|
||||||
|
->value('id');
|
||||||
|
|
||||||
|
$this->selectedProviderConnectionId = $this->session?->provider_connection_id
|
||||||
|
?? (is_int($defaultConnectionId) ? $defaultConnectionId : null);
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: $this->canStartProviderTasks);
|
||||||
|
|
||||||
|
if ($this->session instanceof OnboardingSession
|
||||||
|
&& $this->hasSessionLock
|
||||||
|
&& $this->session->provider_connection_id === null
|
||||||
|
&& is_int($this->selectedProviderConnectionId)
|
||||||
|
&& $this->tenantHasLegacyCredentials($tenant)
|
||||||
|
) {
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($this->selectedProviderConnectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($connection instanceof ProviderConnection) {
|
||||||
|
$this->session->update(['provider_connection_id' => $connection->getKey()]);
|
||||||
|
$this->session->refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function tenantHasLegacyCredentials(Tenant $tenant): bool
|
||||||
|
{
|
||||||
|
return trim((string) ($tenant->app_client_id ?? '')) !== ''
|
||||||
|
&& trim((string) ($tenant->app_client_secret ?? '')) !== '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<Action>
|
||||||
|
*/
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
return [
|
||||||
|
UiEnforcement::forAction(
|
||||||
|
Action::make('takeover_onboarding_session')
|
||||||
|
->label('Take over')
|
||||||
|
->color('warning')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading('Take over onboarding session')
|
||||||
|
->modalDescription('This will take over the onboarding session lock. Use when the current lock holder is unavailable.')
|
||||||
|
->action(function (): void {
|
||||||
|
$this->takeoverSession();
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
->requireCapability(Capabilities::TENANT_MANAGE)
|
||||||
|
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||||
|
->apply()
|
||||||
|
->visible(fn (): bool => $this->session instanceof OnboardingSession && $this->sessionLockedByOther),
|
||||||
|
|
||||||
|
UiEnforcement::forAction(
|
||||||
|
Action::make('handoff_onboarding_session')
|
||||||
|
->label('Handoff')
|
||||||
|
->color('gray')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading('Handoff onboarding session')
|
||||||
|
->modalDescription('Assign onboarding to another tenant member and release your lock.')
|
||||||
|
->form([
|
||||||
|
Select::make('assigned_to_user_id')
|
||||||
|
->label('Assign to')
|
||||||
|
->options(fn (): array => $this->handoffUserOptions)
|
||||||
|
->searchable()
|
||||||
|
->required(),
|
||||||
|
])
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$assignedToUserId = (int) ($data['assigned_to_user_id'] ?? 0);
|
||||||
|
$this->handoffSession($assignedToUserId);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
->requireCapability(Capabilities::TENANT_MANAGE)
|
||||||
|
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||||
|
->apply()
|
||||||
|
->visible(fn (): bool => $this->session instanceof OnboardingSession && $this->hasSessionLock),
|
||||||
|
|
||||||
|
Action::make('release_onboarding_lock')
|
||||||
|
->label('Release lock')
|
||||||
|
->color('gray')
|
||||||
|
->visible(fn (): bool => $this->session instanceof OnboardingSession && $this->hasSessionLock)
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading('Release onboarding lock')
|
||||||
|
->modalDescription('This will release your lock so another user can take over onboarding.')
|
||||||
|
->action(function (): void {
|
||||||
|
$this->releaseSessionLock();
|
||||||
|
}),
|
||||||
|
|
||||||
|
UiEnforcement::forAction(
|
||||||
|
Action::make('migrate_legacy_credentials')
|
||||||
|
->label('Migrate legacy credentials')
|
||||||
|
->color('warning')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading('Migrate legacy tenant credentials')
|
||||||
|
->modalDescription('This will copy the tenant\'s legacy app client secret into the selected provider connection credentials. The secret is never displayed.')
|
||||||
|
->action(function (): void {
|
||||||
|
$this->migrateLegacyCredentials();
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
->requireCapability(Capabilities::PROVIDER_MANAGE)
|
||||||
|
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||||
|
->apply()
|
||||||
|
->visible(fn (): bool => $this->canOfferLegacyCredentialMigration()),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function refreshCollaborationState(bool $attemptAcquire = false): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->hasSessionLock = false;
|
||||||
|
$this->sessionLockedByOther = false;
|
||||||
|
$this->sessionLockedByLabel = null;
|
||||||
|
$this->sessionLockedUntil = null;
|
||||||
|
$this->handoffUserOptions = [];
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->canManageTenant) {
|
||||||
|
$this->handoffUserOptions = $tenant->users()
|
||||||
|
->orderBy('name')
|
||||||
|
->orderBy('email')
|
||||||
|
->get(['users.id', 'users.name', 'users.email'])
|
||||||
|
->mapWithKeys(function (User $member): array {
|
||||||
|
$label = trim((string) $member->name) !== ''
|
||||||
|
? (string) $member->name
|
||||||
|
: (string) $member->email;
|
||||||
|
|
||||||
|
if (trim((string) $member->email) !== '') {
|
||||||
|
$label .= ' <'.$member->email.'>';
|
||||||
|
}
|
||||||
|
|
||||||
|
return [(int) $member->getKey() => $label];
|
||||||
|
})
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($attemptAcquire) {
|
||||||
|
app(OnboardingLockService::class)->acquire($this->session, $user);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session->refresh();
|
||||||
|
$this->session->loadMissing(['lockedBy']);
|
||||||
|
|
||||||
|
$this->hasSessionLock = (int) ($this->session->locked_by_user_id ?? 0) === (int) $user->getKey()
|
||||||
|
&& $this->session->locked_until?->isFuture();
|
||||||
|
|
||||||
|
$this->sessionLockedByOther = $this->isLockedByOther($this->session, $user);
|
||||||
|
|
||||||
|
if ($this->sessionLockedByOther) {
|
||||||
|
$lockedBy = $this->session->lockedBy;
|
||||||
|
$this->sessionLockedByLabel = $lockedBy instanceof User
|
||||||
|
? (trim((string) $lockedBy->name) !== '' ? (string) $lockedBy->name : (string) $lockedBy->email)
|
||||||
|
: 'another user';
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->sessionLockedUntil = $this->session->locked_until?->diffForHumans();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureLockForMutation(): bool
|
||||||
|
{
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$acquired = app(OnboardingLockService::class)->acquire($this->session, $user);
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
if ($acquired) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Session is locked')
|
||||||
|
->body('Another user is currently editing onboarding. Take over the lock to make changes.')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isLockedByOther(OnboardingSession $session, User $user): bool
|
||||||
|
{
|
||||||
|
if ($session->locked_by_user_id === null || $session->locked_until === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($session->locked_until->isPast()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $session->locked_by_user_id !== (int) $user->getKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function takeoverSession(): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->canManageTenant) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$previousLockHolderId = $this->session->locked_by_user_id;
|
||||||
|
|
||||||
|
app(OnboardingLockService::class)->takeover($this->session, $user);
|
||||||
|
|
||||||
|
app(AuditLogger::class)->log(
|
||||||
|
tenant: $tenant,
|
||||||
|
action: 'onboarding.takeover',
|
||||||
|
context: [
|
||||||
|
'onboarding_session_id' => (int) $this->session->getKey(),
|
||||||
|
'previous_locked_by_user_id' => is_int($previousLockHolderId) ? $previousLockHolderId : null,
|
||||||
|
],
|
||||||
|
actorId: (int) $user->getKey(),
|
||||||
|
actorEmail: $user->email,
|
||||||
|
actorName: $user->name,
|
||||||
|
status: 'success',
|
||||||
|
resourceType: 'onboarding_session',
|
||||||
|
resourceId: (string) $this->session->getKey(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Lock taken over')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function handoffSession(int $assignedToUserId): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->canManageTenant) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->ensureLockForMutation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$assignee = $tenant->users()->whereKey($assignedToUserId)->first();
|
||||||
|
if (! $assignee instanceof User) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Assignee not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session->update(['assigned_to_user_id' => (int) $assignee->getKey()]);
|
||||||
|
|
||||||
|
app(OnboardingLockService::class)->release($this->session, $user);
|
||||||
|
|
||||||
|
app(AuditLogger::class)->log(
|
||||||
|
tenant: $tenant,
|
||||||
|
action: 'onboarding.handoff',
|
||||||
|
context: [
|
||||||
|
'onboarding_session_id' => (int) $this->session->getKey(),
|
||||||
|
'assigned_to_user_id' => (int) $assignee->getKey(),
|
||||||
|
],
|
||||||
|
actorId: (int) $user->getKey(),
|
||||||
|
actorEmail: $user->email,
|
||||||
|
actorName: $user->name,
|
||||||
|
status: 'success',
|
||||||
|
resourceType: 'onboarding_session',
|
||||||
|
resourceId: (string) $this->session->getKey(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Onboarding handed off')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function releaseSessionLock(): void
|
||||||
|
{
|
||||||
|
$user = auth()->user();
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
app(OnboardingLockService::class)->release($this->session, $user);
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Lock released')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function canOfferLegacyCredentialMigration(): bool
|
||||||
|
{
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $this->tenantHasLegacyCredentials($tenant)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connectionId = $this->session->provider_connection_id;
|
||||||
|
|
||||||
|
if (! is_int($connectionId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->with('credential')
|
||||||
|
->whereKey($connectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$credential = $connection->credential;
|
||||||
|
|
||||||
|
if ($credential === null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($credential->type !== 'client_secret') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = $credential->payload;
|
||||||
|
if (! is_array($payload)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$clientId = trim((string) Arr::get($payload, 'client_id'));
|
||||||
|
$clientSecret = trim((string) Arr::get($payload, 'client_secret'));
|
||||||
|
|
||||||
|
return $clientId === '' || $clientSecret === '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function migrateLegacyCredentials(): void
|
||||||
|
{
|
||||||
|
if (! $this->canManageProviderConnections) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->ensureLockForMutation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$connectionId = $this->session->provider_connection_id;
|
||||||
|
if (! is_int($connectionId)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Select a provider connection first')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($connectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Selected provider connection not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$outcome = app(LegacyTenantCredentialMigrator::class)->migrate($tenant, $connection);
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title($outcome['migrated'] ? 'Credentials migrated' : 'Migration not needed')
|
||||||
|
->body($outcome['message'])
|
||||||
|
->color($outcome['migrated'] ? 'success' : 'gray')
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{id: int, label: string}>
|
||||||
|
*/
|
||||||
|
public function providerConnections(): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
return ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->orderByDesc('is_default')
|
||||||
|
->orderBy('provider')
|
||||||
|
->orderBy('display_name')
|
||||||
|
->get()
|
||||||
|
->map(function (ProviderConnection $connection): array {
|
||||||
|
$entraName = Arr::get(is_array($connection->metadata) ? $connection->metadata : [], 'entra_tenant_name');
|
||||||
|
$entraSuffix = is_string($entraName) && trim($entraName) !== '' ? ' — '.trim($entraName) : '';
|
||||||
|
|
||||||
|
$label = ($connection->display_name ?: ucfirst($connection->provider))
|
||||||
|
.$entraSuffix
|
||||||
|
.($connection->is_default ? ' (default)' : '');
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => (int) $connection->getKey(),
|
||||||
|
'label' => $label,
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updatedSelectedProviderConnectionId(): void
|
||||||
|
{
|
||||||
|
if (! $this->canStartProviderTasks) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->ensureLockForMutation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_int($this->selectedProviderConnectionId)) {
|
||||||
|
$this->session->update(['provider_connection_id' => null]);
|
||||||
|
$this->session->refresh();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($this->selectedProviderConnectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Connection not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session->update([
|
||||||
|
'provider_connection_id' => $connection->getKey(),
|
||||||
|
]);
|
||||||
|
$this->session->refresh();
|
||||||
|
|
||||||
|
$this->refreshCollaborationState(attemptAcquire: false);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Provider connection selected')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{task_type: string, title: string, step: int, prerequisites: array<int, string>}>
|
||||||
|
*/
|
||||||
|
public function planTasks(): array
|
||||||
|
{
|
||||||
|
return OnboardingTaskCatalog::all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function latestEvidenceStatusByTaskType(): array
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
$evidence = OnboardingEvidence::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereIn('task_type', OnboardingTaskType::all())
|
||||||
|
->orderByDesc('recorded_at')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$byTask = [];
|
||||||
|
|
||||||
|
foreach ($evidence as $row) {
|
||||||
|
if (! isset($byTask[$row->task_type])) {
|
||||||
|
$byTask[$row->task_type] = $row->status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $byTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function startVerifyPermissions(): void
|
||||||
|
{
|
||||||
|
if (! $this->canStartProviderTasks) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
$user = auth()->user();
|
||||||
|
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
Notification::make()
|
||||||
|
->title('No onboarding session')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->ensureLockForMutation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connectionId = $this->session->provider_connection_id;
|
||||||
|
|
||||||
|
if (! is_int($connectionId)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Select a provider connection first')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($connectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Selected provider connection not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->session->current_step < 4) {
|
||||||
|
$this->session->update(['current_step' => 4]);
|
||||||
|
$this->session->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
$taskType = OnboardingTaskType::VerifyPermissions;
|
||||||
|
|
||||||
|
/** @var OperationRunService $runs */
|
||||||
|
$runs = app(OperationRunService::class);
|
||||||
|
|
||||||
|
$run = $runs->ensureRunWithIdentity(
|
||||||
|
tenant: $tenant,
|
||||||
|
type: $taskType,
|
||||||
|
identityInputs: [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
],
|
||||||
|
context: [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
'onboarding_session_id' => (int) $this->session->getKey(),
|
||||||
|
'provider_connection_id' => (int) $connection->getKey(),
|
||||||
|
],
|
||||||
|
initiator: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->verifyPermissionsRunUrl = OperationRunLinks::view($run, $tenant);
|
||||||
|
|
||||||
|
if ($run->wasRecentlyCreated) {
|
||||||
|
OnboardingVerifyPermissionsJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Verify permissions queued')
|
||||||
|
->body('Run queued. Use the link below to monitor progress.')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Verify permissions already queued')
|
||||||
|
->body('A run is already queued or running. Use the link below to monitor progress.')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function startConsentStatus(): void
|
||||||
|
{
|
||||||
|
if (! $this->canStartProviderTasks) {
|
||||||
|
abort(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
$user = auth()->user();
|
||||||
|
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
abort(403, 'Not allowed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->session instanceof OnboardingSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $this->ensureLockForMutation()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->session->current_step < 4) {
|
||||||
|
$this->session->update(['current_step' => 4]);
|
||||||
|
$this->session->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! OnboardingTaskCatalog::prerequisitesMet(
|
||||||
|
taskType: OnboardingTaskType::ConsentStatus,
|
||||||
|
latestEvidenceStatusByTaskType: $this->latestEvidenceStatusByTaskType(),
|
||||||
|
)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Prerequisites not met')
|
||||||
|
->body('Run “Verify permissions” first.')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connectionId = $this->session->provider_connection_id;
|
||||||
|
|
||||||
|
if (! is_int($connectionId)) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Select a provider connection first')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->whereKey($connectionId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
Notification::make()
|
||||||
|
->title('Selected provider connection not found')
|
||||||
|
->danger()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$taskType = OnboardingTaskType::ConsentStatus;
|
||||||
|
|
||||||
|
/** @var OperationRunService $runs */
|
||||||
|
$runs = app(OperationRunService::class);
|
||||||
|
|
||||||
|
$run = $runs->ensureRunWithIdentity(
|
||||||
|
tenant: $tenant,
|
||||||
|
type: $taskType,
|
||||||
|
identityInputs: [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
],
|
||||||
|
context: [
|
||||||
|
'task_type' => $taskType,
|
||||||
|
'onboarding_session_id' => (int) $this->session->getKey(),
|
||||||
|
'provider_connection_id' => (int) $connection->getKey(),
|
||||||
|
],
|
||||||
|
initiator: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->consentStatusRunUrl = OperationRunLinks::view($run, $tenant);
|
||||||
|
|
||||||
|
if ($run->wasRecentlyCreated) {
|
||||||
|
OnboardingConsentStatusJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $user->getKey(),
|
||||||
|
providerConnectionId: (int) $connection->getKey(),
|
||||||
|
onboardingSessionId: (int) $this->session->getKey(),
|
||||||
|
operationRun: $run,
|
||||||
|
);
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Consent status queued')
|
||||||
|
->success()
|
||||||
|
->send();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Notification::make()
|
||||||
|
->title('Consent status already queued')
|
||||||
|
->warning()
|
||||||
|
->send();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createProviderConnectionUrl(): string
|
||||||
|
{
|
||||||
|
return CreateProviderConnection::getUrl(tenant: Tenant::current());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Pages\Operations;
|
|
||||||
|
|
||||||
use App\Models\OperationRun;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use Filament\Actions\Action;
|
|
||||||
use Filament\Pages\Page;
|
|
||||||
|
|
||||||
class TenantlessOperationRunViewer extends Page
|
|
||||||
{
|
|
||||||
protected static string $layout = 'filament-panels::components.layout.simple';
|
|
||||||
|
|
||||||
protected static bool $shouldRegisterNavigation = false;
|
|
||||||
|
|
||||||
protected static bool $isDiscovered = false;
|
|
||||||
|
|
||||||
protected static ?string $title = 'Operation run';
|
|
||||||
|
|
||||||
protected string $view = 'filament.pages.operations.tenantless-operation-run-viewer';
|
|
||||||
|
|
||||||
public OperationRun $run;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<Action>
|
|
||||||
*/
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
Action::make('refresh')
|
|
||||||
->label('Refresh')
|
|
||||||
->icon('heroicon-o-arrow-path')
|
|
||||||
->color('gray')
|
|
||||||
->url(fn (): string => url()->current()),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function mount(OperationRun $run): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceId = (int) ($run->workspace_id ?? 0);
|
|
||||||
|
|
||||||
if ($workspaceId <= 0) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$isMember = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('user_id', (int) $user->getKey())
|
|
||||||
->exists();
|
|
||||||
|
|
||||||
if (! $isMember) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->run = $run->loadMissing(['workspace', 'tenant', 'user']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -4,11 +4,9 @@
|
|||||||
|
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Auth\CapabilityResolver;
|
use App\Services\Auth\CapabilityResolver;
|
||||||
use App\Services\Intune\AuditLogger;
|
use App\Services\Intune\AuditLogger;
|
||||||
use App\Support\Auth\Capabilities;
|
use App\Support\Auth\Capabilities;
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Forms;
|
use Filament\Forms;
|
||||||
use Filament\Pages\Tenancy\RegisterTenant as BaseRegisterTenant;
|
use Filament\Pages\Tenancy\RegisterTenant as BaseRegisterTenant;
|
||||||
use Filament\Schemas\Schema;
|
use Filament\Schemas\Schema;
|
||||||
@ -29,20 +27,6 @@ public static function canView(): bool
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
if ($workspaceId !== null) {
|
|
||||||
$canRegisterInWorkspace = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('user_id', $user->getKey())
|
|
||||||
->whereIn('role', ['owner', 'manager'])
|
|
||||||
->exists();
|
|
||||||
|
|
||||||
if ($canRegisterInWorkspace) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenantIds = $user->tenants()->withTrashed()->pluck('tenants.id');
|
$tenantIds = $user->tenants()->withTrashed()->pluck('tenants.id');
|
||||||
|
|
||||||
if ($tenantIds->isEmpty()) {
|
if ($tenantIds->isEmpty()) {
|
||||||
@ -111,12 +95,6 @@ protected function handleRegistration(array $data): Model
|
|||||||
abort(403);
|
abort(403);
|
||||||
}
|
}
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
if ($workspaceId !== null) {
|
|
||||||
$data['workspace_id'] = $workspaceId;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::create($data);
|
$tenant = Tenant::create($data);
|
||||||
|
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
|
|||||||
@ -1,184 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Pages;
|
|
||||||
|
|
||||||
use App\Filament\Resources\ProviderConnectionResource;
|
|
||||||
use App\Models\ProviderConnection;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Services\Auth\CapabilityResolver;
|
|
||||||
use App\Services\Intune\TenantRequiredPermissionsViewModelBuilder;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use Filament\Pages\Page;
|
|
||||||
|
|
||||||
class TenantRequiredPermissions extends Page
|
|
||||||
{
|
|
||||||
protected static bool $shouldRegisterNavigation = false;
|
|
||||||
|
|
||||||
protected static ?string $slug = 'required-permissions';
|
|
||||||
|
|
||||||
protected static ?string $title = 'Required permissions';
|
|
||||||
|
|
||||||
protected string $view = 'filament.pages.tenant-required-permissions';
|
|
||||||
|
|
||||||
public string $status = 'missing';
|
|
||||||
|
|
||||||
public string $type = 'all';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
public array $features = [];
|
|
||||||
|
|
||||||
public string $search = '';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array<string, mixed>
|
|
||||||
*/
|
|
||||||
public array $viewModel = [];
|
|
||||||
|
|
||||||
public static function canAccess(): bool
|
|
||||||
{
|
|
||||||
$tenant = Tenant::current();
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var CapabilityResolver $resolver */
|
|
||||||
$resolver = app(CapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function mount(): void
|
|
||||||
{
|
|
||||||
$queryFeatures = request()->query('features', $this->features);
|
|
||||||
|
|
||||||
$state = TenantRequiredPermissionsViewModelBuilder::normalizeFilterState([
|
|
||||||
'status' => request()->query('status', $this->status),
|
|
||||||
'type' => request()->query('type', $this->type),
|
|
||||||
'features' => is_array($queryFeatures) ? $queryFeatures : [],
|
|
||||||
'search' => request()->query('search', $this->search),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->status = $state['status'];
|
|
||||||
$this->type = $state['type'];
|
|
||||||
$this->features = $state['features'];
|
|
||||||
$this->search = $state['search'];
|
|
||||||
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updatedStatus(): void
|
|
||||||
{
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updatedType(): void
|
|
||||||
{
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updatedFeatures(): void
|
|
||||||
{
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updatedSearch(): void
|
|
||||||
{
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function applyFeatureFilter(string $feature): void
|
|
||||||
{
|
|
||||||
$feature = trim($feature);
|
|
||||||
|
|
||||||
if ($feature === '') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (in_array($feature, $this->features, true)) {
|
|
||||||
$this->features = array_values(array_filter(
|
|
||||||
$this->features,
|
|
||||||
static fn (string $value): bool => $value !== $feature,
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
$this->features[] = $feature;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->features = array_values(array_unique($this->features));
|
|
||||||
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function clearFeatureFilter(): void
|
|
||||||
{
|
|
||||||
$this->features = [];
|
|
||||||
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function resetFilters(): void
|
|
||||||
{
|
|
||||||
$this->status = 'missing';
|
|
||||||
$this->type = 'all';
|
|
||||||
$this->features = [];
|
|
||||||
$this->search = '';
|
|
||||||
|
|
||||||
$this->refreshViewModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
private function refreshViewModel(): void
|
|
||||||
{
|
|
||||||
$tenant = Tenant::current();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
$this->viewModel = [];
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$builder = app(TenantRequiredPermissionsViewModelBuilder::class);
|
|
||||||
|
|
||||||
$this->viewModel = $builder->build($tenant, [
|
|
||||||
'status' => $this->status,
|
|
||||||
'type' => $this->type,
|
|
||||||
'features' => $this->features,
|
|
||||||
'search' => $this->search,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$filters = $this->viewModel['filters'] ?? null;
|
|
||||||
|
|
||||||
if (is_array($filters)) {
|
|
||||||
$this->status = (string) ($filters['status'] ?? $this->status);
|
|
||||||
$this->type = (string) ($filters['type'] ?? $this->type);
|
|
||||||
$this->features = is_array($filters['features'] ?? null) ? $filters['features'] : $this->features;
|
|
||||||
$this->search = (string) ($filters['search'] ?? $this->search);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function reRunVerificationUrl(): ?string
|
|
||||||
{
|
|
||||||
$tenant = Tenant::current();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$connectionId = ProviderConnection::query()
|
|
||||||
->where('tenant_id', (int) $tenant->getKey())
|
|
||||||
->orderByDesc('is_default')
|
|
||||||
->orderByDesc('id')
|
|
||||||
->value('id');
|
|
||||||
|
|
||||||
if (! is_int($connectionId)) {
|
|
||||||
return ProviderConnectionResource::getUrl('index', tenant: $tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
return ProviderConnectionResource::getUrl('edit', ['record' => $connectionId], tenant: $tenant);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,79 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Pages\Workspaces;
|
|
||||||
|
|
||||||
use App\Filament\Pages\ChooseTenant;
|
|
||||||
use App\Filament\Pages\TenantDashboard;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use Filament\Pages\Page;
|
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
|
||||||
|
|
||||||
class ManagedTenantsLanding extends Page
|
|
||||||
{
|
|
||||||
protected static bool $shouldRegisterNavigation = false;
|
|
||||||
|
|
||||||
protected static bool $isDiscovered = false;
|
|
||||||
|
|
||||||
protected static ?string $title = 'Managed tenants';
|
|
||||||
|
|
||||||
protected string $view = 'filament.pages.workspaces.managed-tenants-landing';
|
|
||||||
|
|
||||||
public Workspace $workspace;
|
|
||||||
|
|
||||||
public function mount(Workspace $workspace): void
|
|
||||||
{
|
|
||||||
$this->workspace = $workspace;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return Collection<int, Tenant>
|
|
||||||
*/
|
|
||||||
public function getTenants(): Collection
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
return Tenant::query()->whereRaw('1 = 0')->get();
|
|
||||||
}
|
|
||||||
|
|
||||||
return $user->tenants()
|
|
||||||
->where('workspace_id', $this->workspace->getKey())
|
|
||||||
->where('status', 'active')
|
|
||||||
->orderBy('name')
|
|
||||||
->get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function goToChooseTenant(): void
|
|
||||||
{
|
|
||||||
$this->redirect(ChooseTenant::getUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
public function openTenant(int $tenantId): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::query()
|
|
||||||
->where('status', 'active')
|
|
||||||
->where('workspace_id', $this->workspace->getKey())
|
|
||||||
->whereKey($tenantId)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $user->canAccessTenant($tenant)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->redirect(TenantDashboard::getUrl(tenant: $tenant));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -938,7 +938,7 @@ public static function table(Table $table): Table
|
|||||||
|
|
||||||
public static function getEloquentQuery(): Builder
|
public static function getEloquentQuery(): Builder
|
||||||
{
|
{
|
||||||
$tenantId = Tenant::currentOrFail()->getKey();
|
$tenantId = Tenant::current()->getKey();
|
||||||
|
|
||||||
return parent::getEloquentQuery()
|
return parent::getEloquentQuery()
|
||||||
->where('tenant_id', $tenantId)
|
->where('tenant_id', $tenantId)
|
||||||
@ -1054,7 +1054,7 @@ public static function ensurePolicyTypes(array $data): array
|
|||||||
|
|
||||||
public static function assignTenant(array $data): array
|
public static function assignTenant(array $data): array
|
||||||
{
|
{
|
||||||
$data['tenant_id'] = Tenant::currentOrFail()->getKey();
|
$data['tenant_id'] = Tenant::current()->getKey();
|
||||||
|
|
||||||
return $data;
|
return $data;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -21,7 +21,7 @@ class BackupScheduleRunsRelationManager extends RelationManager
|
|||||||
public function table(Table $table): Table
|
public function table(Table $table): Table
|
||||||
{
|
{
|
||||||
return $table
|
return $table
|
||||||
->modifyQueryUsing(fn (Builder $query) => $query->where('tenant_id', Tenant::currentOrFail()->getKey())->with('backupSet'))
|
->modifyQueryUsing(fn (Builder $query) => $query->where('tenant_id', Tenant::current()->getKey())->with('backupSet'))
|
||||||
->defaultSort('scheduled_for', 'desc')
|
->defaultSort('scheduled_for', 'desc')
|
||||||
->columns([
|
->columns([
|
||||||
Tables\Columns\TextColumn::make('scheduled_for')
|
Tables\Columns\TextColumn::make('scheduled_for')
|
||||||
|
|||||||
@ -3,16 +3,11 @@
|
|||||||
namespace App\Filament\Resources;
|
namespace App\Filament\Resources;
|
||||||
|
|
||||||
use App\Filament\Resources\OperationRunResource\Pages;
|
use App\Filament\Resources\OperationRunResource\Pages;
|
||||||
use App\Filament\Support\VerificationReportChangeIndicator;
|
|
||||||
use App\Filament\Support\VerificationReportViewer;
|
|
||||||
use App\Models\OperationRun;
|
use App\Models\OperationRun;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\VerificationCheckAcknowledgement;
|
|
||||||
use App\Support\Badges\BadgeDomain;
|
use App\Support\Badges\BadgeDomain;
|
||||||
use App\Support\Badges\BadgeRenderer;
|
use App\Support\Badges\BadgeRenderer;
|
||||||
use App\Support\OperationCatalog;
|
use App\Support\OperationCatalog;
|
||||||
use App\Support\OperationRunLinks;
|
|
||||||
use App\Support\OperationRunOutcome;
|
use App\Support\OperationRunOutcome;
|
||||||
use App\Support\OperationRunStatus;
|
use App\Support\OperationRunStatus;
|
||||||
use App\Support\OpsUx\RunDetailPolling;
|
use App\Support\OpsUx\RunDetailPolling;
|
||||||
@ -141,92 +136,12 @@ public static function infolist(Schema $schema): Schema
|
|||||||
->visible(fn (OperationRun $record): bool => ! empty($record->failure_summary))
|
->visible(fn (OperationRun $record): bool => ! empty($record->failure_summary))
|
||||||
->columnSpanFull(),
|
->columnSpanFull(),
|
||||||
|
|
||||||
Section::make('Verification report')
|
|
||||||
->schema([
|
|
||||||
ViewEntry::make('verification_report')
|
|
||||||
->label('')
|
|
||||||
->view('filament.components.verification-report-viewer')
|
|
||||||
->state(fn (OperationRun $record): ?array => VerificationReportViewer::report($record))
|
|
||||||
->viewData(function (OperationRun $record): array {
|
|
||||||
$report = VerificationReportViewer::report($record);
|
|
||||||
$fingerprint = is_array($report) ? VerificationReportViewer::fingerprint($report) : null;
|
|
||||||
|
|
||||||
$changeIndicator = VerificationReportChangeIndicator::forRun($record);
|
|
||||||
|
|
||||||
$previousRunUrl = null;
|
|
||||||
|
|
||||||
if ($changeIndicator !== null) {
|
|
||||||
$tenant = Tenant::current();
|
|
||||||
|
|
||||||
$previousRunUrl = $tenant instanceof Tenant
|
|
||||||
? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant)
|
|
||||||
: OperationRunLinks::tenantlessView($changeIndicator['previous_report_id']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$acknowledgements = VerificationCheckAcknowledgement::query()
|
|
||||||
->where('tenant_id', (int) ($record->tenant_id ?? 0))
|
|
||||||
->where('workspace_id', (int) ($record->workspace_id ?? 0))
|
|
||||||
->where('operation_run_id', (int) $record->getKey())
|
|
||||||
->with('acknowledgedByUser')
|
|
||||||
->get()
|
|
||||||
->mapWithKeys(static function (VerificationCheckAcknowledgement $ack): array {
|
|
||||||
$user = $ack->acknowledgedByUser;
|
|
||||||
|
|
||||||
return [
|
|
||||||
(string) $ack->check_key => [
|
|
||||||
'check_key' => (string) $ack->check_key,
|
|
||||||
'ack_reason' => (string) $ack->ack_reason,
|
|
||||||
'acknowledged_at' => $ack->acknowledged_at?->toJSON(),
|
|
||||||
'expires_at' => $ack->expires_at?->toJSON(),
|
|
||||||
'acknowledged_by' => $user instanceof User
|
|
||||||
? [
|
|
||||||
'id' => (int) $user->getKey(),
|
|
||||||
'name' => (string) $user->name,
|
|
||||||
]
|
|
||||||
: null,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->all();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'run' => [
|
|
||||||
'id' => (int) $record->getKey(),
|
|
||||||
'type' => (string) $record->type,
|
|
||||||
'status' => (string) $record->status,
|
|
||||||
'outcome' => (string) $record->outcome,
|
|
||||||
'started_at' => $record->started_at?->toJSON(),
|
|
||||||
'completed_at' => $record->completed_at?->toJSON(),
|
|
||||||
],
|
|
||||||
'fingerprint' => $fingerprint,
|
|
||||||
'changeIndicator' => $changeIndicator,
|
|
||||||
'previousRunUrl' => $previousRunUrl,
|
|
||||||
'acknowledgements' => $acknowledgements,
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->columnSpanFull(),
|
|
||||||
])
|
|
||||||
->visible(fn (OperationRun $record): bool => VerificationReportViewer::shouldRenderForRun($record))
|
|
||||||
->columnSpanFull(),
|
|
||||||
|
|
||||||
Section::make('Context')
|
Section::make('Context')
|
||||||
->schema([
|
->schema([
|
||||||
ViewEntry::make('context')
|
ViewEntry::make('context')
|
||||||
->label('')
|
->label('')
|
||||||
->view('filament.infolists.entries.snapshot-json')
|
->view('filament.infolists.entries.snapshot-json')
|
||||||
->state(function (OperationRun $record): array {
|
->state(fn (OperationRun $record): array => $record->context ?? [])
|
||||||
$context = $record->context ?? [];
|
|
||||||
$context = is_array($context) ? $context : [];
|
|
||||||
|
|
||||||
if (array_key_exists('verification_report', $context)) {
|
|
||||||
$context['verification_report'] = [
|
|
||||||
'redacted' => true,
|
|
||||||
'note' => 'Rendered in the Verification report section.',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $context;
|
|
||||||
})
|
|
||||||
->columnSpanFull(),
|
->columnSpanFull(),
|
||||||
])
|
])
|
||||||
->columnSpanFull(),
|
->columnSpanFull(),
|
||||||
|
|||||||
@ -894,7 +894,7 @@ public static function table(Table $table): Table
|
|||||||
|
|
||||||
public static function getEloquentQuery(): Builder
|
public static function getEloquentQuery(): Builder
|
||||||
{
|
{
|
||||||
$tenantId = Tenant::currentOrFail()->getKey();
|
$tenantId = Tenant::current()->getKey();
|
||||||
|
|
||||||
return parent::getEloquentQuery()
|
return parent::getEloquentQuery()
|
||||||
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
||||||
|
|||||||
@ -815,7 +815,7 @@ public static function table(Table $table): Table
|
|||||||
|
|
||||||
public static function getEloquentQuery(): Builder
|
public static function getEloquentQuery(): Builder
|
||||||
{
|
{
|
||||||
$tenantId = Tenant::currentOrFail()->getKey();
|
$tenantId = Tenant::current()->getKey();
|
||||||
|
|
||||||
return parent::getEloquentQuery()
|
return parent::getEloquentQuery()
|
||||||
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
use App\Filament\Concerns\ScopesGlobalSearchToTenant;
|
use App\Filament\Concerns\ScopesGlobalSearchToTenant;
|
||||||
use App\Filament\Resources\ProviderConnectionResource\Pages;
|
use App\Filament\Resources\ProviderConnectionResource\Pages;
|
||||||
use App\Jobs\ProviderComplianceSnapshotJob;
|
use App\Jobs\ProviderComplianceSnapshotJob;
|
||||||
|
use App\Jobs\ProviderConnectionHealthCheckJob;
|
||||||
use App\Jobs\ProviderInventorySyncJob;
|
use App\Jobs\ProviderInventorySyncJob;
|
||||||
use App\Models\OperationRun;
|
use App\Models\OperationRun;
|
||||||
use App\Models\ProviderConnection;
|
use App\Models\ProviderConnection;
|
||||||
@ -14,13 +15,11 @@
|
|||||||
use App\Services\Intune\AuditLogger;
|
use App\Services\Intune\AuditLogger;
|
||||||
use App\Services\Providers\CredentialManager;
|
use App\Services\Providers\CredentialManager;
|
||||||
use App\Services\Providers\ProviderOperationStartGate;
|
use App\Services\Providers\ProviderOperationStartGate;
|
||||||
use App\Services\Verification\StartVerification;
|
|
||||||
use App\Support\Auth\Capabilities;
|
use App\Support\Auth\Capabilities;
|
||||||
use App\Support\Badges\BadgeDomain;
|
use App\Support\Badges\BadgeDomain;
|
||||||
use App\Support\Badges\BadgeRenderer;
|
use App\Support\Badges\BadgeRenderer;
|
||||||
use App\Support\OperationRunLinks;
|
use App\Support\OperationRunLinks;
|
||||||
use App\Support\Rbac\UiEnforcement;
|
use App\Support\Rbac\UiEnforcement;
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use BackedEnum;
|
use BackedEnum;
|
||||||
use Filament\Actions;
|
use Filament\Actions;
|
||||||
use Filament\Forms\Components\TextInput;
|
use Filament\Forms\Components\TextInput;
|
||||||
@ -100,16 +99,9 @@ public static function table(Table $table): Table
|
|||||||
{
|
{
|
||||||
return $table
|
return $table
|
||||||
->modifyQueryUsing(function (Builder $query): Builder {
|
->modifyQueryUsing(function (Builder $query): Builder {
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
|
||||||
$tenantId = Tenant::current()?->getKey();
|
$tenantId = Tenant::current()?->getKey();
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
return $query->when($tenantId, fn (Builder $q) => $q->where('tenant_id', $tenantId));
|
||||||
return $query->whereRaw('1 = 0');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $query
|
|
||||||
->where('workspace_id', (int) $workspaceId)
|
|
||||||
->when($tenantId, fn (Builder $q) => $q->where('tenant_id', $tenantId));
|
|
||||||
})
|
})
|
||||||
->defaultSort('display_name')
|
->defaultSort('display_name')
|
||||||
->columns([
|
->columns([
|
||||||
@ -183,22 +175,29 @@ public static function table(Table $table): Table
|
|||||||
->icon('heroicon-o-check-badge')
|
->icon('heroicon-o-check-badge')
|
||||||
->color('success')
|
->color('success')
|
||||||
->visible(fn (ProviderConnection $record): bool => $record->status !== 'disabled')
|
->visible(fn (ProviderConnection $record): bool => $record->status !== 'disabled')
|
||||||
->action(function (ProviderConnection $record, StartVerification $verification): void {
|
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||||
abort(404);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
$initiator = $user;
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$result = $verification->providerConnectionCheck(
|
$result = $gate->start(
|
||||||
tenant: $tenant,
|
tenant: $tenant,
|
||||||
connection: $record,
|
connection: $record,
|
||||||
initiator: $user,
|
operationType: 'provider.connection.check',
|
||||||
|
dispatcher: function (OperationRun $operationRun) use ($tenant, $initiator, $record): void {
|
||||||
|
ProviderConnectionHealthCheckJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $initiator->getKey(),
|
||||||
|
providerConnectionId: (int) $record->getKey(),
|
||||||
|
operationRun: $operationRun,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
initiator: $initiator,
|
||||||
);
|
);
|
||||||
|
|
||||||
if ($result->status === 'scope_busy') {
|
if ($result->status === 'scope_busy') {
|
||||||
@ -641,17 +640,9 @@ public static function table(Table $table): Table
|
|||||||
|
|
||||||
public static function getEloquentQuery(): Builder
|
public static function getEloquentQuery(): Builder
|
||||||
{
|
{
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
|
||||||
$tenantId = Tenant::current()?->getKey();
|
$tenantId = Tenant::current()?->getKey();
|
||||||
|
|
||||||
$query = parent::getEloquentQuery();
|
return parent::getEloquentQuery()
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
return $query->whereRaw('1 = 0');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $query
|
|
||||||
->where('workspace_id', (int) $workspaceId)
|
|
||||||
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
||||||
->latest('id');
|
->latest('id');
|
||||||
}
|
}
|
||||||
|
|||||||
@ -22,7 +22,6 @@ protected function mutateFormDataBeforeCreate(array $data): array
|
|||||||
$this->shouldMakeDefault = (bool) ($data['is_default'] ?? false);
|
$this->shouldMakeDefault = (bool) ($data['is_default'] ?? false);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'workspace_id' => (int) $tenant->workspace_id,
|
|
||||||
'tenant_id' => $tenant->getKey(),
|
'tenant_id' => $tenant->getKey(),
|
||||||
'provider' => 'microsoft',
|
'provider' => 'microsoft',
|
||||||
'entra_tenant_id' => $data['entra_tenant_id'],
|
'entra_tenant_id' => $data['entra_tenant_id'],
|
||||||
|
|||||||
@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Filament\Resources\ProviderConnectionResource\Pages;
|
namespace App\Filament\Resources\ProviderConnectionResource\Pages;
|
||||||
|
|
||||||
|
use App\Filament\Pages\Onboarding\TenantOnboardingWizard;
|
||||||
use App\Filament\Resources\ProviderConnectionResource;
|
use App\Filament\Resources\ProviderConnectionResource;
|
||||||
use App\Jobs\ProviderComplianceSnapshotJob;
|
use App\Jobs\ProviderComplianceSnapshotJob;
|
||||||
|
use App\Jobs\ProviderConnectionHealthCheckJob;
|
||||||
use App\Jobs\ProviderInventorySyncJob;
|
use App\Jobs\ProviderInventorySyncJob;
|
||||||
use App\Models\OperationRun;
|
use App\Models\OperationRun;
|
||||||
use App\Models\ProviderConnection;
|
use App\Models\ProviderConnection;
|
||||||
@ -13,7 +15,6 @@
|
|||||||
use App\Services\Intune\AuditLogger;
|
use App\Services\Intune\AuditLogger;
|
||||||
use App\Services\Providers\CredentialManager;
|
use App\Services\Providers\CredentialManager;
|
||||||
use App\Services\Providers\ProviderOperationStartGate;
|
use App\Services\Providers\ProviderOperationStartGate;
|
||||||
use App\Services\Verification\StartVerification;
|
|
||||||
use App\Support\Auth\Capabilities;
|
use App\Support\Auth\Capabilities;
|
||||||
use App\Support\OperationRunLinks;
|
use App\Support\OperationRunLinks;
|
||||||
use App\Support\Rbac\UiEnforcement;
|
use App\Support\Rbac\UiEnforcement;
|
||||||
@ -116,6 +117,18 @@ protected function getHeaderActions(): array
|
|||||||
->visible(false),
|
->visible(false),
|
||||||
|
|
||||||
Actions\ActionGroup::make([
|
Actions\ActionGroup::make([
|
||||||
|
UiEnforcement::forAction(
|
||||||
|
Action::make('resume_onboarding')
|
||||||
|
->label('Resume onboarding')
|
||||||
|
->icon('heroicon-o-play')
|
||||||
|
->color('gray')
|
||||||
|
->url(fn (): string => TenantOnboardingWizard::getUrl(tenant: Tenant::current()))
|
||||||
|
)
|
||||||
|
->requireCapability(Capabilities::PROVIDER_VIEW)
|
||||||
|
->tooltip('You do not have permission to view provider onboarding.')
|
||||||
|
->preserveVisibility()
|
||||||
|
->apply(),
|
||||||
|
|
||||||
UiEnforcement::forAction(
|
UiEnforcement::forAction(
|
||||||
Action::make('view_last_check_run')
|
Action::make('view_last_check_run')
|
||||||
->label('View last check run')
|
->label('View last check run')
|
||||||
@ -167,7 +180,7 @@ protected function getHeaderActions(): array
|
|||||||
&& $user->canAccessTenant($tenant)
|
&& $user->canAccessTenant($tenant)
|
||||||
&& $record->status !== 'disabled';
|
&& $record->status !== 'disabled';
|
||||||
})
|
})
|
||||||
->action(function (ProviderConnection $record, StartVerification $verification): void {
|
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
|
|
||||||
@ -185,9 +198,18 @@ protected function getHeaderActions(): array
|
|||||||
|
|
||||||
$initiator = $user;
|
$initiator = $user;
|
||||||
|
|
||||||
$result = $verification->providerConnectionCheck(
|
$result = $gate->start(
|
||||||
tenant: $tenant,
|
tenant: $tenant,
|
||||||
connection: $record,
|
connection: $record,
|
||||||
|
operationType: 'provider.connection.check',
|
||||||
|
dispatcher: function (OperationRun $operationRun) use ($tenant, $initiator, $record): void {
|
||||||
|
ProviderConnectionHealthCheckJob::dispatch(
|
||||||
|
tenantId: (int) $tenant->getKey(),
|
||||||
|
userId: (int) $initiator->getKey(),
|
||||||
|
providerConnectionId: (int) $record->getKey(),
|
||||||
|
operationRun: $operationRun,
|
||||||
|
);
|
||||||
|
},
|
||||||
initiator: $initiator,
|
initiator: $initiator,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@ -87,7 +87,7 @@ public static function form(Schema $schema): Schema
|
|||||||
Forms\Components\Select::make('backup_set_id')
|
Forms\Components\Select::make('backup_set_id')
|
||||||
->label('Backup set')
|
->label('Backup set')
|
||||||
->options(function () {
|
->options(function () {
|
||||||
$tenantId = Tenant::currentOrFail()->getKey();
|
$tenantId = Tenant::current()->getKey();
|
||||||
|
|
||||||
return BackupSet::query()
|
return BackupSet::query()
|
||||||
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
|
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
|
||||||
@ -219,7 +219,7 @@ public static function getWizardSteps(): array
|
|||||||
Forms\Components\Select::make('backup_set_id')
|
Forms\Components\Select::make('backup_set_id')
|
||||||
->label('Backup set')
|
->label('Backup set')
|
||||||
->options(function () {
|
->options(function () {
|
||||||
$tenantId = Tenant::currentOrFail()->getKey();
|
$tenantId = Tenant::current()->getKey();
|
||||||
|
|
||||||
return BackupSet::query()
|
return BackupSet::query()
|
||||||
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
|
->when($tenantId, fn ($query) => $query->where('tenant_id', $tenantId))
|
||||||
|
|||||||
@ -9,7 +9,6 @@
|
|||||||
use App\Jobs\SyncPoliciesJob;
|
use App\Jobs\SyncPoliciesJob;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Auth\CapabilityResolver;
|
use App\Services\Auth\CapabilityResolver;
|
||||||
use App\Services\Auth\RoleCapabilityMap;
|
use App\Services\Auth\RoleCapabilityMap;
|
||||||
use App\Services\Directory\EntraGroupLabelResolver;
|
use App\Services\Directory\EntraGroupLabelResolver;
|
||||||
@ -31,7 +30,6 @@
|
|||||||
use App\Support\OpsUx\OperationUxPresenter;
|
use App\Support\OpsUx\OperationUxPresenter;
|
||||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||||
use App\Support\Rbac\UiEnforcement;
|
use App\Support\Rbac\UiEnforcement;
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use BackedEnum;
|
use BackedEnum;
|
||||||
use Filament\Actions;
|
use Filament\Actions;
|
||||||
use Filament\Actions\ActionGroup;
|
use Filament\Actions\ActionGroup;
|
||||||
@ -72,21 +70,7 @@ public static function canCreate(): bool
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (static::userCanManageAnyTenant($user)) {
|
return static::userCanManageAnyTenant($user);
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('user_id', $user->getKey())
|
|
||||||
->whereIn('role', ['owner', 'manager'])
|
|
||||||
->exists();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function canEdit(Model $record): bool
|
public static function canEdit(Model $record): bool
|
||||||
@ -195,15 +179,8 @@ public static function getEloquentQuery(): Builder
|
|||||||
return parent::getEloquentQuery()->whereRaw('1 = 0');
|
return parent::getEloquentQuery()->whereRaw('1 = 0');
|
||||||
}
|
}
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
return parent::getEloquentQuery()->whereRaw('1 = 0');
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenantIds = $user->tenants()
|
$tenantIds = $user->tenants()
|
||||||
->withTrashed()
|
->withTrashed()
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->pluck('tenants.id');
|
->pluck('tenants.id');
|
||||||
|
|
||||||
return parent::getEloquentQuery()
|
return parent::getEloquentQuery()
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Filament\Resources\TenantResource\Pages;
|
namespace App\Filament\Resources\TenantResource\Pages;
|
||||||
|
|
||||||
|
use App\Filament\Pages\Onboarding\TenantOnboardingWizard;
|
||||||
use App\Filament\Resources\TenantResource;
|
use App\Filament\Resources\TenantResource;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Resources\Pages\CreateRecord;
|
use Filament\Resources\Pages\CreateRecord;
|
||||||
|
|
||||||
class CreateTenant extends CreateRecord
|
class CreateTenant extends CreateRecord
|
||||||
@ -12,16 +12,20 @@ class CreateTenant extends CreateRecord
|
|||||||
protected static string $resource = TenantResource::class;
|
protected static string $resource = TenantResource::class;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Prevent setting legacy tenant credentials during create.
|
||||||
|
* Credential setup should happen via the onboarding flow.
|
||||||
|
*
|
||||||
* @param array<string, mixed> $data
|
* @param array<string, mixed> $data
|
||||||
* @return array<string, mixed>
|
* @return array<string, mixed>
|
||||||
*/
|
*/
|
||||||
protected function mutateFormDataBeforeCreate(array $data): array
|
protected function mutateFormDataBeforeCreate(array $data): array
|
||||||
{
|
{
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
unset(
|
||||||
|
$data['app_client_id'],
|
||||||
if ($workspaceId !== null) {
|
$data['app_client_secret'],
|
||||||
$data['workspace_id'] = $workspaceId;
|
$data['app_certificate_thumbprint'],
|
||||||
}
|
$data['app_notes'],
|
||||||
|
);
|
||||||
|
|
||||||
return $data;
|
return $data;
|
||||||
}
|
}
|
||||||
@ -38,4 +42,9 @@ protected function afterCreate(): void
|
|||||||
$this->record->getKey() => ['role' => 'owner'],
|
$this->record->getKey() => ['role' => 'owner'],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function getRedirectUrl(): string
|
||||||
|
{
|
||||||
|
return TenantOnboardingWizard::getUrl(tenant: $this->record);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Filament\Resources\TenantResource\Pages;
|
namespace App\Filament\Resources\TenantResource\Pages;
|
||||||
|
|
||||||
|
use App\Filament\Pages\Onboarding\TenantOnboardingWizard;
|
||||||
use App\Filament\Resources\TenantResource;
|
use App\Filament\Resources\TenantResource;
|
||||||
use App\Filament\Widgets\Tenant\TenantArchivedBanner;
|
use App\Filament\Widgets\Tenant\TenantArchivedBanner;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
@ -30,6 +31,17 @@ protected function getHeaderActions(): array
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
Actions\ActionGroup::make([
|
Actions\ActionGroup::make([
|
||||||
|
UiEnforcement::forAction(
|
||||||
|
Actions\Action::make('resume_onboarding')
|
||||||
|
->label('Resume onboarding')
|
||||||
|
->icon('heroicon-o-play')
|
||||||
|
->color('gray')
|
||||||
|
->url(fn (Tenant $record): string => TenantOnboardingWizard::getUrl(tenant: $record))
|
||||||
|
)
|
||||||
|
->requireCapability(Capabilities::PROVIDER_VIEW)
|
||||||
|
->tooltip('You do not have permission to view provider onboarding.')
|
||||||
|
->preserveVisibility()
|
||||||
|
->apply(),
|
||||||
UiEnforcement::forAction(
|
UiEnforcement::forAction(
|
||||||
Actions\Action::make('edit')
|
Actions\Action::make('edit')
|
||||||
->label('Edit')
|
->label('Edit')
|
||||||
|
|||||||
@ -25,22 +25,11 @@ public function table(Table $table): Table
|
|||||||
return $table
|
return $table
|
||||||
->modifyQueryUsing(fn (Builder $query) => $query->with('user'))
|
->modifyQueryUsing(fn (Builder $query) => $query->with('user'))
|
||||||
->columns([
|
->columns([
|
||||||
Tables\Columns\TextColumn::make('user.email')
|
Tables\Columns\TextColumn::make('user.name')
|
||||||
->label(__('User'))
|
->label(__('User'))
|
||||||
->searchable(),
|
->searchable(),
|
||||||
Tables\Columns\TextColumn::make('user_domain')
|
Tables\Columns\TextColumn::make('user.email')
|
||||||
->label(__('Domain'))
|
->label(__('Email'))
|
||||||
->getStateUsing(function (TenantMembership $record): ?string {
|
|
||||||
$email = $record->user?->email;
|
|
||||||
|
|
||||||
if (! is_string($email) || $email === '' || ! str_contains($email, '@')) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (string) str($email)->after('@')->lower();
|
|
||||||
}),
|
|
||||||
Tables\Columns\TextColumn::make('user.name')
|
|
||||||
->label(__('Name'))
|
|
||||||
->toggleable(isToggledHiddenByDefault: true),
|
->toggleable(isToggledHiddenByDefault: true),
|
||||||
Tables\Columns\TextColumn::make('role')
|
Tables\Columns\TextColumn::make('role')
|
||||||
->badge()
|
->badge()
|
||||||
@ -60,13 +49,7 @@ public function table(Table $table): Table
|
|||||||
->label(__('User'))
|
->label(__('User'))
|
||||||
->required()
|
->required()
|
||||||
->searchable()
|
->searchable()
|
||||||
->options(fn () => User::query()
|
->options(fn () => User::query()->orderBy('name')->pluck('name', 'id')->all()),
|
||||||
->orderBy('email')
|
|
||||||
->get(['id', 'name', 'email'])
|
|
||||||
->mapWithKeys(fn (User $user): array => [
|
|
||||||
(string) $user->id => trim((string) ($user->name ? "{$user->name} ({$user->email})" : $user->email)),
|
|
||||||
])
|
|
||||||
->all()),
|
|
||||||
Forms\Components\Select::make('role')
|
Forms\Components\Select::make('role')
|
||||||
->label(__('Role'))
|
->label(__('Role'))
|
||||||
->required()
|
->required()
|
||||||
|
|||||||
@ -1,35 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces\Pages;
|
|
||||||
|
|
||||||
use App\Filament\Resources\Workspaces\WorkspaceResource;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Resources\Pages\CreateRecord;
|
|
||||||
|
|
||||||
class CreateWorkspace extends CreateRecord
|
|
||||||
{
|
|
||||||
protected static string $resource = WorkspaceResource::class;
|
|
||||||
|
|
||||||
protected function afterCreate(): void
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
WorkspaceMembership::query()->firstOrCreate(
|
|
||||||
[
|
|
||||||
'workspace_id' => $this->record->getKey(),
|
|
||||||
'user_id' => $user->getKey(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
'role' => 'owner',
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
app(WorkspaceContext::class)->setCurrentWorkspace($this->record, $user, request());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces\Pages;
|
|
||||||
|
|
||||||
use App\Filament\Resources\Workspaces\WorkspaceResource;
|
|
||||||
use Filament\Resources\Pages\EditRecord;
|
|
||||||
|
|
||||||
class EditWorkspace extends EditRecord
|
|
||||||
{
|
|
||||||
protected static string $resource = WorkspaceResource::class;
|
|
||||||
}
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces\Pages;
|
|
||||||
|
|
||||||
use App\Filament\Resources\Workspaces\WorkspaceResource;
|
|
||||||
use Filament\Actions;
|
|
||||||
use Filament\Resources\Pages\ListRecords;
|
|
||||||
|
|
||||||
class ListWorkspaces extends ListRecords
|
|
||||||
{
|
|
||||||
protected static string $resource = WorkspaceResource::class;
|
|
||||||
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
Actions\CreateAction::make(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces\Pages;
|
|
||||||
|
|
||||||
use App\Filament\Resources\Workspaces\WorkspaceResource;
|
|
||||||
use Filament\Actions;
|
|
||||||
use Filament\Resources\Pages\ViewRecord;
|
|
||||||
|
|
||||||
class ViewWorkspace extends ViewRecord
|
|
||||||
{
|
|
||||||
protected static string $resource = WorkspaceResource::class;
|
|
||||||
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
Actions\EditAction::make(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,221 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces\RelationManagers;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Auth\WorkspaceMembershipManager;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
use App\Support\Rbac\WorkspaceUiEnforcement;
|
|
||||||
use Filament\Actions\Action;
|
|
||||||
use Filament\Forms;
|
|
||||||
use Filament\Notifications\Notification;
|
|
||||||
use Filament\Resources\RelationManagers\RelationManager;
|
|
||||||
use Filament\Tables;
|
|
||||||
use Filament\Tables\Table;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class WorkspaceMembershipsRelationManager extends RelationManager
|
|
||||||
{
|
|
||||||
protected static string $relationship = 'memberships';
|
|
||||||
|
|
||||||
public function table(Table $table): Table
|
|
||||||
{
|
|
||||||
return $table
|
|
||||||
->modifyQueryUsing(fn (Builder $query) => $query->with('user'))
|
|
||||||
->columns([
|
|
||||||
Tables\Columns\TextColumn::make('user.email')
|
|
||||||
->label(__('User'))
|
|
||||||
->searchable(),
|
|
||||||
Tables\Columns\TextColumn::make('user_domain')
|
|
||||||
->label(__('Domain'))
|
|
||||||
->getStateUsing(function (WorkspaceMembership $record): ?string {
|
|
||||||
$email = $record->user?->email;
|
|
||||||
|
|
||||||
if (! is_string($email) || $email === '' || ! str_contains($email, '@')) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (string) str($email)->after('@')->lower();
|
|
||||||
}),
|
|
||||||
Tables\Columns\TextColumn::make('user.name')
|
|
||||||
->label(__('Name'))
|
|
||||||
->toggleable(isToggledHiddenByDefault: true),
|
|
||||||
Tables\Columns\TextColumn::make('role')
|
|
||||||
->badge()
|
|
||||||
->sortable(),
|
|
||||||
Tables\Columns\TextColumn::make('created_at')->since(),
|
|
||||||
])
|
|
||||||
->headerActions([
|
|
||||||
WorkspaceUiEnforcement::forTableAction(
|
|
||||||
Action::make('add_member')
|
|
||||||
->label(__('Add member'))
|
|
||||||
->icon('heroicon-o-plus')
|
|
||||||
->form([
|
|
||||||
Forms\Components\Select::make('user_id')
|
|
||||||
->label(__('User'))
|
|
||||||
->required()
|
|
||||||
->searchable()
|
|
||||||
->options(fn () => User::query()
|
|
||||||
->orderBy('email')
|
|
||||||
->get(['id', 'name', 'email'])
|
|
||||||
->mapWithKeys(fn (User $user): array => [
|
|
||||||
(string) $user->id => trim((string) ($user->name ? "{$user->name} ({$user->email})" : $user->email)),
|
|
||||||
])
|
|
||||||
->all()),
|
|
||||||
Forms\Components\Select::make('role')
|
|
||||||
->label(__('Role'))
|
|
||||||
->required()
|
|
||||||
->options([
|
|
||||||
WorkspaceRole::Owner->value => __('Owner'),
|
|
||||||
WorkspaceRole::Manager->value => __('Manager'),
|
|
||||||
WorkspaceRole::Operator->value => __('Operator'),
|
|
||||||
WorkspaceRole::Readonly->value => __('Readonly'),
|
|
||||||
]),
|
|
||||||
])
|
|
||||||
->action(function (array $data, WorkspaceMembershipManager $manager): void {
|
|
||||||
$workspace = $this->getOwnerRecord();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$actor = auth()->user();
|
|
||||||
if (! $actor instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$member = User::query()->find((int) $data['user_id']);
|
|
||||||
if (! $member) {
|
|
||||||
Notification::make()->title(__('User not found'))->danger()->send();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$manager->addMember(
|
|
||||||
workspace: $workspace,
|
|
||||||
actor: $actor,
|
|
||||||
member: $member,
|
|
||||||
role: (string) $data['role'],
|
|
||||||
source: 'manual',
|
|
||||||
);
|
|
||||||
} catch (\Throwable $throwable) {
|
|
||||||
Notification::make()
|
|
||||||
->title(__('Failed to add member'))
|
|
||||||
->body($throwable->getMessage())
|
|
||||||
->danger()
|
|
||||||
->send();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Notification::make()->title(__('Member added'))->success()->send();
|
|
||||||
$this->resetTable();
|
|
||||||
}),
|
|
||||||
fn () => $this->getOwnerRecord(),
|
|
||||||
)
|
|
||||||
->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
|
|
||||||
->tooltip('You do not have permission to manage workspace memberships.')
|
|
||||||
->apply(),
|
|
||||||
])
|
|
||||||
->actions([
|
|
||||||
WorkspaceUiEnforcement::forTableAction(
|
|
||||||
Action::make('change_role')
|
|
||||||
->label(__('Change role'))
|
|
||||||
->icon('heroicon-o-pencil')
|
|
||||||
->requiresConfirmation()
|
|
||||||
->form([
|
|
||||||
Forms\Components\Select::make('role')
|
|
||||||
->label(__('Role'))
|
|
||||||
->required()
|
|
||||||
->options([
|
|
||||||
WorkspaceRole::Owner->value => __('Owner'),
|
|
||||||
WorkspaceRole::Manager->value => __('Manager'),
|
|
||||||
WorkspaceRole::Operator->value => __('Operator'),
|
|
||||||
WorkspaceRole::Readonly->value => __('Readonly'),
|
|
||||||
]),
|
|
||||||
])
|
|
||||||
->action(function (WorkspaceMembership $record, array $data, WorkspaceMembershipManager $manager): void {
|
|
||||||
$workspace = $this->getOwnerRecord();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$actor = auth()->user();
|
|
||||||
if (! $actor instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$manager->changeRole(
|
|
||||||
workspace: $workspace,
|
|
||||||
actor: $actor,
|
|
||||||
membership: $record,
|
|
||||||
newRole: (string) $data['role'],
|
|
||||||
);
|
|
||||||
} catch (\Throwable $throwable) {
|
|
||||||
Notification::make()
|
|
||||||
->title(__('Failed to change role'))
|
|
||||||
->body($throwable->getMessage())
|
|
||||||
->danger()
|
|
||||||
->send();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Notification::make()->title(__('Role updated'))->success()->send();
|
|
||||||
$this->resetTable();
|
|
||||||
}),
|
|
||||||
fn () => $this->getOwnerRecord(),
|
|
||||||
)
|
|
||||||
->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
|
|
||||||
->tooltip('You do not have permission to manage workspace memberships.')
|
|
||||||
->apply(),
|
|
||||||
|
|
||||||
WorkspaceUiEnforcement::forTableAction(
|
|
||||||
Action::make('remove')
|
|
||||||
->label(__('Remove'))
|
|
||||||
->color('danger')
|
|
||||||
->icon('heroicon-o-x-mark')
|
|
||||||
->requiresConfirmation()
|
|
||||||
->action(function (WorkspaceMembership $record, WorkspaceMembershipManager $manager): void {
|
|
||||||
$workspace = $this->getOwnerRecord();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$actor = auth()->user();
|
|
||||||
if (! $actor instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$manager->removeMember(workspace: $workspace, actor: $actor, membership: $record);
|
|
||||||
} catch (\Throwable $throwable) {
|
|
||||||
Notification::make()
|
|
||||||
->title(__('Failed to remove member'))
|
|
||||||
->body($throwable->getMessage())
|
|
||||||
->danger()
|
|
||||||
->send();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Notification::make()->title(__('Member removed'))->success()->send();
|
|
||||||
$this->resetTable();
|
|
||||||
}),
|
|
||||||
fn () => $this->getOwnerRecord(),
|
|
||||||
)
|
|
||||||
->requireCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)
|
|
||||||
->tooltip('You do not have permission to manage workspace memberships.')
|
|
||||||
->destructive()
|
|
||||||
->apply(),
|
|
||||||
])
|
|
||||||
->bulkActions([]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,79 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Filament\Resources\Workspaces;
|
|
||||||
|
|
||||||
use App\Filament\Resources\Workspaces\RelationManagers\WorkspaceMembershipsRelationManager;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use BackedEnum;
|
|
||||||
use Filament\Actions;
|
|
||||||
use Filament\Forms;
|
|
||||||
use Filament\Resources\Resource;
|
|
||||||
use Filament\Schemas\Schema;
|
|
||||||
use Filament\Tables;
|
|
||||||
use Filament\Tables\Table;
|
|
||||||
use UnitEnum;
|
|
||||||
|
|
||||||
class WorkspaceResource extends Resource
|
|
||||||
{
|
|
||||||
protected static ?string $model = Workspace::class;
|
|
||||||
|
|
||||||
protected static bool $isDiscovered = false;
|
|
||||||
|
|
||||||
protected static bool $isScopedToTenant = false;
|
|
||||||
|
|
||||||
protected static ?string $recordTitleAttribute = 'name';
|
|
||||||
|
|
||||||
protected static bool $shouldRegisterNavigation = false;
|
|
||||||
|
|
||||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-squares-2x2';
|
|
||||||
|
|
||||||
protected static string|UnitEnum|null $navigationGroup = 'Settings';
|
|
||||||
|
|
||||||
public static function form(Schema $schema): Schema
|
|
||||||
{
|
|
||||||
return $schema
|
|
||||||
->schema([
|
|
||||||
Forms\Components\TextInput::make('name')
|
|
||||||
->required()
|
|
||||||
->maxLength(255),
|
|
||||||
Forms\Components\TextInput::make('slug')
|
|
||||||
->required()
|
|
||||||
->maxLength(255)
|
|
||||||
->unique(ignoreRecord: true),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function table(Table $table): Table
|
|
||||||
{
|
|
||||||
return $table
|
|
||||||
->columns([
|
|
||||||
Tables\Columns\TextColumn::make('name')
|
|
||||||
->searchable()
|
|
||||||
->sortable(),
|
|
||||||
Tables\Columns\TextColumn::make('slug')
|
|
||||||
->searchable()
|
|
||||||
->sortable(),
|
|
||||||
])
|
|
||||||
->actions([
|
|
||||||
Actions\ViewAction::make(),
|
|
||||||
Actions\EditAction::make(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function getPages(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'index' => Pages\ListWorkspaces::route('/'),
|
|
||||||
'create' => Pages\CreateWorkspace::route('/create'),
|
|
||||||
'view' => Pages\ViewWorkspace::route('/{record}'),
|
|
||||||
'edit' => Pages\EditWorkspace::route('/{record}/edit'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function getRelations(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
WorkspaceMembershipsRelationManager::class,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Support;
|
|
||||||
|
|
||||||
use App\Models\OperationRun;
|
|
||||||
|
|
||||||
final class VerificationReportChangeIndicator
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @return array{state: 'no_changes'|'changed', previous_report_id: int}|null
|
|
||||||
*/
|
|
||||||
public static function forRun(OperationRun $run): ?array
|
|
||||||
{
|
|
||||||
$report = VerificationReportViewer::report($run);
|
|
||||||
|
|
||||||
if ($report === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$previousRun = VerificationReportViewer::previousRun($run, $report);
|
|
||||||
|
|
||||||
if ($previousRun === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$previousReport = VerificationReportViewer::report($previousRun);
|
|
||||||
|
|
||||||
if ($previousReport === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$currentFingerprint = VerificationReportViewer::fingerprint($report);
|
|
||||||
$previousFingerprint = VerificationReportViewer::fingerprint($previousReport);
|
|
||||||
|
|
||||||
if ($currentFingerprint === null || $previousFingerprint === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'state' => $currentFingerprint === $previousFingerprint ? 'no_changes' : 'changed',
|
|
||||||
'previous_report_id' => (int) $previousRun->getKey(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ -1,92 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\Support;
|
|
||||||
|
|
||||||
use App\Models\OperationRun;
|
|
||||||
use App\Support\Verification\VerificationReportFingerprint;
|
|
||||||
use App\Support\Verification\VerificationReportSanitizer;
|
|
||||||
use App\Support\Verification\VerificationReportSchema;
|
|
||||||
|
|
||||||
final class VerificationReportViewer
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @return array<string, mixed>|null
|
|
||||||
*/
|
|
||||||
public static function report(OperationRun $run): ?array
|
|
||||||
{
|
|
||||||
$context = is_array($run->context) ? $run->context : [];
|
|
||||||
$report = $context['verification_report'] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($report)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$report = VerificationReportSanitizer::sanitizeReport($report);
|
|
||||||
|
|
||||||
if (! VerificationReportSchema::isValidReport($report)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $report;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function previousReportId(array $report): ?int
|
|
||||||
{
|
|
||||||
$previousReportId = $report['previous_report_id'] ?? null;
|
|
||||||
|
|
||||||
if (is_int($previousReportId) && $previousReportId > 0) {
|
|
||||||
return $previousReportId;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_string($previousReportId) && ctype_digit(trim($previousReportId))) {
|
|
||||||
return (int) trim($previousReportId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function fingerprint(array $report): ?string
|
|
||||||
{
|
|
||||||
$fingerprint = $report['fingerprint'] ?? null;
|
|
||||||
|
|
||||||
if (is_string($fingerprint)) {
|
|
||||||
$fingerprint = strtolower(trim($fingerprint));
|
|
||||||
|
|
||||||
if (preg_match('/^[a-f0-9]{64}$/', $fingerprint)) {
|
|
||||||
return $fingerprint;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return VerificationReportFingerprint::forReport($report);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function previousRun(OperationRun $run, array $report): ?OperationRun
|
|
||||||
{
|
|
||||||
$previousReportId = self::previousReportId($report);
|
|
||||||
|
|
||||||
if ($previousReportId === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$previous = OperationRun::query()
|
|
||||||
->whereKey($previousReportId)
|
|
||||||
->where('tenant_id', (int) $run->tenant_id)
|
|
||||||
->where('workspace_id', (int) $run->workspace_id)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
return $previous instanceof OperationRun ? $previous : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function shouldRenderForRun(OperationRun $run): bool
|
|
||||||
{
|
|
||||||
$context = is_array($run->context) ? $run->context : [];
|
|
||||||
|
|
||||||
if (array_key_exists('verification_report', $context)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return in_array((string) $run->type, ['provider.connection.check'], true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,169 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Filament\System\Pages;
|
|
||||||
|
|
||||||
use App\Models\PlatformUser;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Audit\WorkspaceAuditLogger;
|
|
||||||
use App\Services\Auth\BreakGlassSession;
|
|
||||||
use App\Support\Audit\AuditActionId;
|
|
||||||
use App\Support\Auth\PlatformCapabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
use Filament\Actions\Action;
|
|
||||||
use Filament\Forms\Components\Select;
|
|
||||||
use Filament\Forms\Components\Textarea;
|
|
||||||
use Filament\Notifications\Notification;
|
|
||||||
use Filament\Pages\Page;
|
|
||||||
|
|
||||||
class RepairWorkspaceOwners extends Page
|
|
||||||
{
|
|
||||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-wrench-screwdriver';
|
|
||||||
|
|
||||||
protected static ?string $navigationLabel = 'Repair workspace owners';
|
|
||||||
|
|
||||||
protected static string|\UnitEnum|null $navigationGroup = 'Recovery';
|
|
||||||
|
|
||||||
protected string $view = 'filament.system.pages.repair-workspace-owners';
|
|
||||||
|
|
||||||
public static function canAccess(): bool
|
|
||||||
{
|
|
||||||
$user = auth('platform')->user();
|
|
||||||
|
|
||||||
if (! $user instanceof PlatformUser) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $user->hasCapability(PlatformCapabilities::USE_BREAK_GLASS);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<Action>
|
|
||||||
*/
|
|
||||||
protected function getHeaderActions(): array
|
|
||||||
{
|
|
||||||
$breakGlass = app(BreakGlassSession::class);
|
|
||||||
|
|
||||||
return [
|
|
||||||
Action::make('assign_owner')
|
|
||||||
->label('Assign owner (break-glass)')
|
|
||||||
->color('danger')
|
|
||||||
->requiresConfirmation()
|
|
||||||
->modalHeading('Assign workspace owner')
|
|
||||||
->modalDescription('This is a recovery action. It is audited and should only be used when the workspace owner set is broken.')
|
|
||||||
->form([
|
|
||||||
Select::make('workspace_id')
|
|
||||||
->label('Workspace')
|
|
||||||
->required()
|
|
||||||
->searchable()
|
|
||||||
->getSearchResultsUsing(function (string $search): array {
|
|
||||||
return Workspace::query()
|
|
||||||
->where('name', 'like', "%{$search}%")
|
|
||||||
->orderBy('name')
|
|
||||||
->limit(25)
|
|
||||||
->pluck('name', 'id')
|
|
||||||
->all();
|
|
||||||
})
|
|
||||||
->getOptionLabelUsing(function ($value): ?string {
|
|
||||||
if (! is_numeric($value)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Workspace::query()->whereKey((int) $value)->value('name');
|
|
||||||
}),
|
|
||||||
|
|
||||||
Select::make('target_user_id')
|
|
||||||
->label('User')
|
|
||||||
->required()
|
|
||||||
->searchable()
|
|
||||||
->getSearchResultsUsing(function (string $search): array {
|
|
||||||
return User::query()
|
|
||||||
->where('email', 'like', "%{$search}%")
|
|
||||||
->orderBy('email')
|
|
||||||
->limit(25)
|
|
||||||
->pluck('email', 'id')
|
|
||||||
->all();
|
|
||||||
})
|
|
||||||
->getOptionLabelUsing(function ($value): ?string {
|
|
||||||
if (! is_numeric($value)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return User::query()->whereKey((int) $value)->value('email');
|
|
||||||
}),
|
|
||||||
|
|
||||||
Textarea::make('reason')
|
|
||||||
->label('Reason')
|
|
||||||
->required()
|
|
||||||
->minLength(5)
|
|
||||||
->maxLength(500)
|
|
||||||
->rows(4),
|
|
||||||
])
|
|
||||||
->action(function (array $data, BreakGlassSession $breakGlass, WorkspaceAuditLogger $auditLogger): void {
|
|
||||||
$platformUser = auth('platform')->user();
|
|
||||||
|
|
||||||
if (! $platformUser instanceof PlatformUser) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $platformUser->hasCapability(PlatformCapabilities::USE_BREAK_GLASS)) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $breakGlass->isActive()) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceId = (int) ($data['workspace_id'] ?? 0);
|
|
||||||
$targetUserId = (int) ($data['target_user_id'] ?? 0);
|
|
||||||
$reason = (string) ($data['reason'] ?? '');
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->whereKey($workspaceId)->firstOrFail();
|
|
||||||
$targetUser = User::query()->whereKey($targetUserId)->firstOrFail();
|
|
||||||
|
|
||||||
$membership = WorkspaceMembership::query()->firstOrNew([
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'user_id' => (int) $targetUser->getKey(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$fromRole = $membership->exists ? (string) $membership->role : null;
|
|
||||||
|
|
||||||
$membership->forceFill([
|
|
||||||
'role' => WorkspaceRole::Owner->value,
|
|
||||||
])->save();
|
|
||||||
|
|
||||||
$auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipBreakGlassAssignOwner->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'actor_user_id' => (int) $platformUser->getKey(),
|
|
||||||
'target_user_id' => (int) $targetUser->getKey(),
|
|
||||||
'attempted_role' => WorkspaceRole::Owner->value,
|
|
||||||
'from_role' => $fromRole,
|
|
||||||
'reason' => trim($reason),
|
|
||||||
'source' => 'break_glass',
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: null,
|
|
||||||
status: 'success',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
actorId: (int) $platformUser->getKey(),
|
|
||||||
actorEmail: $platformUser->email,
|
|
||||||
actorName: $platformUser->name,
|
|
||||||
);
|
|
||||||
|
|
||||||
Notification::make()
|
|
||||||
->title('Owner assigned')
|
|
||||||
->success()
|
|
||||||
->send();
|
|
||||||
})
|
|
||||||
->disabled(fn (): bool => ! $breakGlass->isActive()),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,72 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use App\Filament\Pages\TenantDashboard;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\UserTenantPreference;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Illuminate\Http\RedirectResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
final class SelectTenantController
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request): RedirectResponse
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);
|
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
return redirect()->to('/admin/choose-workspace');
|
|
||||||
}
|
|
||||||
|
|
||||||
$validated = $request->validate([
|
|
||||||
'tenant_id' => ['required', 'integer'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant = Tenant::query()
|
|
||||||
->where('status', 'active')
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->whereKey($validated['tenant_id'])
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $user->canAccessTenant($tenant)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->persistLastTenant($user, $tenant);
|
|
||||||
|
|
||||||
return redirect()->to(TenantDashboard::getUrl(tenant: $tenant));
|
|
||||||
}
|
|
||||||
|
|
||||||
private function persistLastTenant(User $user, Tenant $tenant): void
|
|
||||||
{
|
|
||||||
if (Schema::hasColumn('users', 'last_tenant_id')) {
|
|
||||||
$user->forceFill(['last_tenant_id' => $tenant->getKey()])->save();
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! Schema::hasTable('user_tenant_preferences')) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
UserTenantPreference::query()->updateOrCreate(
|
|
||||||
['user_id' => $user->getKey(), 'tenant_id' => $tenant->getKey()],
|
|
||||||
['last_used_at' => now()]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,67 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use App\Filament\Pages\ChooseTenant;
|
|
||||||
use App\Filament\Pages\TenantDashboard;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Illuminate\Http\RedirectResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
final class SwitchWorkspaceController
|
|
||||||
{
|
|
||||||
public function __invoke(Request $request): RedirectResponse
|
|
||||||
{
|
|
||||||
$user = auth()->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$validated = $request->validate([
|
|
||||||
'workspace_id' => ['required', 'integer'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->whereKey($validated['workspace_id'])->first();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! empty($workspace->archived_at)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$context = app(WorkspaceContext::class);
|
|
||||||
|
|
||||||
if (! $context->isMember($user, $workspace)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$context->setCurrentWorkspace($workspace, $user, $request);
|
|
||||||
|
|
||||||
$tenantsQuery = $user->tenants()
|
|
||||||
->where('workspace_id', $workspace->getKey())
|
|
||||||
->where('status', 'active');
|
|
||||||
|
|
||||||
$tenantCount = (int) $tenantsQuery->count();
|
|
||||||
|
|
||||||
if ($tenantCount === 0) {
|
|
||||||
return redirect()->route('admin.onboarding');
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenantCount === 1) {
|
|
||||||
$tenant = $tenantsQuery->first();
|
|
||||||
|
|
||||||
if ($tenant !== null) {
|
|
||||||
return redirect()->to(TenantDashboard::getUrl(tenant: $tenant));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return redirect()->to(ChooseTenant::getUrl());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,51 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use App\Support\Workspaces\WorkspaceResolver;
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
|
|
||||||
class EnsureWorkspaceMember
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next): Response
|
|
||||||
{
|
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceParam = $request->route()?->parameter('workspace');
|
|
||||||
|
|
||||||
$workspace = $workspaceParam instanceof Workspace
|
|
||||||
? $workspaceParam
|
|
||||||
: (is_scalar($workspaceParam)
|
|
||||||
? app(WorkspaceResolver::class)->resolve((string) $workspaceParam)
|
|
||||||
: null);
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var WorkspaceContext $context */
|
|
||||||
$context = app(WorkspaceContext::class);
|
|
||||||
|
|
||||||
if (! $context->isMember($user, $workspace)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$context->setCurrentWorkspace($workspace, $user, $request);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,80 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Response as HttpResponse;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
|
|
||||||
class EnsureWorkspaceSelected
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next): Response
|
|
||||||
{
|
|
||||||
$routeName = $request->route()?->getName();
|
|
||||||
|
|
||||||
if (is_string($routeName) && str_contains($routeName, '.auth.')) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$path = '/'.ltrim($request->path(), '/');
|
|
||||||
|
|
||||||
if (str_starts_with($path, '/admin/t/')) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($path === '/livewire/update') {
|
|
||||||
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
|
|
||||||
$refererPath = '/'.ltrim((string) $refererPath, '/');
|
|
||||||
|
|
||||||
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (in_array($path, ['/admin/no-access', '/admin/choose-workspace'], true)) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var WorkspaceContext $context */
|
|
||||||
$context = app(WorkspaceContext::class);
|
|
||||||
|
|
||||||
$workspace = $context->resolveInitialWorkspaceFor($user, $request);
|
|
||||||
|
|
||||||
if ($workspace !== null) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$membershipQuery = WorkspaceMembership::query()->where('user_id', $user->getKey());
|
|
||||||
|
|
||||||
$hasAnyActiveMembership = Schema::hasColumn('workspaces', 'archived_at')
|
|
||||||
? $membershipQuery
|
|
||||||
->join('workspaces', 'workspace_memberships.workspace_id', '=', 'workspaces.id')
|
|
||||||
->whereNull('workspaces.archived_at')
|
|
||||||
->exists()
|
|
||||||
: $membershipQuery->exists();
|
|
||||||
|
|
||||||
$target = $hasAnyActiveMembership ? '/admin/choose-workspace' : '/admin/no-access';
|
|
||||||
|
|
||||||
return new HttpResponse('', 302, ['Location' => $target]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
142
app/Jobs/Onboarding/OnboardingConnectionDiagnosticsJob.php
Normal file
142
app/Jobs/Onboarding/OnboardingConnectionDiagnosticsJob.php
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Jobs\Onboarding;
|
||||||
|
|
||||||
|
use App\Jobs\Middleware\TrackOperationRun;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Onboarding\OnboardingEvidenceWriter;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunOutcome;
|
||||||
|
use App\Support\OperationRunStatus;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class OnboardingConnectionDiagnosticsJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public ?OperationRun $operationRun = null;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public int $tenantId,
|
||||||
|
public int $userId,
|
||||||
|
public int $providerConnectionId,
|
||||||
|
public int $onboardingSessionId,
|
||||||
|
?OperationRun $operationRun = null,
|
||||||
|
) {
|
||||||
|
$this->operationRun = $operationRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, object>
|
||||||
|
*/
|
||||||
|
public function middleware(): array
|
||||||
|
{
|
||||||
|
return [new TrackOperationRun];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(OnboardingEvidenceWriter $evidence, OperationRunService $runs): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::query()->find($this->tenantId);
|
||||||
|
if (! $tenant instanceof Tenant) {
|
||||||
|
throw new RuntimeException('Tenant not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = User::query()->find($this->userId);
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
throw new RuntimeException('User not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->onboardingSessionId);
|
||||||
|
|
||||||
|
if (! $session instanceof OnboardingSession) {
|
||||||
|
throw new RuntimeException('OnboardingSession not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->providerConnectionId);
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
throw new RuntimeException('ProviderConnection not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = (string) ($connection->status ?? 'unknown');
|
||||||
|
$health = (string) ($connection->health_status ?? 'unknown');
|
||||||
|
|
||||||
|
$evidenceStatus = 'unknown';
|
||||||
|
$reasonCode = null;
|
||||||
|
$message = 'No health check data available yet.';
|
||||||
|
|
||||||
|
if ($status !== 'connected') {
|
||||||
|
$evidenceStatus = 'blocked';
|
||||||
|
$reasonCode = 'provider.needs_consent';
|
||||||
|
$message = 'Provider connection is not connected. Admin consent may be required.';
|
||||||
|
} elseif ($health === 'healthy') {
|
||||||
|
$evidenceStatus = 'ok';
|
||||||
|
$message = 'Provider connection appears healthy.';
|
||||||
|
} elseif ($health === 'unhealthy') {
|
||||||
|
$evidenceStatus = 'error';
|
||||||
|
$reasonCode = is_string($connection->last_error_reason_code) ? $connection->last_error_reason_code : 'provider.outage';
|
||||||
|
$message = is_string($connection->last_error_message) && trim($connection->last_error_message) !== ''
|
||||||
|
? $connection->last_error_message
|
||||||
|
: 'Provider connection health check indicates an error.';
|
||||||
|
}
|
||||||
|
|
||||||
|
$evidence->record(
|
||||||
|
tenant: $tenant,
|
||||||
|
taskType: OnboardingTaskType::ConnectionDiagnostics,
|
||||||
|
status: $evidenceStatus,
|
||||||
|
reasonCode: $reasonCode,
|
||||||
|
message: $message,
|
||||||
|
payload: [
|
||||||
|
'status' => $status,
|
||||||
|
'health_status' => $health,
|
||||||
|
'last_health_check_at' => $connection->last_health_check_at?->toIso8601String(),
|
||||||
|
'last_error_reason_code' => $connection->last_error_reason_code,
|
||||||
|
],
|
||||||
|
session: $session,
|
||||||
|
providerConnection: $connection,
|
||||||
|
operationRun: $this->operationRun,
|
||||||
|
recordedBy: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $this->operationRun instanceof OperationRun) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($evidenceStatus === 'ok') {
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Succeeded->value,
|
||||||
|
);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Failed->value,
|
||||||
|
failures: [[
|
||||||
|
'code' => 'onboarding.connection.diagnostics.failed',
|
||||||
|
'reason_code' => $reasonCode ?? 'connection.diagnostics.unknown',
|
||||||
|
'message' => $message,
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
134
app/Jobs/Onboarding/OnboardingConsentStatusJob.php
Normal file
134
app/Jobs/Onboarding/OnboardingConsentStatusJob.php
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Jobs\Onboarding;
|
||||||
|
|
||||||
|
use App\Jobs\Middleware\TrackOperationRun;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Onboarding\OnboardingEvidenceWriter;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunOutcome;
|
||||||
|
use App\Support\OperationRunStatus;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class OnboardingConsentStatusJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public ?OperationRun $operationRun = null;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public int $tenantId,
|
||||||
|
public int $userId,
|
||||||
|
public int $providerConnectionId,
|
||||||
|
public int $onboardingSessionId,
|
||||||
|
?OperationRun $operationRun = null,
|
||||||
|
) {
|
||||||
|
$this->operationRun = $operationRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, object>
|
||||||
|
*/
|
||||||
|
public function middleware(): array
|
||||||
|
{
|
||||||
|
return [new TrackOperationRun];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(
|
||||||
|
OnboardingEvidenceWriter $evidence,
|
||||||
|
OperationRunService $runs,
|
||||||
|
): void {
|
||||||
|
$tenant = Tenant::query()->find($this->tenantId);
|
||||||
|
if (! $tenant instanceof Tenant) {
|
||||||
|
throw new RuntimeException('Tenant not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = User::query()->find($this->userId);
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
throw new RuntimeException('User not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->onboardingSessionId);
|
||||||
|
|
||||||
|
if (! $session instanceof OnboardingSession) {
|
||||||
|
throw new RuntimeException('OnboardingSession not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->providerConnectionId);
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
throw new RuntimeException('ProviderConnection not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = (string) ($connection->status ?? 'unknown');
|
||||||
|
|
||||||
|
$evidenceStatus = match ($status) {
|
||||||
|
'connected' => 'ok',
|
||||||
|
'needs_consent' => 'blocked',
|
||||||
|
default => 'error',
|
||||||
|
};
|
||||||
|
|
||||||
|
$message = match ($status) {
|
||||||
|
'connected' => 'Consent appears granted (connection is connected).',
|
||||||
|
'needs_consent' => 'Consent is missing or credentials are not authorized yet.',
|
||||||
|
default => 'Unable to determine consent status.',
|
||||||
|
};
|
||||||
|
|
||||||
|
$evidence->record(
|
||||||
|
tenant: $tenant,
|
||||||
|
taskType: OnboardingTaskType::ConsentStatus,
|
||||||
|
status: $evidenceStatus,
|
||||||
|
reasonCode: $status === 'needs_consent' ? 'consent.missing' : null,
|
||||||
|
message: $message,
|
||||||
|
payload: [
|
||||||
|
'provider_connection_status' => $status,
|
||||||
|
'provider_connection_health_status' => $connection->health_status,
|
||||||
|
],
|
||||||
|
session: $session,
|
||||||
|
providerConnection: $connection,
|
||||||
|
operationRun: $this->operationRun,
|
||||||
|
recordedBy: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $this->operationRun instanceof OperationRun) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($evidenceStatus === 'ok') {
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Succeeded->value,
|
||||||
|
);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Failed->value,
|
||||||
|
failures: [[
|
||||||
|
'code' => 'onboarding.consent.status.failed',
|
||||||
|
'reason_code' => $status === 'needs_consent' ? 'consent.missing' : 'consent.status.error',
|
||||||
|
'message' => $message,
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
125
app/Jobs/Onboarding/OnboardingInitialSyncJob.php
Normal file
125
app/Jobs/Onboarding/OnboardingInitialSyncJob.php
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Jobs\Onboarding;
|
||||||
|
|
||||||
|
use App\Jobs\Middleware\TrackOperationRun;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Onboarding\OnboardingEvidenceWriter;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunOutcome;
|
||||||
|
use App\Support\OperationRunStatus;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class OnboardingInitialSyncJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public ?OperationRun $operationRun = null;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public int $tenantId,
|
||||||
|
public int $userId,
|
||||||
|
public int $providerConnectionId,
|
||||||
|
public int $onboardingSessionId,
|
||||||
|
?OperationRun $operationRun = null,
|
||||||
|
) {
|
||||||
|
$this->operationRun = $operationRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, object>
|
||||||
|
*/
|
||||||
|
public function middleware(): array
|
||||||
|
{
|
||||||
|
return [new TrackOperationRun];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(OnboardingEvidenceWriter $evidence, OperationRunService $runs): void
|
||||||
|
{
|
||||||
|
$tenant = Tenant::query()->find($this->tenantId);
|
||||||
|
if (! $tenant instanceof Tenant) {
|
||||||
|
throw new RuntimeException('Tenant not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = User::query()->find($this->userId);
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
throw new RuntimeException('User not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->onboardingSessionId);
|
||||||
|
|
||||||
|
if (! $session instanceof OnboardingSession) {
|
||||||
|
throw new RuntimeException('OnboardingSession not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->providerConnectionId);
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
throw new RuntimeException('ProviderConnection not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connected = (string) ($connection->status ?? 'unknown') === 'connected';
|
||||||
|
|
||||||
|
$evidenceStatus = $connected ? 'ok' : 'blocked';
|
||||||
|
$reasonCode = $connected ? null : 'provider.not_connected';
|
||||||
|
$message = $connected
|
||||||
|
? 'Prerequisites for initial sync look good.'
|
||||||
|
: 'Provider connection is not connected. Resolve consent/credentials first.';
|
||||||
|
|
||||||
|
$evidence->record(
|
||||||
|
tenant: $tenant,
|
||||||
|
taskType: OnboardingTaskType::InitialSync,
|
||||||
|
status: $evidenceStatus,
|
||||||
|
reasonCode: $reasonCode,
|
||||||
|
message: $message,
|
||||||
|
payload: [
|
||||||
|
'provider_connection_status' => $connection->status,
|
||||||
|
],
|
||||||
|
session: $session,
|
||||||
|
providerConnection: $connection,
|
||||||
|
operationRun: $this->operationRun,
|
||||||
|
recordedBy: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $this->operationRun instanceof OperationRun) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($evidenceStatus === 'ok') {
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Succeeded->value,
|
||||||
|
);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Failed->value,
|
||||||
|
failures: [[
|
||||||
|
'code' => 'onboarding.initial_sync.blocked',
|
||||||
|
'reason_code' => $reasonCode ?? 'initial_sync.unknown',
|
||||||
|
'message' => $message,
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
140
app/Jobs/Onboarding/OnboardingVerifyPermissionsJob.php
Normal file
140
app/Jobs/Onboarding/OnboardingVerifyPermissionsJob.php
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Jobs\Onboarding;
|
||||||
|
|
||||||
|
use App\Jobs\Middleware\TrackOperationRun;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Intune\TenantPermissionService;
|
||||||
|
use App\Services\Onboarding\OnboardingEvidenceWriter;
|
||||||
|
use App\Services\OperationRunService;
|
||||||
|
use App\Support\Onboarding\OnboardingTaskType;
|
||||||
|
use App\Support\OperationRunOutcome;
|
||||||
|
use App\Support\OperationRunStatus;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class OnboardingVerifyPermissionsJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public ?OperationRun $operationRun = null;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public int $tenantId,
|
||||||
|
public int $userId,
|
||||||
|
public int $providerConnectionId,
|
||||||
|
public int $onboardingSessionId,
|
||||||
|
?OperationRun $operationRun = null,
|
||||||
|
) {
|
||||||
|
$this->operationRun = $operationRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, object>
|
||||||
|
*/
|
||||||
|
public function middleware(): array
|
||||||
|
{
|
||||||
|
return [new TrackOperationRun];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(
|
||||||
|
TenantPermissionService $permissions,
|
||||||
|
OnboardingEvidenceWriter $evidence,
|
||||||
|
OperationRunService $runs,
|
||||||
|
): void {
|
||||||
|
$tenant = Tenant::query()->find($this->tenantId);
|
||||||
|
if (! $tenant instanceof Tenant) {
|
||||||
|
throw new RuntimeException('Tenant not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = User::query()->find($this->userId);
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
throw new RuntimeException('User not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = OnboardingSession::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->onboardingSessionId);
|
||||||
|
|
||||||
|
if (! $session instanceof OnboardingSession) {
|
||||||
|
throw new RuntimeException('OnboardingSession not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = ProviderConnection::query()
|
||||||
|
->where('tenant_id', $tenant->getKey())
|
||||||
|
->find($this->providerConnectionId);
|
||||||
|
|
||||||
|
if (! $connection instanceof ProviderConnection) {
|
||||||
|
throw new RuntimeException('ProviderConnection not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// For onboarding, we default to a safe, non-live permission comparison.
|
||||||
|
// Live Graph calls can be enabled later as a deliberate UX and contract decision.
|
||||||
|
$result = $permissions->compare($tenant, persist: true, liveCheck: false, useConfiguredStub: true);
|
||||||
|
|
||||||
|
$overall = $result['overall_status'] ?? 'error';
|
||||||
|
|
||||||
|
$evidenceStatus = match ($overall) {
|
||||||
|
'granted' => 'ok',
|
||||||
|
'missing' => 'blocked',
|
||||||
|
default => 'error',
|
||||||
|
};
|
||||||
|
|
||||||
|
$message = match ($overall) {
|
||||||
|
'granted' => 'All required permissions appear granted.',
|
||||||
|
'missing' => 'Some required permissions are missing.',
|
||||||
|
default => 'Unable to verify permissions.',
|
||||||
|
};
|
||||||
|
|
||||||
|
$evidence->record(
|
||||||
|
tenant: $tenant,
|
||||||
|
taskType: OnboardingTaskType::VerifyPermissions,
|
||||||
|
status: $evidenceStatus,
|
||||||
|
reasonCode: $overall === 'missing' ? 'permissions.missing' : null,
|
||||||
|
message: $message,
|
||||||
|
payload: [
|
||||||
|
'overall_status' => $overall,
|
||||||
|
'permissions' => $result['permissions'] ?? [],
|
||||||
|
],
|
||||||
|
session: $session,
|
||||||
|
providerConnection: $connection,
|
||||||
|
operationRun: $this->operationRun,
|
||||||
|
recordedBy: $user,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $this->operationRun instanceof OperationRun) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($evidenceStatus === 'ok') {
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Succeeded->value,
|
||||||
|
);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$runs->updateRun(
|
||||||
|
$this->operationRun,
|
||||||
|
status: OperationRunStatus::Completed->value,
|
||||||
|
outcome: OperationRunOutcome::Failed->value,
|
||||||
|
failures: [[
|
||||||
|
'code' => 'onboarding.permissions.verify.failed',
|
||||||
|
'reason_code' => $overall === 'missing' ? 'permissions.missing' : 'permissions.verify.error',
|
||||||
|
'message' => $message,
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -7,17 +7,11 @@
|
|||||||
use App\Models\ProviderConnection;
|
use App\Models\ProviderConnection;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\Audit\WorkspaceAuditLogger;
|
|
||||||
use App\Services\Intune\TenantPermissionService;
|
|
||||||
use App\Services\OperationRunService;
|
use App\Services\OperationRunService;
|
||||||
use App\Services\Providers\ProviderGateway;
|
|
||||||
use App\Services\Providers\Contracts\HealthResult;
|
use App\Services\Providers\Contracts\HealthResult;
|
||||||
use App\Services\Providers\MicrosoftProviderHealthCheck;
|
use App\Services\Providers\MicrosoftProviderHealthCheck;
|
||||||
use App\Support\Audit\AuditActionId;
|
|
||||||
use App\Support\OperationRunOutcome;
|
use App\Support\OperationRunOutcome;
|
||||||
use App\Support\OperationRunStatus;
|
use App\Support\OperationRunStatus;
|
||||||
use App\Support\Verification\TenantPermissionCheckClusters;
|
|
||||||
use App\Support\Verification\VerificationReportWriter;
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
@ -89,146 +83,17 @@ public function handle(
|
|||||||
|
|
||||||
$this->updateRunTargetScope($this->operationRun, $connection, $entraTenantName);
|
$this->updateRunTargetScope($this->operationRun, $connection, $entraTenantName);
|
||||||
|
|
||||||
$permissionService = app(TenantPermissionService::class);
|
|
||||||
|
|
||||||
$graphOptions = null;
|
|
||||||
|
|
||||||
if ($result->healthy) {
|
|
||||||
try {
|
|
||||||
$graphOptions = app(ProviderGateway::class)->graphOptions($connection);
|
|
||||||
} catch (\Throwable) {
|
|
||||||
$graphOptions = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$permissionComparison = $result->healthy
|
|
||||||
? ($graphOptions === null
|
|
||||||
? $permissionService->compare(
|
|
||||||
$tenant,
|
|
||||||
persist: false,
|
|
||||||
liveCheck: false,
|
|
||||||
useConfiguredStub: false,
|
|
||||||
)
|
|
||||||
: $permissionService->compare(
|
|
||||||
$tenant,
|
|
||||||
persist: true,
|
|
||||||
liveCheck: true,
|
|
||||||
useConfiguredStub: false,
|
|
||||||
graphOptions: $graphOptions,
|
|
||||||
))
|
|
||||||
: $permissionService->compare(
|
|
||||||
$tenant,
|
|
||||||
persist: false,
|
|
||||||
liveCheck: false,
|
|
||||||
useConfiguredStub: false,
|
|
||||||
);
|
|
||||||
|
|
||||||
$permissionRows = $permissionComparison['permissions'] ?? [];
|
|
||||||
$permissionRows = is_array($permissionRows) ? $permissionRows : [];
|
|
||||||
|
|
||||||
$inventory = null;
|
|
||||||
|
|
||||||
if (! $result->healthy) {
|
|
||||||
$inventory = [
|
|
||||||
'fresh' => false,
|
|
||||||
'reason_code' => $result->reasonCode ?? 'dependency_unreachable',
|
|
||||||
'message' => 'Provider connection check failed; permissions were not refreshed during this run.',
|
|
||||||
];
|
|
||||||
} elseif ($graphOptions === null) {
|
|
||||||
$inventory = [
|
|
||||||
'fresh' => false,
|
|
||||||
'reason_code' => 'provider_credential_missing',
|
|
||||||
'message' => 'Provider credentials were unavailable; observed permissions inventory was not refreshed during this run.',
|
|
||||||
];
|
|
||||||
} else {
|
|
||||||
$liveCheck = $permissionComparison['live_check'] ?? null;
|
|
||||||
$liveCheck = is_array($liveCheck) ? $liveCheck : [];
|
|
||||||
|
|
||||||
$reasonCode = is_string($liveCheck['reason_code'] ?? null) ? (string) $liveCheck['reason_code'] : 'dependency_unreachable';
|
|
||||||
$appId = is_string($liveCheck['app_id'] ?? null) && $liveCheck['app_id'] !== '' ? (string) $liveCheck['app_id'] : null;
|
|
||||||
$observedCount = is_numeric($liveCheck['observed_permissions_count'] ?? null)
|
|
||||||
? (int) $liveCheck['observed_permissions_count']
|
|
||||||
: null;
|
|
||||||
|
|
||||||
$message = ($liveCheck['succeeded'] ?? false) === true
|
|
||||||
? 'Observed permissions inventory refreshed successfully.'
|
|
||||||
: match ($reasonCode) {
|
|
||||||
'permissions_inventory_empty' => $appId !== null
|
|
||||||
? sprintf('No application permissions were detected for app id %s. Verify admin consent was granted for this exact app registration, then retry verification.', $appId)
|
|
||||||
: 'No application permissions were detected. Verify admin consent was granted for the configured app registration, then retry verification.',
|
|
||||||
default => 'Unable to refresh observed permissions inventory during this run. Retry verification.',
|
|
||||||
};
|
|
||||||
|
|
||||||
$inventory = [
|
|
||||||
'fresh' => ($liveCheck['succeeded'] ?? false) === true,
|
|
||||||
'reason_code' => $reasonCode,
|
|
||||||
'message' => $message,
|
|
||||||
'app_id' => $appId,
|
|
||||||
'observed_permissions_count' => $observedCount,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$permissionChecks = TenantPermissionCheckClusters::buildChecks($tenant, $permissionRows, $inventory);
|
|
||||||
|
|
||||||
$report = VerificationReportWriter::write(
|
|
||||||
run: $this->operationRun,
|
|
||||||
checks: [
|
|
||||||
[
|
|
||||||
'key' => 'provider.connection.check',
|
|
||||||
'title' => 'Provider connection check',
|
|
||||||
'status' => $result->healthy ? 'pass' : 'fail',
|
|
||||||
'severity' => $result->healthy ? 'info' : 'critical',
|
|
||||||
'blocking' => ! $result->healthy,
|
|
||||||
'reason_code' => $result->healthy ? 'ok' : ($result->reasonCode ?? 'unknown_error'),
|
|
||||||
'message' => $result->healthy ? 'Connection is healthy.' : ($result->message ?? 'Health check failed.'),
|
|
||||||
'evidence' => array_values(array_filter([
|
|
||||||
[
|
|
||||||
'kind' => 'provider_connection_id',
|
|
||||||
'value' => (int) $connection->getKey(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
'kind' => 'entra_tenant_id',
|
|
||||||
'value' => (string) $connection->entra_tenant_id,
|
|
||||||
],
|
|
||||||
is_numeric($result->meta['http_status'] ?? null) ? [
|
|
||||||
'kind' => 'http_status',
|
|
||||||
'value' => (int) $result->meta['http_status'],
|
|
||||||
] : null,
|
|
||||||
is_string($result->meta['organization_id'] ?? null) ? [
|
|
||||||
'kind' => 'organization_id',
|
|
||||||
'value' => (string) $result->meta['organization_id'],
|
|
||||||
] : null,
|
|
||||||
])),
|
|
||||||
'next_steps' => $result->healthy
|
|
||||||
? []
|
|
||||||
: [[
|
|
||||||
'label' => 'Review provider connection',
|
|
||||||
'url' => \App\Filament\Resources\ProviderConnectionResource::getUrl('edit', [
|
|
||||||
'record' => (int) $connection->getKey(),
|
|
||||||
], tenant: $tenant),
|
|
||||||
]],
|
|
||||||
],
|
|
||||||
...$permissionChecks,
|
|
||||||
],
|
|
||||||
identity: [
|
|
||||||
'provider_connection_id' => (int) $connection->getKey(),
|
|
||||||
'entra_tenant_id' => (string) $connection->entra_tenant_id,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($result->healthy) {
|
if ($result->healthy) {
|
||||||
$run = $runs->updateRun(
|
$runs->updateRun(
|
||||||
$this->operationRun,
|
$this->operationRun,
|
||||||
status: OperationRunStatus::Completed->value,
|
status: OperationRunStatus::Completed->value,
|
||||||
outcome: OperationRunOutcome::Succeeded->value,
|
outcome: OperationRunOutcome::Succeeded->value,
|
||||||
);
|
);
|
||||||
|
|
||||||
$this->logVerificationCompletion($tenant, $user, $run, $report);
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$run = $runs->updateRun(
|
$runs->updateRun(
|
||||||
$this->operationRun,
|
$this->operationRun,
|
||||||
status: OperationRunStatus::Completed->value,
|
status: OperationRunStatus::Completed->value,
|
||||||
outcome: OperationRunOutcome::Failed->value,
|
outcome: OperationRunOutcome::Failed->value,
|
||||||
@ -238,8 +103,6 @@ public function handle(
|
|||||||
'message' => $result->message ?? 'Health check failed.',
|
'message' => $result->message ?? 'Health check failed.',
|
||||||
]],
|
]],
|
||||||
);
|
);
|
||||||
|
|
||||||
$this->logVerificationCompletion($tenant, $user, $run, $report);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private function resolveEntraTenantName(ProviderConnection $connection, HealthResult $result): ?string
|
private function resolveEntraTenantName(ProviderConnection $connection, HealthResult $result): ?string
|
||||||
@ -282,34 +145,4 @@ private function applyHealthResult(ProviderConnection $connection, HealthResult
|
|||||||
'last_error_message' => $result->healthy ? null : $result->message,
|
'last_error_message' => $result->healthy ? null : $result->message,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $report
|
|
||||||
*/
|
|
||||||
private function logVerificationCompletion(Tenant $tenant, User $actor, OperationRun $run, array $report): void
|
|
||||||
{
|
|
||||||
$workspace = $tenant->workspace;
|
|
||||||
|
|
||||||
if (! $workspace) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$counts = $report['summary']['counts'] ?? [];
|
|
||||||
$counts = is_array($counts) ? $counts : [];
|
|
||||||
|
|
||||||
app(WorkspaceAuditLogger::class)->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::VerificationCompleted->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'operation_run_id' => (int) $run->getKey(),
|
|
||||||
'counts' => $counts,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: $run->outcome === OperationRunOutcome::Succeeded->value ? 'success' : 'failed',
|
|
||||||
resourceType: 'operation_run',
|
|
||||||
resourceId: (string) $run->getKey(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -61,7 +61,7 @@ public static function externalIdShort(?string $externalId): string
|
|||||||
public function table(Table $table): Table
|
public function table(Table $table): Table
|
||||||
{
|
{
|
||||||
$backupSet = BackupSet::query()->find($this->backupSetId);
|
$backupSet = BackupSet::query()->find($this->backupSetId);
|
||||||
$tenantId = $backupSet?->tenant_id ?? Tenant::currentOrFail()->getKey();
|
$tenantId = $backupSet?->tenant_id ?? Tenant::current()->getKey();
|
||||||
$existingPolicyIds = $backupSet
|
$existingPolicyIds = $backupSet
|
||||||
? $backupSet->items()->pluck('policy_id')->filter()->all()
|
? $backupSet->items()->pluck('policy_id')->filter()->all()
|
||||||
: [];
|
: [];
|
||||||
|
|||||||
46
app/Models/OnboardingEvidence.php
Normal file
46
app/Models/OnboardingEvidence.php
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class OnboardingEvidence extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $table = 'onboarding_evidence';
|
||||||
|
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'payload' => 'array',
|
||||||
|
'recorded_at' => 'datetime',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function tenant(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tenant::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function onboardingSession(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(OnboardingSession::class, 'onboarding_session_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function providerConnection(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ProviderConnection::class, 'provider_connection_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function operationRun(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(OperationRun::class, 'operation_run_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function recordedBy(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'recorded_by_user_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
47
app/Models/OnboardingSession.php
Normal file
47
app/Models/OnboardingSession.php
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
class OnboardingSession extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'current_step' => 'integer',
|
||||||
|
'locked_until' => 'datetime',
|
||||||
|
'completed_at' => 'datetime',
|
||||||
|
'metadata' => 'array',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function tenant(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tenant::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function providerConnection(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ProviderConnection::class, 'provider_connection_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assignedTo(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'assigned_to_user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function lockedBy(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'locked_by_user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function evidence(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(OnboardingEvidence::class, 'onboarding_session_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -21,41 +21,11 @@ class OperationRun extends Model
|
|||||||
'completed_at' => 'datetime',
|
'completed_at' => 'datetime',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected static function booted(): void
|
|
||||||
{
|
|
||||||
static::creating(function (self $operationRun): void {
|
|
||||||
if ($operationRun->workspace_id !== null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($operationRun->tenant_id === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::query()->whereKey((int) $operationRun->tenant_id)->first();
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenant->workspace_id === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$operationRun->workspace_id = (int) $tenant->workspace_id;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function tenant(): BelongsTo
|
public function tenant(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Tenant::class);
|
return $this->belongsTo(Tenant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function user(): BelongsTo
|
public function user(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class);
|
return $this->belongsTo(User::class);
|
||||||
|
|||||||
@ -26,11 +26,6 @@ public function tenant(): BelongsTo
|
|||||||
return $this->belongsTo(Tenant::class);
|
return $this->belongsTo(Tenant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function credential(): HasOne
|
public function credential(): HasOne
|
||||||
{
|
{
|
||||||
return $this->hasOne(ProviderCredential::class, 'provider_connection_id');
|
return $this->hasOne(ProviderCredential::class, 'provider_connection_id');
|
||||||
|
|||||||
@ -7,7 +7,6 @@
|
|||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
|
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
|
||||||
@ -21,14 +20,6 @@ class Tenant extends Model implements HasName
|
|||||||
use HasFactory;
|
use HasFactory;
|
||||||
use SoftDeletes;
|
use SoftDeletes;
|
||||||
|
|
||||||
public const STATUS_DRAFT = 'draft';
|
|
||||||
|
|
||||||
public const STATUS_ONBOARDING = 'onboarding';
|
|
||||||
|
|
||||||
public const STATUS_ACTIVE = 'active';
|
|
||||||
|
|
||||||
public const STATUS_ARCHIVED = 'archived';
|
|
||||||
|
|
||||||
protected $guarded = [];
|
protected $guarded = [];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
@ -77,16 +68,7 @@ protected static function booted(): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (empty($tenant->status)) {
|
if (empty($tenant->status)) {
|
||||||
$tenant->status = self::STATUS_ACTIVE;
|
$tenant->status = 'active';
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenant->workspace_id === null && app()->runningUnitTests()) {
|
|
||||||
$workspace = Workspace::query()->create([
|
|
||||||
'name' => 'Test Workspace',
|
|
||||||
'slug' => 'test-'.Str::lower(Str::random(10)),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant->workspace_id = (int) $workspace->getKey();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -101,12 +83,12 @@ protected static function booted(): void
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$tenant->status = self::STATUS_ARCHIVED;
|
$tenant->status = 'archived';
|
||||||
$tenant->saveQuietly();
|
$tenant->saveQuietly();
|
||||||
});
|
});
|
||||||
|
|
||||||
static::restored(function (Tenant $tenant) {
|
static::restored(function (Tenant $tenant) {
|
||||||
$tenant->forceFill(['status' => self::STATUS_ACTIVE])->saveQuietly();
|
$tenant->forceFill(['status' => 'active'])->saveQuietly();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,12 +96,12 @@ public static function activeQuery(): Builder
|
|||||||
{
|
{
|
||||||
return static::query()
|
return static::query()
|
||||||
->whereNull('deleted_at')
|
->whereNull('deleted_at')
|
||||||
->where('status', self::STATUS_ACTIVE);
|
->where('status', 'active');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function makeCurrent(): void
|
public function makeCurrent(): void
|
||||||
{
|
{
|
||||||
if ($this->trashed() || $this->status !== self::STATUS_ACTIVE) {
|
if ($this->trashed() || $this->status !== 'active') {
|
||||||
throw new RuntimeException('Only active tenants can be made current.');
|
throw new RuntimeException('Only active tenants can be made current.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -134,7 +116,7 @@ public function makeCurrent(): void
|
|||||||
$this->forceFill(['is_current' => true]);
|
$this->forceFill(['is_current' => true]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function current(): ?self
|
public static function current(): self
|
||||||
{
|
{
|
||||||
$filamentTenant = Filament::getTenant();
|
$filamentTenant = Filament::getTenant();
|
||||||
|
|
||||||
@ -163,13 +145,6 @@ public static function current(): ?self
|
|||||||
->where('is_current', true)
|
->where('is_current', true)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
return $tenant;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function currentOrFail(): self
|
|
||||||
{
|
|
||||||
$tenant = static::current();
|
|
||||||
|
|
||||||
if (! $tenant) {
|
if (! $tenant) {
|
||||||
throw new RuntimeException('No current tenant selected.');
|
throw new RuntimeException('No current tenant selected.');
|
||||||
}
|
}
|
||||||
@ -195,11 +170,6 @@ public function memberships(): HasMany
|
|||||||
return $this->hasMany(TenantMembership::class);
|
return $this->hasMany(TenantMembership::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function roleMappings(): HasMany
|
public function roleMappings(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(TenantRoleMapping::class);
|
return $this->hasMany(TenantRoleMapping::class);
|
||||||
|
|||||||
@ -1,92 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
class TenantOnboardingSession extends Model
|
|
||||||
{
|
|
||||||
/** @use HasFactory<\Database\Factories\TenantOnboardingSessionFactory> */
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $table = 'managed_tenant_onboarding_sessions';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
public const STATE_ALLOWED_KEYS = [
|
|
||||||
'entra_tenant_id',
|
|
||||||
'tenant_id',
|
|
||||||
'tenant_name',
|
|
||||||
'environment',
|
|
||||||
'primary_domain',
|
|
||||||
'notes',
|
|
||||||
'provider_connection_id',
|
|
||||||
'selected_provider_connection_id',
|
|
||||||
'verification_operation_run_id',
|
|
||||||
'verification_run_id',
|
|
||||||
'bootstrap_operation_types',
|
|
||||||
'bootstrap_operation_runs',
|
|
||||||
'bootstrap_run_ids',
|
|
||||||
'connection_recently_updated',
|
|
||||||
];
|
|
||||||
|
|
||||||
protected $guarded = [];
|
|
||||||
|
|
||||||
protected $casts = [
|
|
||||||
'state' => 'array',
|
|
||||||
'completed_at' => 'datetime',
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed>|null $value
|
|
||||||
*/
|
|
||||||
public function setStateAttribute(?array $value): void
|
|
||||||
{
|
|
||||||
if ($value === null) {
|
|
||||||
$this->attributes['state'] = null;
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$allowed = array_intersect_key($value, array_flip(self::STATE_ALLOWED_KEYS));
|
|
||||||
|
|
||||||
$encoded = json_encode($allowed, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
||||||
|
|
||||||
$this->attributes['state'] = $encoded !== false ? $encoded : json_encode([], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<Workspace, $this>
|
|
||||||
*/
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<Tenant, $this>
|
|
||||||
*/
|
|
||||||
public function tenant(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Tenant::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<User, $this>
|
|
||||||
*/
|
|
||||||
public function startedByUser(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(User::class, 'started_by_user_id');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<User, $this>
|
|
||||||
*/
|
|
||||||
public function updatedByUser(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(User::class, 'updated_by_user_id');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -3,7 +3,6 @@
|
|||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
use App\Support\Auth\Capabilities;
|
use App\Support\Auth\Capabilities;
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Filament\Models\Contracts\FilamentUser;
|
use Filament\Models\Contracts\FilamentUser;
|
||||||
use Filament\Models\Contracts\HasDefaultTenant;
|
use Filament\Models\Contracts\HasDefaultTenant;
|
||||||
use Filament\Models\Contracts\HasTenants;
|
use Filament\Models\Contracts\HasTenants;
|
||||||
@ -142,10 +141,7 @@ public function getTenants(Panel $panel): array|Collection
|
|||||||
return collect();
|
return collect();
|
||||||
}
|
}
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
return $this->tenants()
|
return $this->tenants()
|
||||||
->when($workspaceId !== null, fn ($query) => $query->where('tenants.workspace_id', $workspaceId))
|
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->orderBy('name')
|
->orderBy('name')
|
||||||
->get();
|
->get();
|
||||||
@ -157,8 +153,6 @@ public function getDefaultTenant(Panel $panel): ?Model
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
|
||||||
|
|
||||||
$tenantId = null;
|
$tenantId = null;
|
||||||
|
|
||||||
if ($this->tenantPreferencesTableExists()) {
|
if ($this->tenantPreferencesTableExists()) {
|
||||||
@ -170,7 +164,6 @@ public function getDefaultTenant(Panel $panel): ?Model
|
|||||||
|
|
||||||
if ($tenantId !== null) {
|
if ($tenantId !== null) {
|
||||||
$tenant = $this->tenants()
|
$tenant = $this->tenants()
|
||||||
->when($workspaceId !== null, fn ($query) => $query->where('tenants.workspace_id', $workspaceId))
|
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->whereKey($tenantId)
|
->whereKey($tenantId)
|
||||||
->first();
|
->first();
|
||||||
@ -181,7 +174,6 @@ public function getDefaultTenant(Panel $panel): ?Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
return $this->tenants()
|
return $this->tenants()
|
||||||
->when($workspaceId !== null, fn ($query) => $query->where('tenants.workspace_id', $workspaceId))
|
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->orderBy('name')
|
->orderBy('name')
|
||||||
->first();
|
->first();
|
||||||
|
|||||||
@ -1,41 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
class VerificationCheckAcknowledgement extends Model
|
|
||||||
{
|
|
||||||
/** @use HasFactory<\Database\Factories\VerificationCheckAcknowledgementFactory> */
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $guarded = [];
|
|
||||||
|
|
||||||
protected $casts = [
|
|
||||||
'expires_at' => 'datetime',
|
|
||||||
'acknowledged_at' => 'datetime',
|
|
||||||
];
|
|
||||||
|
|
||||||
public function tenant(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Tenant::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function operationRun(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(OperationRun::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function acknowledgedByUser(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(User::class, 'acknowledged_by_user_id');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ -1,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
||||||
|
|
||||||
class Workspace extends Model
|
|
||||||
{
|
|
||||||
/** @use HasFactory<\Database\Factories\WorkspaceFactory> */
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $guarded = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return HasMany<WorkspaceMembership, $this>
|
|
||||||
*/
|
|
||||||
public function memberships(): HasMany
|
|
||||||
{
|
|
||||||
return $this->hasMany(WorkspaceMembership::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsToMany<User, $this>
|
|
||||||
*/
|
|
||||||
public function users(): BelongsToMany
|
|
||||||
{
|
|
||||||
return $this->belongsToMany(User::class, 'workspace_memberships')
|
|
||||||
->using(WorkspaceMembership::class)
|
|
||||||
->withPivot(['id', 'role'])
|
|
||||||
->withTimestamps();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return HasMany<Tenant, $this>
|
|
||||||
*/
|
|
||||||
public function tenants(): HasMany
|
|
||||||
{
|
|
||||||
return $this->hasMany(Tenant::class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
class WorkspaceMembership extends Model
|
|
||||||
{
|
|
||||||
/** @use HasFactory<\Database\Factories\WorkspaceMembershipFactory> */
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $guarded = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<Workspace, $this>
|
|
||||||
*/
|
|
||||||
public function workspace(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Workspace::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return BelongsTo<User, $this>
|
|
||||||
*/
|
|
||||||
public function user(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(User::class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -33,20 +33,8 @@ public function toDatabase(object $notifiable): array
|
|||||||
{
|
{
|
||||||
$tenant = $this->run->tenant;
|
$tenant = $this->run->tenant;
|
||||||
|
|
||||||
$context = is_array($this->run->context) ? $this->run->context : [];
|
|
||||||
$wizard = $context['wizard'] ?? null;
|
|
||||||
|
|
||||||
$isManagedTenantOnboardingWizardRun = is_array($wizard)
|
|
||||||
&& ($wizard['flow'] ?? null) === 'managed_tenant_onboarding';
|
|
||||||
|
|
||||||
$operationLabel = OperationCatalog::label((string) $this->run->type);
|
$operationLabel = OperationCatalog::label((string) $this->run->type);
|
||||||
|
|
||||||
$runUrl = match (true) {
|
|
||||||
$isManagedTenantOnboardingWizardRun => OperationRunLinks::tenantlessView($this->run),
|
|
||||||
$tenant instanceof Tenant => OperationRunLinks::view($this->run, $tenant),
|
|
||||||
default => null,
|
|
||||||
};
|
|
||||||
|
|
||||||
return FilamentNotification::make()
|
return FilamentNotification::make()
|
||||||
->title("{$operationLabel} queued")
|
->title("{$operationLabel} queued")
|
||||||
->body('Queued. Monitor progress in Monitoring → Operations.')
|
->body('Queued. Monitor progress in Monitoring → Operations.')
|
||||||
@ -54,7 +42,7 @@ public function toDatabase(object $notifiable): array
|
|||||||
->actions([
|
->actions([
|
||||||
\Filament\Actions\Action::make('view_run')
|
\Filament\Actions\Action::make('view_run')
|
||||||
->label('View run')
|
->label('View run')
|
||||||
->url($runUrl),
|
->url($tenant instanceof Tenant ? OperationRunLinks::view($this->run, $tenant) : null),
|
||||||
])
|
])
|
||||||
->getDatabaseMessage();
|
->getDatabaseMessage();
|
||||||
}
|
}
|
||||||
|
|||||||
58
app/Policies/OnboardingEvidencePolicy.php
Normal file
58
app/Policies/OnboardingEvidencePolicy.php
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Policies;
|
||||||
|
|
||||||
|
use App\Models\OnboardingEvidence;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\CapabilityResolver;
|
||||||
|
use App\Support\Auth\Capabilities;
|
||||||
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||||
|
use Illuminate\Auth\Access\Response;
|
||||||
|
|
||||||
|
class OnboardingEvidencePolicy
|
||||||
|
{
|
||||||
|
use HandlesAuthorization;
|
||||||
|
|
||||||
|
public function viewAny(User $user): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function view(User $user, OnboardingEvidence $evidence): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((int) $evidence->tenant_id !== (int) $tenant->getKey()) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
}
|
||||||
100
app/Policies/OnboardingSessionPolicy.php
Normal file
100
app/Policies/OnboardingSessionPolicy.php
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Policies;
|
||||||
|
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Auth\CapabilityResolver;
|
||||||
|
use App\Support\Auth\Capabilities;
|
||||||
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||||
|
use Illuminate\Auth\Access\Response;
|
||||||
|
|
||||||
|
class OnboardingSessionPolicy
|
||||||
|
{
|
||||||
|
use HandlesAuthorization;
|
||||||
|
|
||||||
|
public function viewAny(User $user): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function view(User $user, OnboardingSession $session): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((int) $session->tenant_id !== (int) $tenant->getKey()) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(User $user): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(User $user, OnboardingSession $session): Response|bool
|
||||||
|
{
|
||||||
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((int) $session->tenant_id !== (int) $tenant->getKey()) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolver = app(CapabilityResolver::class);
|
||||||
|
|
||||||
|
if (! $resolver->isMember($user, $tenant)) {
|
||||||
|
return Response::denyAsNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)
|
||||||
|
? true
|
||||||
|
: Response::deny();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,9 +3,8 @@
|
|||||||
namespace App\Policies;
|
namespace App\Policies;
|
||||||
|
|
||||||
use App\Models\OperationRun;
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||||
use Illuminate\Auth\Access\Response;
|
use Illuminate\Auth\Access\Response;
|
||||||
|
|
||||||
@ -15,31 +14,31 @@ class OperationRunPolicy
|
|||||||
|
|
||||||
public function viewAny(User $user): bool
|
public function viewAny(User $user): bool
|
||||||
{
|
{
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
if (! $tenant) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return WorkspaceMembership::query()
|
return $user->canAccessTenant($tenant);
|
||||||
->where('workspace_id', (int) $workspaceId)
|
|
||||||
->where('user_id', (int) $user->getKey())
|
|
||||||
->exists();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function view(User $user, OperationRun $run): Response|bool
|
public function view(User $user, OperationRun $run): Response|bool
|
||||||
{
|
{
|
||||||
$workspaceId = (int) ($run->workspace_id ?? 0);
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
if ($workspaceId <= 0) {
|
if (! $tenant) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $user->canAccessTenant($tenant)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((int) $run->tenant_id !== (int) $tenant->getKey()) {
|
||||||
return Response::denyAsNotFound();
|
return Response::denyAsNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
$isMember = WorkspaceMembership::query()
|
return true;
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('user_id', (int) $user->getKey())
|
|
||||||
->exists();
|
|
||||||
|
|
||||||
return $isMember ? true : Response::denyAsNotFound();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,8 +5,6 @@
|
|||||||
use App\Models\ProviderConnection;
|
use App\Models\ProviderConnection;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||||
use Illuminate\Auth\Access\Response;
|
use Illuminate\Auth\Access\Response;
|
||||||
use Illuminate\Support\Facades\Gate;
|
use Illuminate\Support\Facades\Gate;
|
||||||
@ -17,31 +15,15 @@ class ProviderConnectionPolicy
|
|||||||
|
|
||||||
public function viewAny(User $user): bool
|
public function viewAny(User $user): bool
|
||||||
{
|
{
|
||||||
$workspace = $this->currentWorkspace();
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
return $tenant instanceof Tenant
|
return Gate::forUser($user)->allows('provider.view', $tenant);
|
||||||
&& (int) $tenant->workspace_id === (int) $workspace->getKey()
|
|
||||||
&& Gate::forUser($user)->allows('provider.view', $tenant);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function view(User $user, ProviderConnection $connection): Response|bool
|
public function view(User $user, ProviderConnection $connection): Response|bool
|
||||||
{
|
{
|
||||||
$workspace = $this->currentWorkspace();
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -50,40 +32,20 @@ public function view(User $user, ProviderConnection $connection): Response|bool
|
|||||||
return Response::denyAsNotFound();
|
return Response::denyAsNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function create(User $user): bool
|
public function create(User $user): bool
|
||||||
{
|
{
|
||||||
$workspace = $this->currentWorkspace();
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
return $tenant instanceof Tenant
|
return Gate::forUser($user)->allows('provider.manage', $tenant);
|
||||||
&& (int) $tenant->workspace_id === (int) $workspace->getKey()
|
|
||||||
&& Gate::forUser($user)->allows('provider.manage', $tenant);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function update(User $user, ProviderConnection $connection): Response|bool
|
public function update(User $user, ProviderConnection $connection): Response|bool
|
||||||
{
|
{
|
||||||
$workspace = $this->currentWorkspace();
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -92,26 +54,13 @@ public function update(User $user, ProviderConnection $connection): Response|boo
|
|||||||
return Response::denyAsNotFound();
|
return Response::denyAsNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function delete(User $user, ProviderConnection $connection): Response|bool
|
public function delete(User $user, ProviderConnection $connection): Response|bool
|
||||||
{
|
{
|
||||||
$workspace = $this->currentWorkspace();
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = Tenant::current();
|
$tenant = Tenant::current();
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! Gate::forUser($user)->allows('provider.manage', $tenant)) {
|
if (! Gate::forUser($user)->allows('provider.manage', $tenant)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -120,19 +69,6 @@ public function delete(User $user, ProviderConnection $connection): Response|boo
|
|||||||
return Response::denyAsNotFound();
|
return Response::denyAsNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
return Response::denyAsNotFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function currentWorkspace(): ?Workspace
|
|
||||||
{
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
|
||||||
|
|
||||||
return is_int($workspaceId)
|
|
||||||
? Workspace::query()->whereKey($workspaceId)->first()
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,108 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Policies;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
|
|
||||||
class WorkspaceMembershipPolicy
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Determine whether the user can view any models.
|
|
||||||
*/
|
|
||||||
public function viewAny(User $user): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can view the model.
|
|
||||||
*/
|
|
||||||
public function view(User $user, WorkspaceMembership $workspaceMembership): bool
|
|
||||||
{
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $workspaceMembership->workspace, Capabilities::WORKSPACE_MEMBERSHIP_VIEW);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can create models.
|
|
||||||
*/
|
|
||||||
public function create(User $user): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can update the model.
|
|
||||||
*/
|
|
||||||
public function update(User $user, WorkspaceMembership $workspaceMembership): bool
|
|
||||||
{
|
|
||||||
if ($this->isLastOwner($workspaceMembership)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $workspaceMembership->workspace, Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can delete the model.
|
|
||||||
*/
|
|
||||||
public function delete(User $user, WorkspaceMembership $workspaceMembership): bool
|
|
||||||
{
|
|
||||||
if ($this->isLastOwner($workspaceMembership)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $workspaceMembership->workspace, Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can restore the model.
|
|
||||||
*/
|
|
||||||
public function restore(User $user, WorkspaceMembership $workspaceMembership): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can permanently delete the model.
|
|
||||||
*/
|
|
||||||
public function forceDelete(User $user, WorkspaceMembership $workspaceMembership): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function manageForWorkspace(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $workspace, Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function isLastOwner(WorkspaceMembership $membership): bool
|
|
||||||
{
|
|
||||||
if ($membership->role !== WorkspaceRole::Owner->value) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ownerCount = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', $membership->workspace_id)
|
|
||||||
->where('role', WorkspaceRole::Owner->value)
|
|
||||||
->count();
|
|
||||||
|
|
||||||
return $ownerCount <= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,74 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Policies;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
|
|
||||||
class WorkspacePolicy
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Determine whether the user can view any models.
|
|
||||||
*/
|
|
||||||
public function viewAny(User $user): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can view the model.
|
|
||||||
*/
|
|
||||||
public function view(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
return WorkspaceMembership::query()
|
|
||||||
->where('user_id', $user->getKey())
|
|
||||||
->where('workspace_id', $workspace->getKey())
|
|
||||||
->exists();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can create models.
|
|
||||||
*/
|
|
||||||
public function create(User $user): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can update the model.
|
|
||||||
*/
|
|
||||||
public function update(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
return $resolver->can($user, $workspace, Capabilities::WORKSPACE_MANAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can delete the model.
|
|
||||||
*/
|
|
||||||
public function delete(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can restore the model.
|
|
||||||
*/
|
|
||||||
public function restore(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether the user can permanently delete the model.
|
|
||||||
*/
|
|
||||||
public function forceDelete(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -2,14 +2,16 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Models\OnboardingEvidence;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
use App\Models\PlatformUser;
|
use App\Models\PlatformUser;
|
||||||
use App\Models\ProviderConnection;
|
use App\Models\ProviderConnection;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Workspace;
|
use App\Policies\OnboardingEvidencePolicy;
|
||||||
|
use App\Policies\OnboardingSessionPolicy;
|
||||||
use App\Policies\ProviderConnectionPolicy;
|
use App\Policies\ProviderConnectionPolicy;
|
||||||
use App\Services\Auth\CapabilityResolver;
|
use App\Services\Auth\CapabilityResolver;
|
||||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
|
||||||
use App\Support\Auth\Capabilities;
|
use App\Support\Auth\Capabilities;
|
||||||
use App\Support\Auth\PlatformCapabilities;
|
use App\Support\Auth\PlatformCapabilities;
|
||||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||||
@ -19,42 +21,23 @@ class AuthServiceProvider extends ServiceProvider
|
|||||||
{
|
{
|
||||||
protected $policies = [
|
protected $policies = [
|
||||||
ProviderConnection::class => ProviderConnectionPolicy::class,
|
ProviderConnection::class => ProviderConnectionPolicy::class,
|
||||||
|
OnboardingSession::class => OnboardingSessionPolicy::class,
|
||||||
|
OnboardingEvidence::class => OnboardingEvidencePolicy::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public function boot(): void
|
public function boot(): void
|
||||||
{
|
{
|
||||||
$this->registerPolicies();
|
$this->registerPolicies();
|
||||||
|
|
||||||
$tenantResolver = app(CapabilityResolver::class);
|
$resolver = app(CapabilityResolver::class);
|
||||||
$workspaceResolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
$defineTenantCapability = function (string $capability) use ($tenantResolver): void {
|
$defineTenantCapability = function (string $capability) use ($resolver): void {
|
||||||
Gate::define($capability, function (User $user, ?Tenant $tenant = null) use ($tenantResolver, $capability): bool {
|
Gate::define($capability, function (User $user, Tenant $tenant) use ($resolver, $capability): bool {
|
||||||
if (! $tenant instanceof Tenant) {
|
return $resolver->can($user, $tenant, $capability);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $tenantResolver->can($user, $tenant, $capability);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
$defineWorkspaceCapability = function (string $capability) use ($workspaceResolver): void {
|
|
||||||
Gate::define($capability, function (User $user, ?Workspace $workspace = null) use ($workspaceResolver, $capability): bool {
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $workspaceResolver->can($user, $workspace, $capability);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
foreach (Capabilities::all() as $capability) {
|
foreach (Capabilities::all() as $capability) {
|
||||||
if (str_starts_with($capability, 'workspace')) {
|
|
||||||
$defineWorkspaceCapability($capability);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$defineTenantCapability($capability);
|
$defineTenantCapability($capability);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -4,10 +4,9 @@
|
|||||||
|
|
||||||
use App\Filament\Pages\Auth\Login;
|
use App\Filament\Pages\Auth\Login;
|
||||||
use App\Filament\Pages\ChooseTenant;
|
use App\Filament\Pages\ChooseTenant;
|
||||||
use App\Filament\Pages\ChooseWorkspace;
|
|
||||||
use App\Filament\Pages\NoAccess;
|
use App\Filament\Pages\NoAccess;
|
||||||
|
use App\Filament\Pages\Tenancy\RegisterTenant;
|
||||||
use App\Filament\Pages\TenantDashboard;
|
use App\Filament\Pages\TenantDashboard;
|
||||||
use App\Filament\Resources\Workspaces\WorkspaceResource;
|
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Support\Middleware\DenyNonMemberTenantAccess;
|
use App\Support\Middleware\DenyNonMemberTenantAccess;
|
||||||
use Filament\Facades\Filament;
|
use Filament\Facades\Filament;
|
||||||
@ -15,7 +14,6 @@
|
|||||||
use Filament\Http\Middleware\AuthenticateSession;
|
use Filament\Http\Middleware\AuthenticateSession;
|
||||||
use Filament\Http\Middleware\DisableBladeIconComponents;
|
use Filament\Http\Middleware\DisableBladeIconComponents;
|
||||||
use Filament\Http\Middleware\DispatchServingFilamentEvent;
|
use Filament\Http\Middleware\DispatchServingFilamentEvent;
|
||||||
use Filament\Navigation\NavigationItem;
|
|
||||||
use Filament\Panel;
|
use Filament\Panel;
|
||||||
use Filament\PanelProvider;
|
use Filament\PanelProvider;
|
||||||
use Filament\Support\Colors\Color;
|
use Filament\Support\Colors\Color;
|
||||||
@ -39,36 +37,21 @@ public function panel(Panel $panel): Panel
|
|||||||
->path('admin')
|
->path('admin')
|
||||||
->login(Login::class)
|
->login(Login::class)
|
||||||
->authenticatedRoutes(function (Panel $panel): void {
|
->authenticatedRoutes(function (Panel $panel): void {
|
||||||
ChooseWorkspace::registerRoutes($panel);
|
|
||||||
ChooseTenant::registerRoutes($panel);
|
ChooseTenant::registerRoutes($panel);
|
||||||
NoAccess::registerRoutes($panel);
|
NoAccess::registerRoutes($panel);
|
||||||
|
|
||||||
WorkspaceResource::registerRoutes($panel);
|
|
||||||
})
|
})
|
||||||
->tenant(Tenant::class, slugAttribute: 'external_id')
|
->tenant(Tenant::class, slugAttribute: 'external_id')
|
||||||
->tenantRoutePrefix('t')
|
->tenantRoutePrefix('t')
|
||||||
->tenantMenu(fn (): bool => filled(Filament::getTenant()))
|
->tenantMenu(fn (): bool => filled(Filament::getTenant()))
|
||||||
->searchableTenantMenu()
|
->searchableTenantMenu()
|
||||||
|
->tenantRegistration(RegisterTenant::class)
|
||||||
->colors([
|
->colors([
|
||||||
'primary' => Color::Amber,
|
'primary' => Color::Amber,
|
||||||
])
|
])
|
||||||
->navigationItems([
|
|
||||||
NavigationItem::make('Workspaces')
|
|
||||||
->url(function (): string {
|
|
||||||
return route('filament.admin.resources.workspaces.index');
|
|
||||||
})
|
|
||||||
->icon('heroicon-o-squares-2x2')
|
|
||||||
->group('Settings')
|
|
||||||
->sort(10),
|
|
||||||
])
|
|
||||||
->renderHook(
|
->renderHook(
|
||||||
PanelsRenderHook::HEAD_END,
|
PanelsRenderHook::HEAD_END,
|
||||||
fn () => view('filament.partials.livewire-intercept-shim')->render()
|
fn () => view('filament.partials.livewire-intercept-shim')->render()
|
||||||
)
|
)
|
||||||
->renderHook(
|
|
||||||
PanelsRenderHook::USER_MENU_PROFILE_AFTER,
|
|
||||||
fn () => view('filament.partials.workspace-switcher')->render()
|
|
||||||
)
|
|
||||||
->renderHook(
|
->renderHook(
|
||||||
PanelsRenderHook::BODY_END,
|
PanelsRenderHook::BODY_END,
|
||||||
fn () => (bool) config('tenantpilot.bulk_operations.progress_widget_enabled', true)
|
fn () => (bool) config('tenantpilot.bulk_operations.progress_widget_enabled', true)
|
||||||
@ -96,8 +79,6 @@ public function panel(Panel $panel): Panel
|
|||||||
VerifyCsrfToken::class,
|
VerifyCsrfToken::class,
|
||||||
SubstituteBindings::class,
|
SubstituteBindings::class,
|
||||||
'ensure-correct-guard:web',
|
'ensure-correct-guard:web',
|
||||||
'ensure-workspace-selected',
|
|
||||||
'ensure-filament-tenant-selected',
|
|
||||||
DenyNonMemberTenantAccess::class,
|
DenyNonMemberTenantAccess::class,
|
||||||
DisableBladeIconComponents::class,
|
DisableBladeIconComponents::class,
|
||||||
DispatchServingFilamentEvent::class,
|
DispatchServingFilamentEvent::class,
|
||||||
|
|||||||
@ -1,48 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Services\Audit;
|
|
||||||
|
|
||||||
use App\Models\AuditLog;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Support\Audit\AuditContextSanitizer;
|
|
||||||
use Carbon\CarbonImmutable;
|
|
||||||
|
|
||||||
class WorkspaceAuditLogger
|
|
||||||
{
|
|
||||||
public function log(
|
|
||||||
Workspace $workspace,
|
|
||||||
string $action,
|
|
||||||
array $context = [],
|
|
||||||
?User $actor = null,
|
|
||||||
string $status = 'success',
|
|
||||||
?string $resourceType = null,
|
|
||||||
?string $resourceId = null,
|
|
||||||
?int $actorId = null,
|
|
||||||
?string $actorEmail = null,
|
|
||||||
?string $actorName = null,
|
|
||||||
): AuditLog {
|
|
||||||
$metadata = $context['metadata'] ?? [];
|
|
||||||
unset($context['metadata']);
|
|
||||||
|
|
||||||
$metadata = is_array($metadata) ? $metadata : [];
|
|
||||||
|
|
||||||
$sanitizedMetadata = AuditContextSanitizer::sanitize($metadata + $context);
|
|
||||||
|
|
||||||
return AuditLog::create([
|
|
||||||
'tenant_id' => null,
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'actor_id' => $actor?->getKey() ?? $actorId,
|
|
||||||
'actor_email' => $actor?->email ?? $actorEmail,
|
|
||||||
'actor_name' => $actor?->name ?? $actorName,
|
|
||||||
'action' => $action,
|
|
||||||
'resource_type' => $resourceType,
|
|
||||||
'resource_id' => $resourceId,
|
|
||||||
'status' => $status,
|
|
||||||
'metadata' => $sanitizedMetadata,
|
|
||||||
'recorded_at' => CarbonImmutable::now(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -4,27 +4,39 @@
|
|||||||
|
|
||||||
namespace App\Services\Auth;
|
namespace App\Services\Auth;
|
||||||
|
|
||||||
|
use App\Filament\Pages\TenantDashboard;
|
||||||
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\WorkspaceMembership;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
class PostLoginRedirectResolver
|
class PostLoginRedirectResolver
|
||||||
{
|
{
|
||||||
public function resolve(User $user): string
|
public function resolve(User $user): string
|
||||||
{
|
{
|
||||||
$membershipQuery = WorkspaceMembership::query()->where('user_id', $user->getKey());
|
$tenants = $this->getActiveTenants($user);
|
||||||
|
|
||||||
$hasAnyActiveMembership = Schema::hasColumn('workspaces', 'archived_at')
|
if ($tenants->isEmpty()) {
|
||||||
? $membershipQuery
|
|
||||||
->join('workspaces', 'workspace_memberships.workspace_id', '=', 'workspaces.id')
|
|
||||||
->whereNull('workspaces.archived_at')
|
|
||||||
->exists()
|
|
||||||
: $membershipQuery->exists();
|
|
||||||
|
|
||||||
if (! $hasAnyActiveMembership) {
|
|
||||||
return '/admin/no-access';
|
return '/admin/no-access';
|
||||||
}
|
}
|
||||||
|
|
||||||
return '/admin';
|
if ($tenants->count() === 1) {
|
||||||
|
/** @var Tenant $tenant */
|
||||||
|
$tenant = $tenants->first();
|
||||||
|
|
||||||
|
return TenantDashboard::getUrl(tenant: $tenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/admin/choose-tenant';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Collection<int, Tenant>
|
||||||
|
*/
|
||||||
|
private function getActiveTenants(User $user): Collection
|
||||||
|
{
|
||||||
|
return $user->tenants()
|
||||||
|
->where('status', 'active')
|
||||||
|
->orderBy('name')
|
||||||
|
->get();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -21,7 +21,6 @@ class RoleCapabilityMap
|
|||||||
Capabilities::TENANT_SYNC,
|
Capabilities::TENANT_SYNC,
|
||||||
Capabilities::TENANT_INVENTORY_SYNC_RUN,
|
Capabilities::TENANT_INVENTORY_SYNC_RUN,
|
||||||
Capabilities::TENANT_FINDINGS_ACKNOWLEDGE,
|
Capabilities::TENANT_FINDINGS_ACKNOWLEDGE,
|
||||||
Capabilities::TENANT_VERIFICATION_ACKNOWLEDGE,
|
|
||||||
|
|
||||||
Capabilities::TENANT_MEMBERSHIP_VIEW,
|
Capabilities::TENANT_MEMBERSHIP_VIEW,
|
||||||
Capabilities::TENANT_MEMBERSHIP_MANAGE,
|
Capabilities::TENANT_MEMBERSHIP_MANAGE,
|
||||||
@ -45,7 +44,6 @@ class RoleCapabilityMap
|
|||||||
Capabilities::TENANT_SYNC,
|
Capabilities::TENANT_SYNC,
|
||||||
Capabilities::TENANT_INVENTORY_SYNC_RUN,
|
Capabilities::TENANT_INVENTORY_SYNC_RUN,
|
||||||
Capabilities::TENANT_FINDINGS_ACKNOWLEDGE,
|
Capabilities::TENANT_FINDINGS_ACKNOWLEDGE,
|
||||||
Capabilities::TENANT_VERIFICATION_ACKNOWLEDGE,
|
|
||||||
|
|
||||||
Capabilities::TENANT_MEMBERSHIP_VIEW,
|
Capabilities::TENANT_MEMBERSHIP_VIEW,
|
||||||
|
|
||||||
|
|||||||
@ -1,100 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Services\Auth;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
use Illuminate\Support\Facades\Log;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Workspace Capability Resolver
|
|
||||||
*
|
|
||||||
* Resolves user memberships and capabilities for a given workspace.
|
|
||||||
* Caches results per request to avoid N+1 queries.
|
|
||||||
*/
|
|
||||||
class WorkspaceCapabilityResolver
|
|
||||||
{
|
|
||||||
private array $resolvedMemberships = [];
|
|
||||||
|
|
||||||
private array $loggedDenials = [];
|
|
||||||
|
|
||||||
public function getRole(User $user, Workspace $workspace): ?WorkspaceRole
|
|
||||||
{
|
|
||||||
$membership = $this->getMembership($user, $workspace);
|
|
||||||
|
|
||||||
if ($membership === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return WorkspaceRole::tryFrom($membership['role']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function can(User $user, Workspace $workspace, string $capability): bool
|
|
||||||
{
|
|
||||||
if (! Capabilities::isKnown($capability)) {
|
|
||||||
throw new \InvalidArgumentException("Unknown capability: {$capability}");
|
|
||||||
}
|
|
||||||
|
|
||||||
$role = $this->getRole($user, $workspace);
|
|
||||||
|
|
||||||
if ($role === null) {
|
|
||||||
$this->logDenial($user, $workspace, $capability);
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$allowed = WorkspaceRoleCapabilityMap::hasCapability($role, $capability);
|
|
||||||
|
|
||||||
if (! $allowed) {
|
|
||||||
$this->logDenial($user, $workspace, $capability);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function isMember(User $user, Workspace $workspace): bool
|
|
||||||
{
|
|
||||||
return $this->getMembership($user, $workspace) !== null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function clearCache(): void
|
|
||||||
{
|
|
||||||
$this->resolvedMemberships = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
private function logDenial(User $user, Workspace $workspace, string $capability): void
|
|
||||||
{
|
|
||||||
$key = implode(':', [(string) $user->getKey(), (string) $workspace->getKey(), $capability]);
|
|
||||||
|
|
||||||
if (isset($this->loggedDenials[$key])) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->loggedDenials[$key] = true;
|
|
||||||
|
|
||||||
Log::warning('rbac.workspace.denied', [
|
|
||||||
'capability' => $capability,
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'actor_user_id' => (int) $user->getKey(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function getMembership(User $user, Workspace $workspace): ?array
|
|
||||||
{
|
|
||||||
$cacheKey = "workspace_membership_{$user->id}_{$workspace->id}";
|
|
||||||
|
|
||||||
if (! isset($this->resolvedMemberships[$cacheKey])) {
|
|
||||||
$membership = WorkspaceMembership::query()
|
|
||||||
->where('user_id', $user->id)
|
|
||||||
->where('workspace_id', $workspace->id)
|
|
||||||
->first(['role']);
|
|
||||||
|
|
||||||
$this->resolvedMemberships[$cacheKey] = $membership?->toArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->resolvedMemberships[$cacheKey];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,303 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Services\Auth;
|
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Models\WorkspaceMembership;
|
|
||||||
use App\Services\Audit\WorkspaceAuditLogger;
|
|
||||||
use App\Support\Audit\AuditActionId;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
use DomainException;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class WorkspaceMembershipManager
|
|
||||||
{
|
|
||||||
public function __construct(public WorkspaceAuditLogger $auditLogger) {}
|
|
||||||
|
|
||||||
public function addMember(
|
|
||||||
Workspace $workspace,
|
|
||||||
User $actor,
|
|
||||||
User $member,
|
|
||||||
string $role,
|
|
||||||
string $source = 'manual',
|
|
||||||
): WorkspaceMembership {
|
|
||||||
$this->assertValidRole($role);
|
|
||||||
$this->assertActorCanManage($actor, $workspace);
|
|
||||||
|
|
||||||
try {
|
|
||||||
return DB::transaction(function () use ($workspace, $actor, $member, $role, $source): WorkspaceMembership {
|
|
||||||
$existing = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', (int) $workspace->getKey())
|
|
||||||
->where('user_id', (int) $member->getKey())
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($existing) {
|
|
||||||
if ($existing->role !== $role) {
|
|
||||||
$fromRole = (string) $existing->role;
|
|
||||||
|
|
||||||
$this->guardLastOwnerDemotion($workspace, $existing, $role);
|
|
||||||
|
|
||||||
$existing->forceFill([
|
|
||||||
'role' => $role,
|
|
||||||
])->save();
|
|
||||||
|
|
||||||
$this->auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipRoleChange->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'member_user_id' => (int) $member->getKey(),
|
|
||||||
'from_role' => $fromRole,
|
|
||||||
'to_role' => $role,
|
|
||||||
'source' => $source,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: 'success',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $existing->refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
$membership = WorkspaceMembership::query()->create([
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'user_id' => (int) $member->getKey(),
|
|
||||||
'role' => $role,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipAdd->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'member_user_id' => (int) $member->getKey(),
|
|
||||||
'role' => $role,
|
|
||||||
'source' => $source,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: 'success',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
);
|
|
||||||
|
|
||||||
return $membership;
|
|
||||||
});
|
|
||||||
} catch (DomainException $exception) {
|
|
||||||
if ($exception->getMessage() === 'You cannot demote the last remaining owner.') {
|
|
||||||
$this->auditLastOwnerBlocked(
|
|
||||||
workspace: $workspace,
|
|
||||||
actor: $actor,
|
|
||||||
targetUserId: (int) $member->getKey(),
|
|
||||||
attemptedRole: $role,
|
|
||||||
currentRole: WorkspaceRole::Owner->value,
|
|
||||||
attemptedAction: 'role_change',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $exception;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function changeRole(Workspace $workspace, User $actor, WorkspaceMembership $membership, string $newRole): WorkspaceMembership
|
|
||||||
{
|
|
||||||
$this->assertValidRole($newRole);
|
|
||||||
$this->assertActorCanManage($actor, $workspace);
|
|
||||||
|
|
||||||
try {
|
|
||||||
return DB::transaction(function () use ($workspace, $actor, $membership, $newRole): WorkspaceMembership {
|
|
||||||
$membership->refresh();
|
|
||||||
|
|
||||||
if ($membership->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
throw new DomainException('Membership belongs to a different workspace.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$oldRole = (string) $membership->role;
|
|
||||||
|
|
||||||
if ($oldRole === $newRole) {
|
|
||||||
return $membership;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->guardLastOwnerDemotion($workspace, $membership, $newRole);
|
|
||||||
|
|
||||||
$membership->forceFill([
|
|
||||||
'role' => $newRole,
|
|
||||||
])->save();
|
|
||||||
|
|
||||||
$this->auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipRoleChange->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'member_user_id' => (int) $membership->user_id,
|
|
||||||
'from_role' => $oldRole,
|
|
||||||
'to_role' => $newRole,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: 'success',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
);
|
|
||||||
|
|
||||||
return $membership->refresh();
|
|
||||||
});
|
|
||||||
} catch (DomainException $exception) {
|
|
||||||
if ($exception->getMessage() === 'You cannot demote the last remaining owner.') {
|
|
||||||
$this->auditLastOwnerBlocked(
|
|
||||||
workspace: $workspace,
|
|
||||||
actor: $actor,
|
|
||||||
targetUserId: (int) $membership->user_id,
|
|
||||||
attemptedRole: $newRole,
|
|
||||||
currentRole: (string) $membership->role,
|
|
||||||
attemptedAction: 'role_change',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $exception;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function removeMember(Workspace $workspace, User $actor, WorkspaceMembership $membership): void
|
|
||||||
{
|
|
||||||
$this->assertActorCanManage($actor, $workspace);
|
|
||||||
|
|
||||||
try {
|
|
||||||
DB::transaction(function () use ($workspace, $actor, $membership): void {
|
|
||||||
$membership->refresh();
|
|
||||||
|
|
||||||
if ($membership->workspace_id !== (int) $workspace->getKey()) {
|
|
||||||
throw new DomainException('Membership belongs to a different workspace.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->guardLastOwnerRemoval($workspace, $membership);
|
|
||||||
|
|
||||||
$memberUserId = (int) $membership->user_id;
|
|
||||||
$oldRole = (string) $membership->role;
|
|
||||||
|
|
||||||
$membership->delete();
|
|
||||||
|
|
||||||
$this->auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipRemove->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'member_user_id' => $memberUserId,
|
|
||||||
'role' => $oldRole,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: 'success',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
} catch (DomainException $exception) {
|
|
||||||
if ($exception->getMessage() === 'You cannot remove the last remaining owner.') {
|
|
||||||
$this->auditLastOwnerBlocked(
|
|
||||||
workspace: $workspace,
|
|
||||||
actor: $actor,
|
|
||||||
targetUserId: (int) $membership->user_id,
|
|
||||||
attemptedRole: (string) $membership->role,
|
|
||||||
currentRole: (string) $membership->role,
|
|
||||||
attemptedAction: 'remove',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $exception;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function assertActorCanManage(User $actor, Workspace $workspace): void
|
|
||||||
{
|
|
||||||
/** @var WorkspaceCapabilityResolver $resolver */
|
|
||||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
|
||||||
|
|
||||||
if (! $resolver->can($actor, $workspace, Capabilities::WORKSPACE_MEMBERSHIP_MANAGE)) {
|
|
||||||
throw new DomainException('Forbidden.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function assertValidRole(string $role): void
|
|
||||||
{
|
|
||||||
$valid = array_map(
|
|
||||||
static fn (WorkspaceRole $workspaceRole): string => $workspaceRole->value,
|
|
||||||
WorkspaceRole::cases(),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (! in_array($role, $valid, true)) {
|
|
||||||
throw new DomainException('Invalid role.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function guardLastOwnerDemotion(Workspace $workspace, WorkspaceMembership $membership, string $newRole): void
|
|
||||||
{
|
|
||||||
if ($membership->role !== WorkspaceRole::Owner->value) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($newRole === WorkspaceRole::Owner->value) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$owners = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', (int) $workspace->getKey())
|
|
||||||
->where('role', WorkspaceRole::Owner->value)
|
|
||||||
->count();
|
|
||||||
|
|
||||||
if ($owners <= 1) {
|
|
||||||
throw new DomainException('You cannot demote the last remaining owner.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function guardLastOwnerRemoval(Workspace $workspace, WorkspaceMembership $membership): void
|
|
||||||
{
|
|
||||||
if ($membership->role !== WorkspaceRole::Owner->value) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$owners = WorkspaceMembership::query()
|
|
||||||
->where('workspace_id', (int) $workspace->getKey())
|
|
||||||
->where('role', WorkspaceRole::Owner->value)
|
|
||||||
->count();
|
|
||||||
|
|
||||||
if ($owners <= 1) {
|
|
||||||
throw new DomainException('You cannot remove the last remaining owner.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function auditLastOwnerBlocked(
|
|
||||||
Workspace $workspace,
|
|
||||||
User $actor,
|
|
||||||
int $targetUserId,
|
|
||||||
string $attemptedRole,
|
|
||||||
string $currentRole,
|
|
||||||
string $attemptedAction,
|
|
||||||
): void {
|
|
||||||
$this->auditLogger->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::WorkspaceMembershipLastOwnerBlocked->value,
|
|
||||||
context: [
|
|
||||||
'metadata' => [
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'actor_user_id' => (int) $actor->getKey(),
|
|
||||||
'target_user_id' => $targetUserId,
|
|
||||||
'attempted_role' => $attemptedRole,
|
|
||||||
'current_role' => $currentRole,
|
|
||||||
'attempted_action' => $attemptedAction,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
status: 'blocked',
|
|
||||||
resourceType: 'workspace',
|
|
||||||
resourceId: (string) $workspace->getKey(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,96 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Services\Auth;
|
|
||||||
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Auth\WorkspaceRole;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Workspace Role to Capability Mapping (Single Source of Truth)
|
|
||||||
*
|
|
||||||
* This class defines which capabilities each workspace role has.
|
|
||||||
* All capability strings MUST be references from the Capabilities registry.
|
|
||||||
*/
|
|
||||||
class WorkspaceRoleCapabilityMap
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @var array<string, array<int, string>>
|
|
||||||
*/
|
|
||||||
private static array $roleCapabilities = [
|
|
||||||
WorkspaceRole::Owner->value => [
|
|
||||||
Capabilities::WORKSPACE_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MANAGE,
|
|
||||||
Capabilities::WORKSPACE_ARCHIVE,
|
|
||||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MEMBERSHIP_MANAGE,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE,
|
|
||||||
],
|
|
||||||
|
|
||||||
WorkspaceRole::Manager->value => [
|
|
||||||
Capabilities::WORKSPACE_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MEMBERSHIP_MANAGE,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
|
||||||
],
|
|
||||||
|
|
||||||
WorkspaceRole::Operator->value => [
|
|
||||||
Capabilities::WORKSPACE_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
|
||||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
|
||||||
],
|
|
||||||
|
|
||||||
WorkspaceRole::Readonly->value => [
|
|
||||||
Capabilities::WORKSPACE_VIEW,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<string>
|
|
||||||
*/
|
|
||||||
public static function getCapabilities(WorkspaceRole|string $role): array
|
|
||||||
{
|
|
||||||
$roleValue = $role instanceof WorkspaceRole ? $role->value : $role;
|
|
||||||
|
|
||||||
return self::$roleCapabilities[$roleValue] ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<string>
|
|
||||||
*/
|
|
||||||
public static function rolesWithCapability(string $capability): array
|
|
||||||
{
|
|
||||||
$roles = [];
|
|
||||||
|
|
||||||
foreach (self::$roleCapabilities as $role => $capabilities) {
|
|
||||||
if (in_array($capability, $capabilities, true)) {
|
|
||||||
$roles[] = $role;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $roles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function hasCapability(WorkspaceRole|string $role, string $capability): bool
|
|
||||||
{
|
|
||||||
return in_array($capability, self::getCapabilities($role), true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -6,25 +6,6 @@
|
|||||||
|
|
||||||
class GraphContractRegistry
|
class GraphContractRegistry
|
||||||
{
|
{
|
||||||
public function probePath(string $key, array $replacements = []): ?string
|
|
||||||
{
|
|
||||||
$path = config("graph_contracts.probes.$key.path");
|
|
||||||
|
|
||||||
if (! is_string($path) || $path === '') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($replacements as $placeholder => $value) {
|
|
||||||
if (! is_string($placeholder) || $placeholder === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$path = str_replace($placeholder, urlencode((string) $value), $path);
|
|
||||||
}
|
|
||||||
|
|
||||||
return '/'.ltrim($path, '/');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function directoryGroupsPolicyType(): string
|
public function directoryGroupsPolicyType(): string
|
||||||
{
|
{
|
||||||
return 'directoryGroups';
|
return 'directoryGroups';
|
||||||
|
|||||||
@ -409,20 +409,7 @@ private function shouldApplySelectFallback(GraphResponse $graphResponse, array $
|
|||||||
public function getOrganization(array $options = []): GraphResponse
|
public function getOrganization(array $options = []): GraphResponse
|
||||||
{
|
{
|
||||||
$context = $this->resolveContext($options);
|
$context = $this->resolveContext($options);
|
||||||
$endpoint = $this->contracts->probePath('organization');
|
$endpoint = 'organization';
|
||||||
|
|
||||||
if (! is_string($endpoint) || $endpoint === '') {
|
|
||||||
return new GraphResponse(
|
|
||||||
success: false,
|
|
||||||
data: [],
|
|
||||||
status: 500,
|
|
||||||
errors: [[
|
|
||||||
'message' => 'Graph contract missing for probe: organization',
|
|
||||||
]],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$endpoint = ltrim($endpoint, '/');
|
|
||||||
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
||||||
$fullPath = $this->buildFullPath($endpoint);
|
$fullPath = $this->buildFullPath($endpoint);
|
||||||
|
|
||||||
@ -492,27 +479,14 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
|||||||
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
||||||
|
|
||||||
// First, get the service principal object by clientId (appId)
|
// First, get the service principal object by clientId (appId)
|
||||||
$endpoint = $this->contracts->probePath('service_principal_by_app_id', ['{appId}' => $clientId]);
|
$endpoint = "servicePrincipals?\$filter=appId eq '{$clientId}'";
|
||||||
|
|
||||||
if (! is_string($endpoint) || $endpoint === '') {
|
|
||||||
return new GraphResponse(
|
|
||||||
success: false,
|
|
||||||
data: [],
|
|
||||||
status: 500,
|
|
||||||
errors: [[
|
|
||||||
'message' => 'Graph contract missing for probe: service_principal_by_app_id',
|
|
||||||
]],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$endpoint = ltrim($endpoint, '/');
|
|
||||||
|
|
||||||
$this->logger->logRequest('get_service_principal', [
|
$this->logger->logRequest('get_service_principal', [
|
||||||
'endpoint' => $endpoint,
|
'endpoint' => $endpoint,
|
||||||
'client_id' => $clientId,
|
'client_id' => $clientId,
|
||||||
'tenant' => $context['tenant'],
|
'tenant' => $context['tenant'],
|
||||||
'method' => 'GET',
|
'method' => 'GET',
|
||||||
'full_path' => $this->buildFullPath($endpoint),
|
'full_path' => $endpoint,
|
||||||
'client_request_id' => $clientRequestId,
|
'client_request_id' => $clientRequestId,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@ -554,30 +528,14 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Now get the app role assignments (application permissions)
|
// Now get the app role assignments (application permissions)
|
||||||
$assignmentsEndpoint = $this->contracts->probePath(
|
$assignmentsEndpoint = "servicePrincipals/{$servicePrincipalId}/appRoleAssignments";
|
||||||
'service_principal_app_role_assignments',
|
|
||||||
['{servicePrincipalId}' => $servicePrincipalId],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (! is_string($assignmentsEndpoint) || $assignmentsEndpoint === '') {
|
|
||||||
return new GraphResponse(
|
|
||||||
success: false,
|
|
||||||
data: [],
|
|
||||||
status: 500,
|
|
||||||
errors: [[
|
|
||||||
'message' => 'Graph contract missing for probe: service_principal_app_role_assignments',
|
|
||||||
]],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$assignmentsEndpoint = ltrim($assignmentsEndpoint, '/');
|
|
||||||
|
|
||||||
$this->logger->logRequest('get_app_role_assignments', [
|
$this->logger->logRequest('get_app_role_assignments', [
|
||||||
'endpoint' => $assignmentsEndpoint,
|
'endpoint' => $assignmentsEndpoint,
|
||||||
'service_principal_id' => $servicePrincipalId,
|
'service_principal_id' => $servicePrincipalId,
|
||||||
'tenant' => $context['tenant'],
|
'tenant' => $context['tenant'],
|
||||||
'method' => 'GET',
|
'method' => 'GET',
|
||||||
'full_path' => $this->buildFullPath($assignmentsEndpoint),
|
'full_path' => $assignmentsEndpoint,
|
||||||
'client_request_id' => $clientRequestId,
|
'client_request_id' => $clientRequestId,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@ -587,68 +545,29 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
|||||||
action: 'get_service_principal_permissions',
|
action: 'get_service_principal_permissions',
|
||||||
response: $assignmentsResponse,
|
response: $assignmentsResponse,
|
||||||
transform: function (array $json) use ($context) {
|
transform: function (array $json) use ($context) {
|
||||||
$assignments = is_array($json['value'] ?? null) ? $json['value'] : [];
|
$assignments = $json['value'] ?? [];
|
||||||
$assignmentsTotal = count($assignments);
|
|
||||||
$permissions = [];
|
$permissions = [];
|
||||||
|
|
||||||
// Get Microsoft Graph service principal to map role IDs to permission names
|
// Get Microsoft Graph service principal to map role IDs to permission names
|
||||||
$graphSpEndpoint = $this->contracts->probePath(
|
$graphSpEndpoint = "servicePrincipals?\$filter=appId eq '00000003-0000-0000-c000-000000000000'";
|
||||||
'service_principal_by_app_id',
|
$graphSpResponse = $this->send('GET', $graphSpEndpoint, [], $context);
|
||||||
['{appId}' => '00000003-0000-0000-c000-000000000000'],
|
$graphSps = $graphSpResponse->json('value', []);
|
||||||
);
|
$appRoles = $graphSps[0]['appRoles'] ?? [];
|
||||||
|
|
||||||
$graphSpResponse = null;
|
|
||||||
|
|
||||||
if (is_string($graphSpEndpoint) && $graphSpEndpoint !== '') {
|
|
||||||
$graphSpResponse = $this->send('GET', ltrim($graphSpEndpoint, '/'), [], $context);
|
|
||||||
}
|
|
||||||
|
|
||||||
$graphSps = $graphSpResponse instanceof Response
|
|
||||||
? $graphSpResponse->json('value', [])
|
|
||||||
: [];
|
|
||||||
$appRoles = is_array($graphSps[0]['appRoles'] ?? null) ? $graphSps[0]['appRoles'] : [];
|
|
||||||
|
|
||||||
// Map role IDs to permission names
|
// Map role IDs to permission names
|
||||||
$roleMap = [];
|
$roleMap = [];
|
||||||
foreach ($appRoles as $role) {
|
foreach ($appRoles as $role) {
|
||||||
$roleId = $role['id'] ?? null;
|
$roleMap[$role['id']] = $role['value'];
|
||||||
$value = $role['value'] ?? null;
|
|
||||||
|
|
||||||
if (! is_string($roleId) || $roleId === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! is_string($value) || $value === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$roleMap[strtolower($roleId)] = $value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($assignments as $assignment) {
|
foreach ($assignments as $assignment) {
|
||||||
$roleId = $assignment['appRoleId'] ?? null;
|
$roleId = $assignment['appRoleId'] ?? null;
|
||||||
|
if ($roleId && isset($roleMap[$roleId])) {
|
||||||
if (! is_string($roleId) || $roleId === '') {
|
$permissions[] = $roleMap[$roleId];
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$normalizedRoleId = strtolower($roleId);
|
|
||||||
|
|
||||||
if (isset($roleMap[$normalizedRoleId])) {
|
|
||||||
$permissions[] = $roleMap[$normalizedRoleId];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$permissions = array_values(array_unique($permissions));
|
return ['permissions' => $permissions];
|
||||||
|
|
||||||
return [
|
|
||||||
'permissions' => $permissions,
|
|
||||||
'diagnostics' => [
|
|
||||||
'assignments_total' => $assignmentsTotal,
|
|
||||||
'mapped_total' => count($permissions),
|
|
||||||
'graph_roles_total' => count($roleMap),
|
|
||||||
],
|
|
||||||
];
|
|
||||||
},
|
},
|
||||||
meta: [
|
meta: [
|
||||||
'tenant' => $context['tenant'] ?? null,
|
'tenant' => $context['tenant'] ?? null,
|
||||||
|
|||||||
@ -4,7 +4,6 @@
|
|||||||
|
|
||||||
use App\Models\AuditLog;
|
use App\Models\AuditLog;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Support\Audit\AuditContextSanitizer;
|
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
class AuditLogger
|
class AuditLogger
|
||||||
@ -23,10 +22,6 @@ public function log(
|
|||||||
$metadata = $context['metadata'] ?? [];
|
$metadata = $context['metadata'] ?? [];
|
||||||
unset($context['metadata']);
|
unset($context['metadata']);
|
||||||
|
|
||||||
$metadata = is_array($metadata) ? $metadata : [];
|
|
||||||
|
|
||||||
$sanitizedMetadata = AuditContextSanitizer::sanitize($metadata + $context);
|
|
||||||
|
|
||||||
return AuditLog::create([
|
return AuditLog::create([
|
||||||
'tenant_id' => $tenant->id,
|
'tenant_id' => $tenant->id,
|
||||||
'actor_id' => $actorId,
|
'actor_id' => $actorId,
|
||||||
@ -36,7 +31,7 @@ public function log(
|
|||||||
'resource_type' => $resourceType,
|
'resource_type' => $resourceType,
|
||||||
'resource_id' => $resourceId,
|
'resource_id' => $resourceId,
|
||||||
'status' => $status,
|
'status' => $status,
|
||||||
'metadata' => $sanitizedMetadata,
|
'metadata' => $metadata + $context,
|
||||||
'recorded_at' => CarbonImmutable::now(),
|
'recorded_at' => CarbonImmutable::now(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -40,79 +40,27 @@ public function getGrantedPermissions(Tenant $tenant): array
|
|||||||
* @param bool $persist Persist comparison results to tenant_permissions
|
* @param bool $persist Persist comparison results to tenant_permissions
|
||||||
* @param bool $liveCheck If true, fetch actual permissions from Graph API
|
* @param bool $liveCheck If true, fetch actual permissions from Graph API
|
||||||
* @param bool $useConfiguredStub Include configured stub permissions when no live check is used
|
* @param bool $useConfiguredStub Include configured stub permissions when no live check is used
|
||||||
* @param array{tenant?:string|null,client_id?:string|null,client_secret?:string|null,client_request_id?:string|null}|null $graphOptions
|
* @return array{overall_status:string,permissions:array<int,array{key:string,type:string,description:?string,features:array<int,string>,status:string,details:array<string,mixed>|null}>}
|
||||||
* @return array{
|
|
||||||
* overall_status:string,
|
|
||||||
* permissions:array<int,array{key:string,type:string,description:?string,features:array<int,string>,status:string,details:array<string,mixed>|null}>,
|
|
||||||
* live_check?: array{attempted:bool,succeeded:bool,http_status:?int,reason_code:?string}
|
|
||||||
* }
|
|
||||||
*/
|
*/
|
||||||
public function compare(
|
public function compare(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
?array $grantedStatuses = null,
|
?array $grantedStatuses = null,
|
||||||
bool $persist = true,
|
bool $persist = true,
|
||||||
bool $liveCheck = false,
|
bool $liveCheck = false,
|
||||||
bool $useConfiguredStub = true,
|
bool $useConfiguredStub = true
|
||||||
?array $graphOptions = null,
|
|
||||||
): array {
|
): array {
|
||||||
$required = $this->getRequiredPermissions();
|
$required = $this->getRequiredPermissions();
|
||||||
$liveCheckMeta = [
|
|
||||||
'attempted' => false,
|
|
||||||
'succeeded' => false,
|
|
||||||
'http_status' => null,
|
|
||||||
'reason_code' => null,
|
|
||||||
];
|
|
||||||
|
|
||||||
$liveCheckFailed = false;
|
$liveCheckFailed = false;
|
||||||
$liveCheckDetails = null;
|
$liveCheckDetails = null;
|
||||||
|
|
||||||
// If liveCheck is requested, fetch actual permissions from Graph
|
// If liveCheck is requested, fetch actual permissions from Graph
|
||||||
if ($liveCheck && $grantedStatuses === null) {
|
if ($liveCheck && $grantedStatuses === null) {
|
||||||
$liveCheckMeta['attempted'] = true;
|
$grantedStatuses = $this->fetchLivePermissions($tenant);
|
||||||
|
|
||||||
$appId = null;
|
|
||||||
if (is_array($graphOptions) && is_string($graphOptions['client_id'] ?? null) && $graphOptions['client_id'] !== '') {
|
|
||||||
$appId = (string) $graphOptions['client_id'];
|
|
||||||
} elseif (is_string($tenant->graphOptions()['client_id'] ?? null) && $tenant->graphOptions()['client_id'] !== '') {
|
|
||||||
$appId = (string) $tenant->graphOptions()['client_id'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($appId !== null) {
|
|
||||||
$liveCheckMeta['app_id'] = $appId;
|
|
||||||
}
|
|
||||||
|
|
||||||
$grantedStatuses = $this->fetchLivePermissions($tenant, $graphOptions);
|
|
||||||
|
|
||||||
if (isset($grantedStatuses['__error'])) {
|
if (isset($grantedStatuses['__error'])) {
|
||||||
$liveCheckFailed = true;
|
$liveCheckFailed = true;
|
||||||
$liveCheckError = is_array($grantedStatuses['__error'] ?? null) ? $grantedStatuses['__error'] : null;
|
$liveCheckDetails = $grantedStatuses['__error']['details'] ?? null;
|
||||||
$liveCheckDetails = is_array($liveCheckError['details'] ?? null)
|
|
||||||
? $liveCheckError['details']
|
|
||||||
: (is_array($liveCheckError) ? $liveCheckError : null);
|
|
||||||
|
|
||||||
$httpStatus = $liveCheckDetails['status'] ?? null;
|
|
||||||
$liveCheckMeta['http_status'] = is_int($httpStatus) ? $httpStatus : null;
|
|
||||||
$liveCheckMeta['reason_code'] = $this->deriveLiveCheckReasonCode(
|
|
||||||
$liveCheckMeta['http_status'],
|
|
||||||
is_array($liveCheckDetails) ? $liveCheckDetails : null,
|
|
||||||
);
|
|
||||||
|
|
||||||
unset($grantedStatuses['__error']);
|
unset($grantedStatuses['__error']);
|
||||||
$grantedStatuses = null;
|
|
||||||
} else {
|
|
||||||
$observedCount = is_array($grantedStatuses) ? count($grantedStatuses) : 0;
|
|
||||||
$liveCheckMeta['observed_permissions_count'] = $observedCount;
|
|
||||||
|
|
||||||
if ($observedCount === 0) {
|
|
||||||
// Enterprise-safe: if the live refresh produced an empty inventory, treat it as non-fresh.
|
|
||||||
// This prevents false "missing" findings due to partial/misconfigured verification context.
|
|
||||||
$liveCheckMeta['succeeded'] = false;
|
|
||||||
$liveCheckMeta['reason_code'] = 'permissions_inventory_empty';
|
|
||||||
$grantedStatuses = null;
|
|
||||||
} else {
|
|
||||||
$liveCheckMeta['succeeded'] = true;
|
|
||||||
$liveCheckMeta['reason_code'] = 'ok';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,29 +81,16 @@ public function compare(
|
|||||||
$hasErrors = false;
|
$hasErrors = false;
|
||||||
$checkedAt = now();
|
$checkedAt = now();
|
||||||
|
|
||||||
$canPersist = $persist;
|
|
||||||
|
|
||||||
if ($liveCheckMeta['attempted'] === true && $liveCheckMeta['succeeded'] === false) {
|
|
||||||
// Enterprise-safe: never overwrite stored inventory when we could not refresh it.
|
|
||||||
$canPersist = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($required as $permission) {
|
foreach ($required as $permission) {
|
||||||
$key = $permission['key'];
|
$key = $permission['key'];
|
||||||
$status = $liveCheckFailed
|
$status = $liveCheckFailed
|
||||||
? 'error'
|
? 'error'
|
||||||
: ($granted[$key]['status'] ?? 'missing');
|
: ($granted[$key]['status'] ?? 'missing');
|
||||||
|
|
||||||
$details = $liveCheckFailed
|
$details = $liveCheckFailed
|
||||||
? array_filter([
|
? ($liveCheckDetails ?? ['source' => 'graph_api'])
|
||||||
'source' => 'graph_api',
|
|
||||||
'status' => $liveCheckMeta['http_status'],
|
|
||||||
'reason_code' => $liveCheckMeta['reason_code'],
|
|
||||||
'message' => is_array($liveCheckDetails) ? ($liveCheckDetails['message'] ?? null) : null,
|
|
||||||
], fn (mixed $value): bool => $value !== null)
|
|
||||||
: ($granted[$key]['details'] ?? null);
|
: ($granted[$key]['details'] ?? null);
|
||||||
|
|
||||||
if ($canPersist) {
|
if ($persist) {
|
||||||
TenantPermission::updateOrCreate(
|
TenantPermission::updateOrCreate(
|
||||||
[
|
[
|
||||||
'tenant_id' => $tenant->id,
|
'tenant_id' => $tenant->id,
|
||||||
@ -188,36 +123,10 @@ public function compare(
|
|||||||
default => 'granted',
|
default => 'granted',
|
||||||
};
|
};
|
||||||
|
|
||||||
$payload = [
|
return [
|
||||||
'overall_status' => $overall,
|
'overall_status' => $overall,
|
||||||
'permissions' => $results,
|
'permissions' => $results,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($liveCheckMeta['attempted'] === true) {
|
|
||||||
$payload['live_check'] = $liveCheckMeta;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed>|null $details
|
|
||||||
*/
|
|
||||||
private function deriveLiveCheckReasonCode(?int $httpStatus, ?array $details = null): string
|
|
||||||
{
|
|
||||||
if (is_array($details) && is_string($details['reason_code'] ?? null)) {
|
|
||||||
return (string) $details['reason_code'];
|
|
||||||
}
|
|
||||||
|
|
||||||
return match (true) {
|
|
||||||
$httpStatus === 401 => 'authentication_failed',
|
|
||||||
$httpStatus === 403 => 'permission_denied',
|
|
||||||
$httpStatus === 408 => 'dependency_unreachable',
|
|
||||||
$httpStatus === 429 => 'throttled',
|
|
||||||
is_int($httpStatus) && $httpStatus >= 500 => 'dependency_unreachable',
|
|
||||||
is_int($httpStatus) && $httpStatus >= 400 => 'unknown_error',
|
|
||||||
default => is_array($details) && is_string($details['message'] ?? null) ? 'dependency_unreachable' : 'unknown_error',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -302,11 +211,11 @@ private function configuredGrantedKeys(): array
|
|||||||
*
|
*
|
||||||
* @return array<string, array{status:string,details:array<string,mixed>|null}>
|
* @return array<string, array{status:string,details:array<string,mixed>|null}>
|
||||||
*/
|
*/
|
||||||
private function fetchLivePermissions(Tenant $tenant, ?array $graphOptions = null): array
|
private function fetchLivePermissions(Tenant $tenant): array
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$response = $this->graphClient->getServicePrincipalPermissions(
|
$response = $this->graphClient->getServicePrincipalPermissions(
|
||||||
$graphOptions ?? $tenant->graphOptions()
|
$tenant->graphOptions()
|
||||||
);
|
);
|
||||||
|
|
||||||
if (! $response->success) {
|
if (! $response->success) {
|
||||||
@ -323,25 +232,6 @@ private function fetchLivePermissions(Tenant $tenant, ?array $graphOptions = nul
|
|||||||
}
|
}
|
||||||
|
|
||||||
$grantedPermissions = $response->data['permissions'] ?? [];
|
$grantedPermissions = $response->data['permissions'] ?? [];
|
||||||
$diagnostics = is_array($response->data['diagnostics'] ?? null) ? $response->data['diagnostics'] : null;
|
|
||||||
$assignmentsTotal = is_array($diagnostics) ? (int) ($diagnostics['assignments_total'] ?? 0) : 0;
|
|
||||||
$mappedTotal = is_array($diagnostics) ? (int) ($diagnostics['mapped_total'] ?? 0) : null;
|
|
||||||
|
|
||||||
if ($assignmentsTotal > 0 && $mappedTotal === 0) {
|
|
||||||
return [
|
|
||||||
'__error' => [
|
|
||||||
'status' => 'error',
|
|
||||||
'details' => [
|
|
||||||
'source' => 'graph_api',
|
|
||||||
'status' => $response->status,
|
|
||||||
'reason_code' => 'permission_mapping_failed',
|
|
||||||
'message' => 'Graph returned app role assignments, but the system could not map them to permission values.',
|
|
||||||
'diagnostics' => $diagnostics,
|
|
||||||
],
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$normalized = [];
|
$normalized = [];
|
||||||
|
|
||||||
foreach ($grantedPermissions as $permission) {
|
foreach ($grantedPermissions as $permission) {
|
||||||
|
|||||||
@ -1,389 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Services\Intune;
|
|
||||||
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Support\Verification\VerificationReportOverall;
|
|
||||||
|
|
||||||
class TenantRequiredPermissionsViewModelBuilder
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @phpstan-type TenantPermissionRow array{key:string,type:'application'|'delegated',description:?string,features:array<int,string>,status:'granted'|'missing'|'error',details:array<string,mixed>|null}
|
|
||||||
* @phpstan-type FeatureImpact array{feature:string,missing:int,required_application:int,required_delegated:int,blocked:bool}
|
|
||||||
* @phpstan-type FilterState array{status:'missing'|'present'|'all',type:'application'|'delegated'|'all',features:array<int,string>,search:string}
|
|
||||||
* @phpstan-type ViewModel array{
|
|
||||||
* tenant: array{id:int,external_id:string,name:string},
|
|
||||||
* overview: array{
|
|
||||||
* overall: string,
|
|
||||||
* counts: array{missing_application:int,missing_delegated:int,present:int,error:int},
|
|
||||||
* feature_impacts: array<int, FeatureImpact>
|
|
||||||
* },
|
|
||||||
* permissions: array<int, TenantPermissionRow>,
|
|
||||||
* filters: FilterState,
|
|
||||||
* copy: array{application:string,delegated:string}
|
|
||||||
* }
|
|
||||||
*/
|
|
||||||
public function __construct(private readonly TenantPermissionService $permissionService) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
* @return ViewModel
|
|
||||||
*/
|
|
||||||
public function build(Tenant $tenant, array $filters = []): array
|
|
||||||
{
|
|
||||||
$comparison = $this->permissionService->compare(
|
|
||||||
$tenant,
|
|
||||||
persist: false,
|
|
||||||
liveCheck: false,
|
|
||||||
useConfiguredStub: false,
|
|
||||||
);
|
|
||||||
|
|
||||||
/** @var array<int, TenantPermissionRow> $allPermissions */
|
|
||||||
$allPermissions = collect($comparison['permissions'] ?? [])
|
|
||||||
->filter(fn (mixed $row): bool => is_array($row))
|
|
||||||
->map(fn (array $row): array => self::normalizePermissionRow($row))
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
|
|
||||||
$state = self::normalizeFilterState($filters);
|
|
||||||
|
|
||||||
$filteredPermissions = self::applyFilterState($allPermissions, $state);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'tenant' => [
|
|
||||||
'id' => (int) $tenant->getKey(),
|
|
||||||
'external_id' => (string) $tenant->external_id,
|
|
||||||
'name' => (string) $tenant->name,
|
|
||||||
],
|
|
||||||
'overview' => [
|
|
||||||
'overall' => self::deriveOverallStatus($allPermissions),
|
|
||||||
'counts' => self::deriveCounts($allPermissions),
|
|
||||||
'feature_impacts' => self::deriveFeatureImpacts($allPermissions),
|
|
||||||
],
|
|
||||||
'permissions' => $filteredPermissions,
|
|
||||||
'filters' => $state,
|
|
||||||
'copy' => [
|
|
||||||
'application' => self::deriveCopyPayload($allPermissions, 'application', $state['features']),
|
|
||||||
'delegated' => self::deriveCopyPayload($allPermissions, 'delegated', $state['features']),
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<int, TenantPermissionRow> $permissions
|
|
||||||
*/
|
|
||||||
public static function deriveOverallStatus(array $permissions): string
|
|
||||||
{
|
|
||||||
$hasMissingApplication = collect($permissions)->contains(
|
|
||||||
fn (array $row): bool => $row['status'] === 'missing' && $row['type'] === 'application',
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($hasMissingApplication) {
|
|
||||||
return VerificationReportOverall::Blocked->value;
|
|
||||||
}
|
|
||||||
|
|
||||||
$hasErrors = collect($permissions)->contains(
|
|
||||||
fn (array $row): bool => $row['status'] === 'error',
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasMissingDelegated = collect($permissions)->contains(
|
|
||||||
fn (array $row): bool => $row['status'] === 'missing' && $row['type'] === 'delegated',
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($hasErrors || $hasMissingDelegated) {
|
|
||||||
return VerificationReportOverall::NeedsAttention->value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return VerificationReportOverall::Ready->value;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<int, TenantPermissionRow> $permissions
|
|
||||||
* @return array{missing_application:int,missing_delegated:int,present:int,error:int}
|
|
||||||
*/
|
|
||||||
public static function deriveCounts(array $permissions): array
|
|
||||||
{
|
|
||||||
$counts = [
|
|
||||||
'missing_application' => 0,
|
|
||||||
'missing_delegated' => 0,
|
|
||||||
'present' => 0,
|
|
||||||
'error' => 0,
|
|
||||||
];
|
|
||||||
|
|
||||||
foreach ($permissions as $row) {
|
|
||||||
if (($row['status'] ?? null) === 'missing') {
|
|
||||||
if (($row['type'] ?? null) === 'delegated') {
|
|
||||||
$counts['missing_delegated'] += 1;
|
|
||||||
} else {
|
|
||||||
$counts['missing_application'] += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($row['status'] ?? null) === 'granted') {
|
|
||||||
$counts['present'] += 1;
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($row['status'] ?? null) === 'error') {
|
|
||||||
$counts['error'] += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $counts;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<int, TenantPermissionRow> $permissions
|
|
||||||
* @return array<int, FeatureImpact>
|
|
||||||
*/
|
|
||||||
public static function deriveFeatureImpacts(array $permissions): array
|
|
||||||
{
|
|
||||||
/** @var array<string, FeatureImpact> $impacts */
|
|
||||||
$impacts = [];
|
|
||||||
|
|
||||||
foreach ($permissions as $row) {
|
|
||||||
$features = array_values(array_unique($row['features'] ?? []));
|
|
||||||
|
|
||||||
foreach ($features as $feature) {
|
|
||||||
if (! isset($impacts[$feature])) {
|
|
||||||
$impacts[$feature] = [
|
|
||||||
'feature' => $feature,
|
|
||||||
'missing' => 0,
|
|
||||||
'required_application' => 0,
|
|
||||||
'required_delegated' => 0,
|
|
||||||
'blocked' => false,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($row['type'] ?? null) === 'delegated') {
|
|
||||||
$impacts[$feature]['required_delegated'] += 1;
|
|
||||||
} else {
|
|
||||||
$impacts[$feature]['required_application'] += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($row['status'] ?? null) === 'missing') {
|
|
||||||
$impacts[$feature]['missing'] += 1;
|
|
||||||
|
|
||||||
if (($row['type'] ?? null) === 'application') {
|
|
||||||
$impacts[$feature]['blocked'] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$values = array_values($impacts);
|
|
||||||
|
|
||||||
usort($values, static function (array $a, array $b): int {
|
|
||||||
$blocked = (int) ($b['blocked'] <=> $a['blocked']);
|
|
||||||
if ($blocked !== 0) {
|
|
||||||
return $blocked;
|
|
||||||
}
|
|
||||||
|
|
||||||
$missing = (int) (($b['missing'] ?? 0) <=> ($a['missing'] ?? 0));
|
|
||||||
if ($missing !== 0) {
|
|
||||||
return $missing;
|
|
||||||
}
|
|
||||||
|
|
||||||
return strcmp((string) ($a['feature'] ?? ''), (string) ($b['feature'] ?? ''));
|
|
||||||
});
|
|
||||||
|
|
||||||
return $values;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Copy payload semantics:
|
|
||||||
* - Always Missing-only
|
|
||||||
* - Always Type fixed by button (application vs delegated)
|
|
||||||
* - Respects Feature filter only
|
|
||||||
* - Ignores Search
|
|
||||||
*
|
|
||||||
* @param array<int, TenantPermissionRow> $permissions
|
|
||||||
* @param 'application'|'delegated' $type
|
|
||||||
* @param array<int, string> $featureFilter
|
|
||||||
*/
|
|
||||||
public static function deriveCopyPayload(array $permissions, string $type, array $featureFilter = []): string
|
|
||||||
{
|
|
||||||
$featureFilter = array_values(array_unique(array_filter(array_map('strval', $featureFilter))));
|
|
||||||
|
|
||||||
$payload = collect($permissions)
|
|
||||||
->filter(function (array $row) use ($type, $featureFilter): bool {
|
|
||||||
if (($row['status'] ?? null) !== 'missing') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($row['type'] ?? null) !== $type) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($featureFilter === []) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$rowFeatures = $row['features'] ?? [];
|
|
||||||
|
|
||||||
return count(array_intersect($featureFilter, $rowFeatures)) > 0;
|
|
||||||
})
|
|
||||||
->pluck('key')
|
|
||||||
->map(fn (mixed $key): string => (string) $key)
|
|
||||||
->filter()
|
|
||||||
->unique()
|
|
||||||
->sort()
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
|
|
||||||
return implode("\n", $payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<int, TenantPermissionRow> $permissions
|
|
||||||
* @return array<int, TenantPermissionRow>
|
|
||||||
*/
|
|
||||||
public static function applyFilterState(array $permissions, array $state): array
|
|
||||||
{
|
|
||||||
$status = $state['status'] ?? 'missing';
|
|
||||||
$type = $state['type'] ?? 'all';
|
|
||||||
$features = $state['features'] ?? [];
|
|
||||||
$search = $state['search'] ?? '';
|
|
||||||
|
|
||||||
$search = is_string($search) ? trim($search) : '';
|
|
||||||
$searchLower = strtolower($search);
|
|
||||||
|
|
||||||
$features = array_values(array_unique(array_filter(array_map('strval', $features))));
|
|
||||||
|
|
||||||
$filtered = collect($permissions)
|
|
||||||
->filter(function (array $row) use ($status, $type, $features): bool {
|
|
||||||
$rowStatus = $row['status'] ?? null;
|
|
||||||
$rowType = $row['type'] ?? null;
|
|
||||||
|
|
||||||
if ($status === 'missing' && ! in_array($rowStatus, ['missing', 'error'], true)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($status === 'present' && $rowStatus !== 'granted') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($type !== 'all' && $rowType !== $type) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($features === []) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$rowFeatures = $row['features'] ?? [];
|
|
||||||
|
|
||||||
return count(array_intersect($features, $rowFeatures)) > 0;
|
|
||||||
})
|
|
||||||
->when($searchLower !== '', function ($collection) use ($searchLower) {
|
|
||||||
return $collection->filter(function (array $row) use ($searchLower): bool {
|
|
||||||
$key = strtolower((string) ($row['key'] ?? ''));
|
|
||||||
$description = strtolower((string) ($row['description'] ?? ''));
|
|
||||||
|
|
||||||
return str_contains($key, $searchLower) || ($description !== '' && str_contains($description, $searchLower));
|
|
||||||
});
|
|
||||||
})
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
|
|
||||||
usort($filtered, static function (array $a, array $b): int {
|
|
||||||
$weight = static function (array $row): int {
|
|
||||||
return match ($row['status'] ?? null) {
|
|
||||||
'missing' => 0,
|
|
||||||
'error' => 1,
|
|
||||||
default => 2,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
$cmp = $weight($a) <=> $weight($b);
|
|
||||||
if ($cmp !== 0) {
|
|
||||||
return $cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return strcmp((string) ($a['key'] ?? ''), (string) ($b['key'] ?? ''));
|
|
||||||
});
|
|
||||||
|
|
||||||
return $filtered;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
* @return FilterState
|
|
||||||
*/
|
|
||||||
public static function normalizeFilterState(array $filters): array
|
|
||||||
{
|
|
||||||
$status = (string) ($filters['status'] ?? 'missing');
|
|
||||||
$type = (string) ($filters['type'] ?? 'all');
|
|
||||||
$features = $filters['features'] ?? [];
|
|
||||||
$search = (string) ($filters['search'] ?? '');
|
|
||||||
|
|
||||||
if (! in_array($status, ['missing', 'present', 'all'], true)) {
|
|
||||||
$status = 'missing';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! in_array($type, ['application', 'delegated', 'all'], true)) {
|
|
||||||
$type = 'all';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! is_array($features)) {
|
|
||||||
$features = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$features = array_values(array_unique(array_filter(array_map('strval', $features))));
|
|
||||||
|
|
||||||
return [
|
|
||||||
'status' => $status,
|
|
||||||
'type' => $type,
|
|
||||||
'features' => $features,
|
|
||||||
'search' => $search,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $row
|
|
||||||
* @return TenantPermissionRow
|
|
||||||
*/
|
|
||||||
private static function normalizePermissionRow(array $row): array
|
|
||||||
{
|
|
||||||
$key = (string) ($row['key'] ?? '');
|
|
||||||
$type = (string) ($row['type'] ?? 'application');
|
|
||||||
$description = $row['description'] ?? null;
|
|
||||||
$features = $row['features'] ?? [];
|
|
||||||
$status = (string) ($row['status'] ?? 'missing');
|
|
||||||
$details = $row['details'] ?? null;
|
|
||||||
|
|
||||||
if (! in_array($type, ['application', 'delegated'], true)) {
|
|
||||||
$type = 'application';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! is_string($description) || $description === '') {
|
|
||||||
$description = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! is_array($features)) {
|
|
||||||
$features = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$features = array_values(array_unique(array_filter(array_map('strval', $features))));
|
|
||||||
|
|
||||||
if (! in_array($status, ['granted', 'missing', 'error'], true)) {
|
|
||||||
$status = 'missing';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! is_array($details)) {
|
|
||||||
$details = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'key' => $key,
|
|
||||||
'type' => $type,
|
|
||||||
'description' => $description,
|
|
||||||
'features' => $features,
|
|
||||||
'status' => $status,
|
|
||||||
'details' => $details,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
68
app/Services/Onboarding/LegacyTenantCredentialMigrator.php
Normal file
68
app/Services/Onboarding/LegacyTenantCredentialMigrator.php
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Services\Onboarding;
|
||||||
|
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\ProviderCredential;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Services\Providers\CredentialManager;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
final class LegacyTenantCredentialMigrator
|
||||||
|
{
|
||||||
|
public function __construct(private readonly CredentialManager $credentials) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{migrated: bool, message: string}
|
||||||
|
*/
|
||||||
|
public function migrate(Tenant $tenant, ProviderConnection $connection): array
|
||||||
|
{
|
||||||
|
if ((int) $connection->tenant_id !== (int) $tenant->getKey()) {
|
||||||
|
throw new InvalidArgumentException('Provider connection does not belong to the tenant.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$clientId = trim((string) ($tenant->app_client_id ?? ''));
|
||||||
|
$clientSecret = trim((string) ($tenant->app_client_secret ?? ''));
|
||||||
|
|
||||||
|
if ($clientId === '' || $clientSecret === '') {
|
||||||
|
return [
|
||||||
|
'migrated' => false,
|
||||||
|
'message' => 'No legacy tenant credentials found to migrate.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$existing = $connection->credential;
|
||||||
|
|
||||||
|
if ($existing instanceof ProviderCredential) {
|
||||||
|
if ($existing->type !== 'client_secret') {
|
||||||
|
throw new RuntimeException('Provider connection has unsupported credential type.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = $existing->payload;
|
||||||
|
$existingClientId = trim((string) Arr::get(is_array($payload) ? $payload : [], 'client_id'));
|
||||||
|
$existingClientSecret = trim((string) Arr::get(is_array($payload) ? $payload : [], 'client_secret'));
|
||||||
|
|
||||||
|
if ($existingClientId !== '' && $existingClientSecret !== '') {
|
||||||
|
return [
|
||||||
|
'migrated' => false,
|
||||||
|
'message' => 'Provider credentials already exist for this connection.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->credentials->upsertClientSecretCredential(
|
||||||
|
connection: $connection,
|
||||||
|
clientId: $clientId,
|
||||||
|
clientSecret: $clientSecret,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'migrated' => true,
|
||||||
|
'message' => 'Legacy tenant credentials migrated to the provider connection.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
94
app/Services/Onboarding/OnboardingEvidenceWriter.php
Normal file
94
app/Services/Onboarding/OnboardingEvidenceWriter.php
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Onboarding;
|
||||||
|
|
||||||
|
use App\Models\OnboardingEvidence;
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\OperationRun;
|
||||||
|
use App\Models\ProviderConnection;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Support\OpsUx\RunFailureSanitizer;
|
||||||
|
|
||||||
|
class OnboardingEvidenceWriter
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
*/
|
||||||
|
public function record(
|
||||||
|
Tenant $tenant,
|
||||||
|
string $taskType,
|
||||||
|
string $status,
|
||||||
|
?string $reasonCode = null,
|
||||||
|
?string $message = null,
|
||||||
|
array $payload = [],
|
||||||
|
?OnboardingSession $session = null,
|
||||||
|
?ProviderConnection $providerConnection = null,
|
||||||
|
?OperationRun $operationRun = null,
|
||||||
|
?User $recordedBy = null,
|
||||||
|
): OnboardingEvidence {
|
||||||
|
$reasonCode = $reasonCode === null ? null : RunFailureSanitizer::normalizeReasonCode($reasonCode);
|
||||||
|
$message = $message === null ? null : RunFailureSanitizer::sanitizeMessage($message);
|
||||||
|
|
||||||
|
/** @var array<string, mixed> $payload */
|
||||||
|
$payload = $this->sanitizePayload($payload);
|
||||||
|
|
||||||
|
return OnboardingEvidence::query()->create([
|
||||||
|
'tenant_id' => $tenant->getKey(),
|
||||||
|
'onboarding_session_id' => $session?->getKey(),
|
||||||
|
'provider_connection_id' => $providerConnection?->getKey(),
|
||||||
|
'task_type' => $taskType,
|
||||||
|
'status' => $status,
|
||||||
|
'reason_code' => $reasonCode,
|
||||||
|
'message' => $message,
|
||||||
|
'payload' => $payload,
|
||||||
|
'operation_run_id' => $operationRun?->getKey(),
|
||||||
|
'recorded_at' => now(),
|
||||||
|
'recorded_by_user_id' => $recordedBy?->getKey(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $payload
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function sanitizePayload(array $payload): array
|
||||||
|
{
|
||||||
|
$redactedKeys = ['access_token', 'refresh_token', 'client_secret', 'password', 'authorization', 'bearer'];
|
||||||
|
|
||||||
|
$sanitize = function (mixed $value) use (&$sanitize, $redactedKeys): mixed {
|
||||||
|
if (is_array($value)) {
|
||||||
|
$out = [];
|
||||||
|
|
||||||
|
foreach ($value as $k => $v) {
|
||||||
|
$key = is_string($k) ? strtolower($k) : null;
|
||||||
|
|
||||||
|
if ($key !== null) {
|
||||||
|
foreach ($redactedKeys as $needle) {
|
||||||
|
if (str_contains($key, $needle)) {
|
||||||
|
$out[$k] = '[REDACTED]';
|
||||||
|
|
||||||
|
continue 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$out[$k] = $sanitize($v);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_string($value)) {
|
||||||
|
return RunFailureSanitizer::sanitizeMessage($value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @var array<string, mixed> $sanitized */
|
||||||
|
$sanitized = $sanitize($payload);
|
||||||
|
|
||||||
|
return $sanitized;
|
||||||
|
}
|
||||||
|
}
|
||||||
89
app/Services/Onboarding/OnboardingLockService.php
Normal file
89
app/Services/Onboarding/OnboardingLockService.php
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Onboarding;
|
||||||
|
|
||||||
|
use App\Models\OnboardingSession;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class OnboardingLockService
|
||||||
|
{
|
||||||
|
public function acquire(OnboardingSession $session, User $user, int $ttlSeconds = 600): bool
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($session, $user, $ttlSeconds): bool {
|
||||||
|
$session = OnboardingSession::query()->lockForUpdate()->findOrFail($session->getKey());
|
||||||
|
|
||||||
|
if ($this->isLockedByOther($session, $user)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$session->forceFill([
|
||||||
|
'locked_by_user_id' => $user->getKey(),
|
||||||
|
'locked_until' => Carbon::now()->addSeconds($ttlSeconds),
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function renew(OnboardingSession $session, User $user, int $ttlSeconds = 600): bool
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($session, $user, $ttlSeconds): bool {
|
||||||
|
$session = OnboardingSession::query()->lockForUpdate()->findOrFail($session->getKey());
|
||||||
|
|
||||||
|
if ((int) $session->locked_by_user_id !== (int) $user->getKey()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$session->forceFill([
|
||||||
|
'locked_until' => Carbon::now()->addSeconds($ttlSeconds),
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function release(OnboardingSession $session, User $user): bool
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($session, $user): bool {
|
||||||
|
$session = OnboardingSession::query()->lockForUpdate()->findOrFail($session->getKey());
|
||||||
|
|
||||||
|
if ((int) $session->locked_by_user_id !== (int) $user->getKey()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$session->forceFill([
|
||||||
|
'locked_by_user_id' => null,
|
||||||
|
'locked_until' => null,
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function takeover(OnboardingSession $session, User $newOwner, int $ttlSeconds = 600): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($session, $newOwner, $ttlSeconds): void {
|
||||||
|
$session = OnboardingSession::query()->lockForUpdate()->findOrFail($session->getKey());
|
||||||
|
|
||||||
|
$session->forceFill([
|
||||||
|
'locked_by_user_id' => $newOwner->getKey(),
|
||||||
|
'locked_until' => Carbon::now()->addSeconds($ttlSeconds),
|
||||||
|
])->save();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function isLockedByOther(OnboardingSession $session, User $user): bool
|
||||||
|
{
|
||||||
|
if ($session->locked_by_user_id === null || $session->locked_until === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($session->locked_until->isPast()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $session->locked_by_user_id !== (int) $user->getKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5,7 +5,6 @@
|
|||||||
use App\Models\OperationRun;
|
use App\Models\OperationRun;
|
||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Notifications\OperationRunCompleted as OperationRunCompletedNotification;
|
use App\Notifications\OperationRunCompleted as OperationRunCompletedNotification;
|
||||||
use App\Notifications\OperationRunQueued as OperationRunQueuedNotification;
|
use App\Notifications\OperationRunQueued as OperationRunQueuedNotification;
|
||||||
use App\Services\Operations\BulkIdempotencyFingerprint;
|
use App\Services\Operations\BulkIdempotencyFingerprint;
|
||||||
@ -61,19 +60,12 @@ public function ensureRun(
|
|||||||
array $inputs,
|
array $inputs,
|
||||||
?User $initiator = null
|
?User $initiator = null
|
||||||
): OperationRun {
|
): OperationRun {
|
||||||
$workspaceId = (int) ($tenant->workspace_id ?? 0);
|
|
||||||
|
|
||||||
if ($workspaceId <= 0) {
|
|
||||||
throw new InvalidArgumentException('Tenant must belong to a workspace to start an operation run.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$hash = $this->calculateHash($tenant->id, $type, $inputs);
|
$hash = $this->calculateHash($tenant->id, $type, $inputs);
|
||||||
|
|
||||||
// Idempotency Check (Fast Path)
|
// Idempotency Check (Fast Path)
|
||||||
// We check specific status to match the partial unique index
|
// We check specific status to match the partial unique index
|
||||||
$existing = OperationRun::query()
|
$existing = OperationRun::query()
|
||||||
->where('tenant_id', $tenant->id)
|
->where('tenant_id', $tenant->id)
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('run_identity_hash', $hash)
|
->where('run_identity_hash', $hash)
|
||||||
->whereIn('status', OperationRunStatus::values())
|
->whereIn('status', OperationRunStatus::values())
|
||||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
->where('status', '!=', OperationRunStatus::Completed->value)
|
||||||
@ -86,7 +78,6 @@ public function ensureRun(
|
|||||||
// Create new run (race-safe via partial unique index)
|
// Create new run (race-safe via partial unique index)
|
||||||
try {
|
try {
|
||||||
return OperationRun::create([
|
return OperationRun::create([
|
||||||
'workspace_id' => $workspaceId,
|
|
||||||
'tenant_id' => $tenant->id,
|
'tenant_id' => $tenant->id,
|
||||||
'user_id' => $initiator?->id,
|
'user_id' => $initiator?->id,
|
||||||
'initiator_name' => $initiator?->name ?? 'System',
|
'initiator_name' => $initiator?->name ?? 'System',
|
||||||
@ -106,7 +97,6 @@ public function ensureRun(
|
|||||||
|
|
||||||
$existing = OperationRun::query()
|
$existing = OperationRun::query()
|
||||||
->where('tenant_id', $tenant->id)
|
->where('tenant_id', $tenant->id)
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('run_identity_hash', $hash)
|
->where('run_identity_hash', $hash)
|
||||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
||||||
->first();
|
->first();
|
||||||
@ -126,19 +116,12 @@ public function ensureRunWithIdentity(
|
|||||||
array $context,
|
array $context,
|
||||||
?User $initiator = null
|
?User $initiator = null
|
||||||
): OperationRun {
|
): OperationRun {
|
||||||
$workspaceId = (int) ($tenant->workspace_id ?? 0);
|
|
||||||
|
|
||||||
if ($workspaceId <= 0) {
|
|
||||||
throw new InvalidArgumentException('Tenant must belong to a workspace to start an operation run.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$hash = $this->calculateHash($tenant->id, $type, $identityInputs);
|
$hash = $this->calculateHash($tenant->id, $type, $identityInputs);
|
||||||
|
|
||||||
// Idempotency Check (Fast Path)
|
// Idempotency Check (Fast Path)
|
||||||
// We check specific status to match the partial unique index
|
// We check specific status to match the partial unique index
|
||||||
$existing = OperationRun::query()
|
$existing = OperationRun::query()
|
||||||
->where('tenant_id', $tenant->id)
|
->where('tenant_id', $tenant->id)
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('run_identity_hash', $hash)
|
->where('run_identity_hash', $hash)
|
||||||
->whereIn('status', OperationRunStatus::values())
|
->whereIn('status', OperationRunStatus::values())
|
||||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
->where('status', '!=', OperationRunStatus::Completed->value)
|
||||||
@ -151,7 +134,6 @@ public function ensureRunWithIdentity(
|
|||||||
// Create new run (race-safe via partial unique index)
|
// Create new run (race-safe via partial unique index)
|
||||||
try {
|
try {
|
||||||
return OperationRun::create([
|
return OperationRun::create([
|
||||||
'workspace_id' => $workspaceId,
|
|
||||||
'tenant_id' => $tenant->id,
|
'tenant_id' => $tenant->id,
|
||||||
'user_id' => $initiator?->id,
|
'user_id' => $initiator?->id,
|
||||||
'initiator_name' => $initiator?->name ?? 'System',
|
'initiator_name' => $initiator?->name ?? 'System',
|
||||||
@ -171,7 +153,6 @@ public function ensureRunWithIdentity(
|
|||||||
|
|
||||||
$existing = OperationRun::query()
|
$existing = OperationRun::query()
|
||||||
->where('tenant_id', $tenant->id)
|
->where('tenant_id', $tenant->id)
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('run_identity_hash', $hash)
|
->where('run_identity_hash', $hash)
|
||||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
||||||
->first();
|
->first();
|
||||||
@ -246,59 +227,6 @@ public function enqueueBulkOperation(
|
|||||||
return $run;
|
return $run;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function ensureWorkspaceRunWithIdentity(
|
|
||||||
Workspace $workspace,
|
|
||||||
string $type,
|
|
||||||
array $identityInputs,
|
|
||||||
array $context,
|
|
||||||
?User $initiator = null,
|
|
||||||
): OperationRun {
|
|
||||||
$hash = $this->calculateWorkspaceHash((int) $workspace->getKey(), $type, $identityInputs);
|
|
||||||
|
|
||||||
$existing = OperationRun::query()
|
|
||||||
->where('workspace_id', (int) $workspace->getKey())
|
|
||||||
->whereNull('tenant_id')
|
|
||||||
->where('run_identity_hash', $hash)
|
|
||||||
->whereIn('status', OperationRunStatus::values())
|
|
||||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($existing) {
|
|
||||||
return $existing;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return OperationRun::create([
|
|
||||||
'workspace_id' => (int) $workspace->getKey(),
|
|
||||||
'tenant_id' => null,
|
|
||||||
'user_id' => $initiator?->id,
|
|
||||||
'initiator_name' => $initiator?->name ?? 'System',
|
|
||||||
'type' => $type,
|
|
||||||
'status' => OperationRunStatus::Queued->value,
|
|
||||||
'outcome' => OperationRunOutcome::Pending->value,
|
|
||||||
'run_identity_hash' => $hash,
|
|
||||||
'context' => $context,
|
|
||||||
]);
|
|
||||||
} catch (QueryException $e) {
|
|
||||||
if (! in_array(($e->errorInfo[0] ?? null), ['23505', '23000'], true)) {
|
|
||||||
throw $e;
|
|
||||||
}
|
|
||||||
|
|
||||||
$existing = OperationRun::query()
|
|
||||||
->where('workspace_id', (int) $workspace->getKey())
|
|
||||||
->whereNull('tenant_id')
|
|
||||||
->where('run_identity_hash', $hash)
|
|
||||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($existing) {
|
|
||||||
return $existing;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updateRun(
|
public function updateRun(
|
||||||
OperationRun $run,
|
OperationRun $run,
|
||||||
string $status,
|
string $status,
|
||||||
@ -590,15 +518,6 @@ protected function calculateHash(int $tenantId, string $type, array $inputs): st
|
|||||||
return hash('sha256', $tenantId.'|'.$type.'|'.$json);
|
return hash('sha256', $tenantId.'|'.$type.'|'.$json);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function calculateWorkspaceHash(int $workspaceId, string $type, array $inputs): string
|
|
||||||
{
|
|
||||||
$normalizedInputs = $this->normalizeInputs($inputs);
|
|
||||||
|
|
||||||
$json = json_encode($normalizedInputs, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
||||||
|
|
||||||
return hash('sha256', 'workspace|'.$workspaceId.'|'.$type.'|'.$json);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize inputs for stable identity hashing.
|
* Normalize inputs for stable identity hashing.
|
||||||
*
|
*
|
||||||
|
|||||||
@ -74,21 +74,4 @@ public function upsertClientSecretCredential(
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateClientIdPreservingSecret(ProviderConnection $connection, string $clientId): ProviderCredential
|
|
||||||
{
|
|
||||||
$clientId = trim($clientId);
|
|
||||||
|
|
||||||
if ($clientId === '') {
|
|
||||||
throw new InvalidArgumentException('client_id is required.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$existing = $this->getClientCredentials($connection);
|
|
||||||
|
|
||||||
return $this->upsertClientSecretCredential(
|
|
||||||
connection: $connection,
|
|
||||||
clientId: $clientId,
|
|
||||||
clientSecret: (string) $existing['client_secret'],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,57 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Services\Verification;
|
|
||||||
|
|
||||||
use App\Jobs\ProviderConnectionHealthCheckJob;
|
|
||||||
use App\Models\OperationRun;
|
|
||||||
use App\Models\ProviderConnection;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Services\Providers\ProviderOperationStartGate;
|
|
||||||
use App\Services\Providers\ProviderOperationStartResult;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use Illuminate\Support\Facades\Gate;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
||||||
|
|
||||||
final class StartVerification
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly ProviderOperationStartGate $providers,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Start (or dedupe) a provider-connection verification run.
|
|
||||||
*
|
|
||||||
* @param array<string, mixed> $extraContext
|
|
||||||
*/
|
|
||||||
public function providerConnectionCheck(
|
|
||||||
Tenant $tenant,
|
|
||||||
ProviderConnection $connection,
|
|
||||||
User $initiator,
|
|
||||||
array $extraContext = [],
|
|
||||||
): ProviderOperationStartResult {
|
|
||||||
if (! $initiator->canAccessTenant($tenant)) {
|
|
||||||
throw new NotFoundHttpException;
|
|
||||||
}
|
|
||||||
|
|
||||||
Gate::forUser($initiator)->authorize(Capabilities::PROVIDER_RUN, $tenant);
|
|
||||||
|
|
||||||
return $this->providers->start(
|
|
||||||
tenant: $tenant,
|
|
||||||
connection: $connection,
|
|
||||||
operationType: 'provider.connection.check',
|
|
||||||
dispatcher: function (OperationRun $run) use ($tenant, $initiator, $connection): void {
|
|
||||||
ProviderConnectionHealthCheckJob::dispatch(
|
|
||||||
tenantId: (int) $tenant->getKey(),
|
|
||||||
userId: (int) $initiator->getKey(),
|
|
||||||
providerConnectionId: (int) $connection->getKey(),
|
|
||||||
operationRun: $run,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
initiator: $initiator,
|
|
||||||
extraContext: $extraContext,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,187 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Services\Verification;
|
|
||||||
|
|
||||||
use App\Models\OperationRun;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\VerificationCheckAcknowledgement;
|
|
||||||
use App\Services\Audit\WorkspaceAuditLogger;
|
|
||||||
use App\Support\Audit\AuditActionId;
|
|
||||||
use App\Support\Auth\Capabilities;
|
|
||||||
use App\Support\Verification\VerificationReportSanitizer;
|
|
||||||
use App\Support\Verification\VerificationReportSchema;
|
|
||||||
use App\Support\Verification\VerificationCheckStatus;
|
|
||||||
use Carbon\CarbonImmutable;
|
|
||||||
use Illuminate\Database\QueryException;
|
|
||||||
use Illuminate\Support\Facades\Gate;
|
|
||||||
use InvalidArgumentException;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
||||||
|
|
||||||
final class VerificationCheckAcknowledgementService
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly WorkspaceAuditLogger $audit,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function acknowledge(
|
|
||||||
Tenant $tenant,
|
|
||||||
OperationRun $run,
|
|
||||||
string $checkKey,
|
|
||||||
string $ackReason,
|
|
||||||
?string $expiresAt,
|
|
||||||
User $actor,
|
|
||||||
): VerificationCheckAcknowledgement {
|
|
||||||
if (! $actor->canAccessTenant($tenant)) {
|
|
||||||
throw new NotFoundHttpException;
|
|
||||||
}
|
|
||||||
|
|
||||||
Gate::forUser($actor)->authorize(Capabilities::TENANT_VERIFICATION_ACKNOWLEDGE, $tenant);
|
|
||||||
|
|
||||||
if ((int) $run->tenant_id !== (int) $tenant->getKey()) {
|
|
||||||
throw new NotFoundHttpException;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((int) $run->workspace_id !== (int) $tenant->workspace_id) {
|
|
||||||
throw new NotFoundHttpException;
|
|
||||||
}
|
|
||||||
|
|
||||||
$checkKey = trim($checkKey);
|
|
||||||
if ($checkKey === '') {
|
|
||||||
throw new InvalidArgumentException('check_key is required.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$ackReason = trim($ackReason);
|
|
||||||
if ($ackReason === '') {
|
|
||||||
throw new InvalidArgumentException('ack_reason is required.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mb_strlen($ackReason) > 160) {
|
|
||||||
throw new InvalidArgumentException('ack_reason must be at most 160 characters.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$report = $this->reportForRun($run);
|
|
||||||
$check = $this->findCheckByKey($report, $checkKey);
|
|
||||||
|
|
||||||
$status = $check['status'] ?? null;
|
|
||||||
|
|
||||||
if (! is_string($status) || ! in_array($status, [VerificationCheckStatus::Fail->value, VerificationCheckStatus::Warn->value], true)) {
|
|
||||||
throw new InvalidArgumentException('Only failing or warning checks can be acknowledged.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$reasonCode = $check['reason_code'] ?? null;
|
|
||||||
if (! is_string($reasonCode) || trim($reasonCode) === '') {
|
|
||||||
throw new InvalidArgumentException('Check reason_code is required.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$expiresAtParsed = null;
|
|
||||||
|
|
||||||
if ($expiresAt !== null && trim($expiresAt) !== '') {
|
|
||||||
try {
|
|
||||||
$expiresAtParsed = CarbonImmutable::parse($expiresAt);
|
|
||||||
} catch (\Throwable) {
|
|
||||||
throw new InvalidArgumentException('expires_at must be a valid date-time.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($expiresAtParsed->isBefore(CarbonImmutable::now())) {
|
|
||||||
throw new InvalidArgumentException('expires_at must be in the future.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$acknowledgedAt = CarbonImmutable::now();
|
|
||||||
|
|
||||||
try {
|
|
||||||
$ack = VerificationCheckAcknowledgement::create([
|
|
||||||
'tenant_id' => (int) $tenant->getKey(),
|
|
||||||
'workspace_id' => (int) $tenant->workspace_id,
|
|
||||||
'operation_run_id' => (int) $run->getKey(),
|
|
||||||
'check_key' => $checkKey,
|
|
||||||
'ack_reason' => $ackReason,
|
|
||||||
'expires_at' => $expiresAtParsed,
|
|
||||||
'acknowledged_at' => $acknowledgedAt,
|
|
||||||
'acknowledged_by_user_id' => (int) $actor->getKey(),
|
|
||||||
]);
|
|
||||||
} catch (QueryException $e) {
|
|
||||||
$ack = VerificationCheckAcknowledgement::query()
|
|
||||||
->where('operation_run_id', (int) $run->getKey())
|
|
||||||
->where('check_key', $checkKey)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (! $ack instanceof VerificationCheckAcknowledgement) {
|
|
||||||
throw $e;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $ack;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($ack->wasRecentlyCreated) {
|
|
||||||
$workspace = $tenant->workspace;
|
|
||||||
|
|
||||||
if ($workspace !== null) {
|
|
||||||
$this->audit->log(
|
|
||||||
workspace: $workspace,
|
|
||||||
action: AuditActionId::VerificationCheckAcknowledged->value,
|
|
||||||
context: [
|
|
||||||
'tenant_id' => (int) $tenant->getKey(),
|
|
||||||
'operation_run_id' => (int) $run->getKey(),
|
|
||||||
'report_id' => (int) $run->getKey(),
|
|
||||||
'flow' => (string) $run->type,
|
|
||||||
'check_key' => $checkKey,
|
|
||||||
'reason_code' => $reasonCode,
|
|
||||||
],
|
|
||||||
actor: $actor,
|
|
||||||
resourceType: 'operation_run',
|
|
||||||
resourceId: (string) $run->getKey(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $ack;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
|
||||||
private function reportForRun(OperationRun $run): array
|
|
||||||
{
|
|
||||||
$context = is_array($run->context) ? $run->context : [];
|
|
||||||
$report = $context['verification_report'] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($report)) {
|
|
||||||
throw new InvalidArgumentException('Verification report is missing.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$report = VerificationReportSanitizer::sanitizeReport($report);
|
|
||||||
|
|
||||||
if (! VerificationReportSchema::isValidReport($report)) {
|
|
||||||
throw new InvalidArgumentException('Verification report is invalid.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $report;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $report
|
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
|
||||||
private function findCheckByKey(array $report, string $checkKey): array
|
|
||||||
{
|
|
||||||
$checks = $report['checks'] ?? null;
|
|
||||||
$checks = is_array($checks) ? $checks : [];
|
|
||||||
|
|
||||||
foreach ($checks as $check) {
|
|
||||||
if (! is_array($check)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($check['key'] ?? null) === $checkKey) {
|
|
||||||
return $check;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new InvalidArgumentException('Check not found in verification report.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ -6,12 +6,6 @@
|
|||||||
|
|
||||||
enum AuditActionId: string
|
enum AuditActionId: string
|
||||||
{
|
{
|
||||||
case WorkspaceMembershipAdd = 'workspace_membership.add';
|
|
||||||
case WorkspaceMembershipRoleChange = 'workspace_membership.role_change';
|
|
||||||
case WorkspaceMembershipRemove = 'workspace_membership.remove';
|
|
||||||
case WorkspaceMembershipLastOwnerBlocked = 'workspace_membership.last_owner_blocked';
|
|
||||||
case WorkspaceMembershipBreakGlassAssignOwner = 'workspace_membership.break_glass.assign_owner';
|
|
||||||
|
|
||||||
case TenantMembershipAdd = 'tenant_membership.add';
|
case TenantMembershipAdd = 'tenant_membership.add';
|
||||||
case TenantMembershipRoleChange = 'tenant_membership.role_change';
|
case TenantMembershipRoleChange = 'tenant_membership.role_change';
|
||||||
case TenantMembershipRemove = 'tenant_membership.remove';
|
case TenantMembershipRemove = 'tenant_membership.remove';
|
||||||
@ -22,12 +16,4 @@ enum AuditActionId: string
|
|||||||
|
|
||||||
// Diagnostics / repair actions.
|
// Diagnostics / repair actions.
|
||||||
case TenantMembershipDuplicatesMerged = 'tenant_membership.duplicates_merged';
|
case TenantMembershipDuplicatesMerged = 'tenant_membership.duplicates_merged';
|
||||||
|
|
||||||
// Managed tenant onboarding wizard.
|
|
||||||
case ManagedTenantOnboardingStart = 'managed_tenant_onboarding.start';
|
|
||||||
case ManagedTenantOnboardingResume = 'managed_tenant_onboarding.resume';
|
|
||||||
case ManagedTenantOnboardingVerificationStart = 'managed_tenant_onboarding.verification_start';
|
|
||||||
case ManagedTenantOnboardingActivation = 'managed_tenant_onboarding.activation';
|
|
||||||
case VerificationCompleted = 'verification.completed';
|
|
||||||
case VerificationCheckAcknowledged = 'verification.check_acknowledged';
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace App\Support\Audit;
|
|
||||||
|
|
||||||
final class AuditContextSanitizer
|
|
||||||
{
|
|
||||||
private const REDACTED = '[REDACTED]';
|
|
||||||
|
|
||||||
public static function sanitize(mixed $value): mixed
|
|
||||||
{
|
|
||||||
if (is_array($value)) {
|
|
||||||
$sanitized = [];
|
|
||||||
|
|
||||||
foreach ($value as $key => $item) {
|
|
||||||
if (is_string($key) && self::shouldRedactKey($key)) {
|
|
||||||
$sanitized[$key] = self::REDACTED;
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$sanitized[$key] = self::sanitize($item);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sanitized;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_string($value)) {
|
|
||||||
return self::sanitizeString($value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function shouldRedactKey(string $key): bool
|
|
||||||
{
|
|
||||||
$key = strtolower(trim($key));
|
|
||||||
|
|
||||||
return str_contains($key, 'token')
|
|
||||||
|| str_contains($key, 'secret')
|
|
||||||
|| str_contains($key, 'password')
|
|
||||||
|| str_contains($key, 'authorization')
|
|
||||||
|| str_contains($key, 'private_key')
|
|
||||||
|| str_contains($key, 'client_secret');
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function sanitizeString(string $value): string
|
|
||||||
{
|
|
||||||
$candidate = trim($value);
|
|
||||||
|
|
||||||
if ($candidate === '') {
|
|
||||||
return $value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('/\bBearer\s+[A-Za-z0-9\-\._~\+\/]+=*\b/i', $candidate)) {
|
|
||||||
return self::REDACTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('/\b[A-Za-z0-9\-_]{20,}\.[A-Za-z0-9\-_]{20,}\.[A-Za-z0-9\-_]{20,}\b/', $candidate)) {
|
|
||||||
return self::REDACTED;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -15,37 +15,6 @@ class Capabilities
|
|||||||
*/
|
*/
|
||||||
private static ?array $all = null;
|
private static ?array $all = null;
|
||||||
|
|
||||||
// Workspaces
|
|
||||||
public const WORKSPACE_VIEW = 'workspace.view';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGE = 'workspace.manage';
|
|
||||||
|
|
||||||
public const WORKSPACE_ARCHIVE = 'workspace.archive';
|
|
||||||
|
|
||||||
// Workspace memberships
|
|
||||||
public const WORKSPACE_MEMBERSHIP_VIEW = 'workspace_membership.view';
|
|
||||||
|
|
||||||
public const WORKSPACE_MEMBERSHIP_MANAGE = 'workspace_membership.manage';
|
|
||||||
|
|
||||||
// Managed tenant onboarding
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD = 'workspace_managed_tenant.onboard';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY = 'workspace_managed_tenant.onboard.identify';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW = 'workspace_managed_tenant.onboard.connection.view';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE = 'workspace_managed_tenant.onboard.connection.manage';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START = 'workspace_managed_tenant.onboard.verification.start';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC = 'workspace_managed_tenant.onboard.bootstrap.inventory_sync';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC = 'workspace_managed_tenant.onboard.bootstrap.policy_sync';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP = 'workspace_managed_tenant.onboard.bootstrap.backup_bootstrap';
|
|
||||||
|
|
||||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE = 'workspace_managed_tenant.onboard.activate';
|
|
||||||
|
|
||||||
// Tenants
|
// Tenants
|
||||||
public const TENANT_VIEW = 'tenant.view';
|
public const TENANT_VIEW = 'tenant.view';
|
||||||
|
|
||||||
@ -61,9 +30,6 @@ class Capabilities
|
|||||||
// Findings
|
// Findings
|
||||||
public const TENANT_FINDINGS_ACKNOWLEDGE = 'tenant_findings.acknowledge';
|
public const TENANT_FINDINGS_ACKNOWLEDGE = 'tenant_findings.acknowledge';
|
||||||
|
|
||||||
// Verification
|
|
||||||
public const TENANT_VERIFICATION_ACKNOWLEDGE = 'tenant_verification.acknowledge';
|
|
||||||
|
|
||||||
// Tenant memberships
|
// Tenant memberships
|
||||||
public const TENANT_MEMBERSHIP_VIEW = 'tenant_membership.view';
|
public const TENANT_MEMBERSHIP_VIEW = 'tenant_membership.view';
|
||||||
|
|
||||||
|
|||||||
@ -44,9 +44,7 @@ class UiEnforcement
|
|||||||
*/
|
*/
|
||||||
private ?\Closure $bulkPreflight = null;
|
private ?\Closure $bulkPreflight = null;
|
||||||
|
|
||||||
public function __construct(private string $capability)
|
public function __construct(private string $capability) {}
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function for(string $capability): self
|
public static function for(string $capability): self
|
||||||
{
|
{
|
||||||
@ -418,6 +416,7 @@ private function resolveTenantIdsForRecords(Collection $records): array
|
|||||||
|
|
||||||
if ($resolved instanceof Tenant) {
|
if ($resolved instanceof Tenant) {
|
||||||
$ids[] = (int) $resolved->getKey();
|
$ids[] = (int) $resolved->getKey();
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -11,4 +11,3 @@ public static function insufficientPermission(): string
|
|||||||
return self::INSUFFICIENT_PERMISSION_ASK_OWNER;
|
return self::INSUFFICIENT_PERMISSION_ASK_OWNER;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Auth;
|
|
||||||
|
|
||||||
enum WorkspaceRole: string
|
|
||||||
{
|
|
||||||
case Owner = 'owner';
|
|
||||||
case Manager = 'manager';
|
|
||||||
case Operator = 'operator';
|
|
||||||
case Readonly = 'readonly';
|
|
||||||
}
|
|
||||||
@ -34,12 +34,9 @@ final class BadgeCatalog
|
|||||||
BadgeDomain::IgnoredAt->value => Domains\IgnoredAtBadge::class,
|
BadgeDomain::IgnoredAt->value => Domains\IgnoredAtBadge::class,
|
||||||
BadgeDomain::RestorePreviewDecision->value => Domains\RestorePreviewDecisionBadge::class,
|
BadgeDomain::RestorePreviewDecision->value => Domains\RestorePreviewDecisionBadge::class,
|
||||||
BadgeDomain::RestoreResultStatus->value => Domains\RestoreResultStatusBadge::class,
|
BadgeDomain::RestoreResultStatus->value => Domains\RestoreResultStatusBadge::class,
|
||||||
|
BadgeDomain::OnboardingTaskStatus->value => Domains\OnboardingTaskStatusBadge::class,
|
||||||
BadgeDomain::ProviderConnectionStatus->value => Domains\ProviderConnectionStatusBadge::class,
|
BadgeDomain::ProviderConnectionStatus->value => Domains\ProviderConnectionStatusBadge::class,
|
||||||
BadgeDomain::ProviderConnectionHealth->value => Domains\ProviderConnectionHealthBadge::class,
|
BadgeDomain::ProviderConnectionHealth->value => Domains\ProviderConnectionHealthBadge::class,
|
||||||
BadgeDomain::ManagedTenantOnboardingVerificationStatus->value => Domains\ManagedTenantOnboardingVerificationStatusBadge::class,
|
|
||||||
BadgeDomain::VerificationCheckStatus->value => Domains\VerificationCheckStatusBadge::class,
|
|
||||||
BadgeDomain::VerificationCheckSeverity->value => Domains\VerificationCheckSeverityBadge::class,
|
|
||||||
BadgeDomain::VerificationReportOverall->value => Domains\VerificationReportOverallBadge::class,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -26,10 +26,7 @@ enum BadgeDomain: string
|
|||||||
case IgnoredAt = 'ignored_at';
|
case IgnoredAt = 'ignored_at';
|
||||||
case RestorePreviewDecision = 'restore_preview_decision';
|
case RestorePreviewDecision = 'restore_preview_decision';
|
||||||
case RestoreResultStatus = 'restore_result_status';
|
case RestoreResultStatus = 'restore_result_status';
|
||||||
|
case OnboardingTaskStatus = 'onboarding_task.status';
|
||||||
case ProviderConnectionStatus = 'provider_connection.status';
|
case ProviderConnectionStatus = 'provider_connection.status';
|
||||||
case ProviderConnectionHealth = 'provider_connection.health';
|
case ProviderConnectionHealth = 'provider_connection.health';
|
||||||
case ManagedTenantOnboardingVerificationStatus = 'managed_tenant_onboarding.verification_status';
|
|
||||||
case VerificationCheckStatus = 'verification_check_status';
|
|
||||||
case VerificationCheckSeverity = 'verification_check_severity';
|
|
||||||
case VerificationReportOverall = 'verification_report_overall';
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Badges\Domains;
|
|
||||||
|
|
||||||
use App\Support\Badges\BadgeCatalog;
|
|
||||||
use App\Support\Badges\BadgeMapper;
|
|
||||||
use App\Support\Badges\BadgeSpec;
|
|
||||||
|
|
||||||
final class ManagedTenantOnboardingVerificationStatusBadge implements BadgeMapper
|
|
||||||
{
|
|
||||||
public function spec(mixed $value): BadgeSpec
|
|
||||||
{
|
|
||||||
$state = BadgeCatalog::normalizeState($value);
|
|
||||||
|
|
||||||
return match ($state) {
|
|
||||||
'not_started' => new BadgeSpec('Not started', 'gray', 'heroicon-m-minus-circle'),
|
|
||||||
'in_progress' => new BadgeSpec('In progress', 'info', 'heroicon-m-arrow-path'),
|
|
||||||
'needs_attention' => new BadgeSpec('Needs attention', 'warning', 'heroicon-m-exclamation-triangle'),
|
|
||||||
'blocked' => new BadgeSpec('Blocked', 'danger', 'heroicon-m-x-circle'),
|
|
||||||
'ready' => new BadgeSpec('Ready', 'success', 'heroicon-m-check-circle'),
|
|
||||||
default => BadgeSpec::unknown(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
23
app/Support/Badges/Domains/OnboardingTaskStatusBadge.php
Normal file
23
app/Support/Badges/Domains/OnboardingTaskStatusBadge.php
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\Badges\Domains;
|
||||||
|
|
||||||
|
use App\Support\Badges\BadgeCatalog;
|
||||||
|
use App\Support\Badges\BadgeMapper;
|
||||||
|
use App\Support\Badges\BadgeSpec;
|
||||||
|
|
||||||
|
final class OnboardingTaskStatusBadge implements BadgeMapper
|
||||||
|
{
|
||||||
|
public function spec(mixed $value): BadgeSpec
|
||||||
|
{
|
||||||
|
$state = BadgeCatalog::normalizeState($value);
|
||||||
|
|
||||||
|
return match ($state) {
|
||||||
|
'ok' => new BadgeSpec('OK', 'success', 'heroicon-m-check-circle'),
|
||||||
|
'warn' => new BadgeSpec('Warning', 'warning', 'heroicon-m-exclamation-triangle'),
|
||||||
|
'fail' => new BadgeSpec('Failed', 'danger', 'heroicon-m-x-circle'),
|
||||||
|
'unknown' => new BadgeSpec('Unknown', 'gray', 'heroicon-m-question-mark-circle'),
|
||||||
|
default => BadgeSpec::unknown(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -13,7 +13,6 @@ public function spec(mixed $value): BadgeSpec
|
|||||||
$state = BadgeCatalog::normalizeState($value);
|
$state = BadgeCatalog::normalizeState($value);
|
||||||
|
|
||||||
return match ($state) {
|
return match ($state) {
|
||||||
'pending' => new BadgeSpec('Pending', 'warning', 'heroicon-m-clock'),
|
|
||||||
'active' => new BadgeSpec('Active', 'success', 'heroicon-m-check-circle'),
|
'active' => new BadgeSpec('Active', 'success', 'heroicon-m-check-circle'),
|
||||||
'inactive' => new BadgeSpec('Inactive', 'gray', 'heroicon-m-minus-circle'),
|
'inactive' => new BadgeSpec('Inactive', 'gray', 'heroicon-m-minus-circle'),
|
||||||
'archived' => new BadgeSpec('Archived', 'gray', 'heroicon-m-minus-circle'),
|
'archived' => new BadgeSpec('Archived', 'gray', 'heroicon-m-minus-circle'),
|
||||||
|
|||||||
@ -1,25 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Badges\Domains;
|
|
||||||
|
|
||||||
use App\Support\Badges\BadgeCatalog;
|
|
||||||
use App\Support\Badges\BadgeMapper;
|
|
||||||
use App\Support\Badges\BadgeSpec;
|
|
||||||
use App\Support\Verification\VerificationCheckSeverity;
|
|
||||||
|
|
||||||
final class VerificationCheckSeverityBadge implements BadgeMapper
|
|
||||||
{
|
|
||||||
public function spec(mixed $value): BadgeSpec
|
|
||||||
{
|
|
||||||
$state = BadgeCatalog::normalizeState($value);
|
|
||||||
|
|
||||||
return match ($state) {
|
|
||||||
VerificationCheckSeverity::Info->value => new BadgeSpec('Info', 'gray', 'heroicon-m-information-circle'),
|
|
||||||
VerificationCheckSeverity::Low->value => new BadgeSpec('Low', 'info', 'heroicon-m-arrow-down'),
|
|
||||||
VerificationCheckSeverity::Medium->value => new BadgeSpec('Medium', 'warning', 'heroicon-m-exclamation-triangle'),
|
|
||||||
VerificationCheckSeverity::High->value => new BadgeSpec('High', 'danger', 'heroicon-m-exclamation-triangle'),
|
|
||||||
VerificationCheckSeverity::Critical->value => new BadgeSpec('Critical', 'danger', 'heroicon-m-x-circle'),
|
|
||||||
default => BadgeSpec::unknown(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Badges\Domains;
|
|
||||||
|
|
||||||
use App\Support\Badges\BadgeCatalog;
|
|
||||||
use App\Support\Badges\BadgeMapper;
|
|
||||||
use App\Support\Badges\BadgeSpec;
|
|
||||||
use App\Support\Verification\VerificationCheckStatus;
|
|
||||||
|
|
||||||
final class VerificationCheckStatusBadge implements BadgeMapper
|
|
||||||
{
|
|
||||||
public function spec(mixed $value): BadgeSpec
|
|
||||||
{
|
|
||||||
$state = BadgeCatalog::normalizeState($value);
|
|
||||||
|
|
||||||
return match ($state) {
|
|
||||||
VerificationCheckStatus::Pass->value => new BadgeSpec('Pass', 'success', 'heroicon-m-check-circle'),
|
|
||||||
VerificationCheckStatus::Fail->value => new BadgeSpec('Fail', 'danger', 'heroicon-m-x-circle'),
|
|
||||||
VerificationCheckStatus::Warn->value => new BadgeSpec('Warn', 'warning', 'heroicon-m-exclamation-triangle'),
|
|
||||||
VerificationCheckStatus::Skip->value => new BadgeSpec('Skipped', 'gray', 'heroicon-m-minus-circle'),
|
|
||||||
VerificationCheckStatus::Running->value => new BadgeSpec('Running', 'info', 'heroicon-m-arrow-path'),
|
|
||||||
default => BadgeSpec::unknown(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Badges\Domains;
|
|
||||||
|
|
||||||
use App\Support\Badges\BadgeCatalog;
|
|
||||||
use App\Support\Badges\BadgeMapper;
|
|
||||||
use App\Support\Badges\BadgeSpec;
|
|
||||||
use App\Support\Verification\VerificationReportOverall;
|
|
||||||
|
|
||||||
final class VerificationReportOverallBadge implements BadgeMapper
|
|
||||||
{
|
|
||||||
public function spec(mixed $value): BadgeSpec
|
|
||||||
{
|
|
||||||
$state = BadgeCatalog::normalizeState($value);
|
|
||||||
|
|
||||||
return match ($state) {
|
|
||||||
VerificationReportOverall::Ready->value => new BadgeSpec('Ready', 'success', 'heroicon-m-check-circle'),
|
|
||||||
VerificationReportOverall::NeedsAttention->value => new BadgeSpec('Needs attention', 'warning', 'heroicon-m-exclamation-triangle'),
|
|
||||||
VerificationReportOverall::Blocked->value => new BadgeSpec('Blocked', 'danger', 'heroicon-m-x-circle'),
|
|
||||||
VerificationReportOverall::Running->value => new BadgeSpec('Running', 'info', 'heroicon-m-arrow-path'),
|
|
||||||
default => BadgeSpec::unknown(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,42 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Links;
|
|
||||||
|
|
||||||
use App\Filament\Resources\TenantResource;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
|
|
||||||
final class RequiredPermissionsLinks
|
|
||||||
{
|
|
||||||
private const ADMIN_CONSENT_GUIDE_URL = 'https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/grant-admin-consent';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
*/
|
|
||||||
public static function requiredPermissions(Tenant $tenant, array $filters = []): string
|
|
||||||
{
|
|
||||||
$base = sprintf('/admin/t/%s/required-permissions', urlencode((string) $tenant->external_id));
|
|
||||||
|
|
||||||
if ($filters === []) {
|
|
||||||
return $base;
|
|
||||||
}
|
|
||||||
|
|
||||||
$query = http_build_query($filters);
|
|
||||||
|
|
||||||
return $query !== '' ? "{$base}?{$query}" : $base;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function adminConsentUrl(Tenant $tenant): ?string
|
|
||||||
{
|
|
||||||
return TenantResource::adminConsentUrl($tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function adminConsentGuideUrl(): string
|
|
||||||
{
|
|
||||||
return self::ADMIN_CONSENT_GUIDE_URL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function adminConsentPrimaryUrl(Tenant $tenant): string
|
|
||||||
{
|
|
||||||
return self::adminConsentUrl($tenant) ?? self::adminConsentGuideUrl();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,206 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Support\Middleware;
|
|
||||||
|
|
||||||
use App\Filament\Pages\ChooseWorkspace;
|
|
||||||
use App\Models\Tenant;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Models\Workspace;
|
|
||||||
use App\Services\Auth\CapabilityResolver;
|
|
||||||
use App\Support\Workspaces\WorkspaceContext;
|
|
||||||
use Closure;
|
|
||||||
use Filament\Facades\Filament;
|
|
||||||
use Filament\Models\Contracts\HasTenants;
|
|
||||||
use Filament\Navigation\NavigationBuilder;
|
|
||||||
use Filament\Navigation\NavigationItem;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
|
|
||||||
class EnsureFilamentTenantSelected
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @param Closure(Request): Response $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next): Response
|
|
||||||
{
|
|
||||||
$panel = Filament::getCurrentOrDefaultPanel();
|
|
||||||
|
|
||||||
$path = '/'.ltrim($request->path(), '/');
|
|
||||||
|
|
||||||
if ($path === '/livewire/update') {
|
|
||||||
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
|
|
||||||
$refererPath = '/'.ltrim((string) $refererPath, '/');
|
|
||||||
|
|
||||||
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($request->route()?->hasParameter('tenant')) {
|
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
if ($user === null) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $user instanceof HasTenants) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $panel->hasTenancy()) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenantParameter = $request->route()->parameter('tenant');
|
|
||||||
$tenant = $panel->getTenant($tenantParameter);
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspaceContext = app(WorkspaceContext::class);
|
|
||||||
$workspaceId = $workspaceContext->currentWorkspaceId($request);
|
|
||||||
|
|
||||||
if ($workspaceId === null) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((int) $tenant->workspace_id !== (int) $workspaceId) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
|
||||||
|
|
||||||
if (! $workspace instanceof Workspace) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $user instanceof User || ! $workspaceContext->isMember($user, $workspace)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $user->canAccessTenant($tenant)) {
|
|
||||||
abort(404);
|
|
||||||
}
|
|
||||||
|
|
||||||
Filament::setTenant($tenant, true);
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
str_starts_with($path, '/admin/w/')
|
|
||||||
|| str_starts_with($path, '/admin/workspaces')
|
|
||||||
|| in_array($path, ['/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access'], true)
|
|
||||||
) {
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filled(Filament::getTenant())) {
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
if (! $user instanceof User) {
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant = null;
|
|
||||||
|
|
||||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);
|
|
||||||
|
|
||||||
if ($workspaceId !== null) {
|
|
||||||
$tenant = $user->tenants()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->where('status', 'active')
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
$tenant = $user->tenants()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
$tenant = $user->tenants()
|
|
||||||
->withTrashed()
|
|
||||||
->where('workspace_id', $workspaceId)
|
|
||||||
->first();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
try {
|
|
||||||
$tenant = Tenant::current();
|
|
||||||
} catch (\RuntimeException) {
|
|
||||||
$tenant = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenant instanceof Tenant && ! app(CapabilityResolver::class)->isMember($user, $tenant)) {
|
|
||||||
$tenant = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
$tenant = $user->tenants()
|
|
||||||
->where('status', 'active')
|
|
||||||
->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
$tenant = $user->tenants()->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
$tenant = $user->tenants()->withTrashed()->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($tenant) {
|
|
||||||
Filament::setTenant($tenant, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->configureNavigationForRequest($panel);
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function configureNavigationForRequest(\Filament\Panel $panel): void
|
|
||||||
{
|
|
||||||
if (! $panel->hasTenancy()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filled(Filament::getTenant())) {
|
|
||||||
$panel->navigation(true);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$panel->navigation(function (): NavigationBuilder {
|
|
||||||
return app(NavigationBuilder::class)
|
|
||||||
->item(
|
|
||||||
NavigationItem::make('Workspaces')
|
|
||||||
->url(fn (): string => ChooseWorkspace::getUrl())
|
|
||||||
->icon('heroicon-o-squares-2x2')
|
|
||||||
->group('Settings')
|
|
||||||
->sort(10),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
54
app/Support/Onboarding/OnboardingFixHints.php
Normal file
54
app/Support/Onboarding/OnboardingFixHints.php
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Support\Onboarding;
|
||||||
|
|
||||||
|
use App\Support\OpsUx\RunFailureSanitizer;
|
||||||
|
|
||||||
|
final class OnboardingFixHints
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public static function forReason(?string $reasonCode): array
|
||||||
|
{
|
||||||
|
if (! is_string($reasonCode) || trim($reasonCode) === '') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = RunFailureSanitizer::normalizeReasonCode($reasonCode);
|
||||||
|
|
||||||
|
return match ($normalized) {
|
||||||
|
RunFailureSanitizer::REASON_PERMISSION_DENIED => [
|
||||||
|
'Confirm admin consent is granted for all required Microsoft Graph permissions.',
|
||||||
|
'Verify the Azure app registration has the correct API permissions assigned.',
|
||||||
|
'Re-run “Verify permissions” after updating consent/permissions.',
|
||||||
|
],
|
||||||
|
RunFailureSanitizer::REASON_PROVIDER_AUTH_FAILED => [
|
||||||
|
'Confirm the client secret is valid and not expired.',
|
||||||
|
'Verify the tenant ID and client ID are correct for this connection.',
|
||||||
|
'Re-save credentials and re-run the task.',
|
||||||
|
],
|
||||||
|
RunFailureSanitizer::REASON_GRAPH_THROTTLED, RunFailureSanitizer::REASON_GRAPH_TIMEOUT => [
|
||||||
|
'Wait a few minutes and try again (transient Graph errors are common).',
|
||||||
|
'Run the task during off-peak hours if throttling persists.',
|
||||||
|
],
|
||||||
|
RunFailureSanitizer::REASON_PROVIDER_OUTAGE => [
|
||||||
|
'Check Microsoft 365 service health / Graph status and try again later.',
|
||||||
|
],
|
||||||
|
RunFailureSanitizer::REASON_VALIDATION_ERROR => [
|
||||||
|
'Double-check the selected provider connection and tenant settings.',
|
||||||
|
'Review the error message for which input is invalid (no secrets are shown).',
|
||||||
|
],
|
||||||
|
RunFailureSanitizer::REASON_CONFLICT_DETECTED => [
|
||||||
|
'Review what changed in the tenant before rerunning.',
|
||||||
|
'If a conflicting configuration exists, resolve it and re-run the task.',
|
||||||
|
],
|
||||||
|
default => [
|
||||||
|
'Retry the task and review the latest evidence message.',
|
||||||
|
'If the issue persists, ask an Owner to review tenant access and connection settings.',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
86
app/Support/Onboarding/OnboardingTaskCatalog.php
Normal file
86
app/Support/Onboarding/OnboardingTaskCatalog.php
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\Onboarding;
|
||||||
|
|
||||||
|
final class OnboardingTaskCatalog
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<int, array{task_type: string, title: string, step: int, prerequisites: array<int, string>}>
|
||||||
|
*/
|
||||||
|
public static function all(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
[
|
||||||
|
'task_type' => OnboardingTaskType::VerifyPermissions,
|
||||||
|
'title' => 'Verify permissions',
|
||||||
|
'step' => 4,
|
||||||
|
'prerequisites' => [],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'task_type' => OnboardingTaskType::ConsentStatus,
|
||||||
|
'title' => 'Check consent status',
|
||||||
|
'step' => 4,
|
||||||
|
'prerequisites' => [OnboardingTaskType::VerifyPermissions],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'task_type' => OnboardingTaskType::ConnectionDiagnostics,
|
||||||
|
'title' => 'Run connection diagnostics',
|
||||||
|
'step' => 4,
|
||||||
|
'prerequisites' => [OnboardingTaskType::VerifyPermissions],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'task_type' => OnboardingTaskType::InitialSync,
|
||||||
|
'title' => 'Initial sync',
|
||||||
|
'step' => 5,
|
||||||
|
'prerequisites' => [OnboardingTaskType::VerifyPermissions],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{task_type: string, title: string, step: int, prerequisites: array<int, string>}|null
|
||||||
|
*/
|
||||||
|
public static function find(string $taskType): ?array
|
||||||
|
{
|
||||||
|
foreach (self::all() as $task) {
|
||||||
|
if ($task['task_type'] === $taskType) {
|
||||||
|
return $task;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $latestEvidenceStatusByTaskType
|
||||||
|
*/
|
||||||
|
public static function prerequisitesMet(string $taskType, array $latestEvidenceStatusByTaskType): bool
|
||||||
|
{
|
||||||
|
return count(self::unmetPrerequisites($taskType, $latestEvidenceStatusByTaskType)) === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $latestEvidenceStatusByTaskType
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public static function unmetPrerequisites(string $taskType, array $latestEvidenceStatusByTaskType): array
|
||||||
|
{
|
||||||
|
$task = self::find($taskType);
|
||||||
|
|
||||||
|
if (! $task) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$unmet = [];
|
||||||
|
|
||||||
|
foreach ($task['prerequisites'] as $requiredTaskType) {
|
||||||
|
$status = $latestEvidenceStatusByTaskType[$requiredTaskType] ?? 'unknown';
|
||||||
|
|
||||||
|
if ($status !== 'ok') {
|
||||||
|
$unmet[] = $requiredTaskType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $unmet;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user