From 9e8e919ade80f1d90ce4393cfe4d5f1da556c9b5 Mon Sep 17 00:00:00 2001 From: danielhe4rt Date: Tue, 8 Sep 2026 00:00:07 -0300 Subject: [PATCH] feat(identity): super admin como role do spatie/laravel-permission MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Substitui a lista de usernames em HE4RT_ADMINS_USERNAMES pela role super-admin. O papel é atribuído pelo próprio UserResource do painel admin, com bootstrap em produção pelo comando identity:grant-super-admin. - Gate::before libera qualquer ability para quem tem a role - model_has_roles.model_id é uuid, porque users.id é uuid - admin não altera os próprios papéis pelo form - testes passam a usar User::factory()->superAdmin() --- .../tests/Feature/EventResourceTest.php | 4 +- .../database/factories/UserFactory.php | 11 + ..._09_08_025342_create_permission_tables.php | 111 +++++++++ .../identity/database/seeders/RolesSeeder.php | 22 ++ .../0002-super-admin-via-spatie-permission.md | 40 ++++ .../Authorization/Console/GrantSuperAdmin.php | 43 ++++ .../src/Authorization/Enums/UserRole.php | 60 +++++ .../identity/src/IdentityServiceProvider.php | 8 + app-modules/identity/src/User/Models/User.php | 12 +- .../GrantSuperAdminCommandTest.php | 31 +++ .../Authorization/SuperAdminGateTest.php | 19 ++ .../tests/Unit/Authorization/UserRoleTest.php | 18 ++ .../Resources/Users/Schemas/UserForm.php | 35 +++ .../Resources/Users/Schemas/UserInfolist.php | 8 + .../Resources/Users/Tables/UsersTable.php | 14 ++ .../Filament/Resources/Users/UserResource.php | 2 +- .../tests/Feature/AdminPanelAccessTest.php | 26 ++- .../Feature/Albums/AlbumResourceTest.php | 3 +- .../Contents/ContentEntryResourceTest.php | 3 +- .../Discord/DiscordClusterSmokeTest.php | 4 +- .../Github/GithubRepositoryResourceTest.php | 4 +- .../Identity/ExternalIdentityResourceTest.php | 3 +- .../Feature/Identity/UserResourceTest.php | 61 ++++- .../Marketing/ShortLinkResourceTest.php | 3 +- .../Feature/Moderation/AppealQueueTest.php | 4 +- .../Moderation/ModerationDashboardTest.php | 4 +- .../Moderation/ModerationQueueTest.php | 4 +- .../Feature/Moderation/TestRuleActionTest.php | 4 +- .../tests/Feature/NavigationGroupsTest.php | 4 +- .../Feature/Profile/ProfileResourceTest.php | 3 +- .../Feature/Profile/SkillResourceTest.php | 3 +- .../Feature/Retrospective/BuildDeckTest.php | 4 +- .../RetrospectiveResourceTest.php | 4 +- .../Twitch/ConnectTwitchActionTest.php | 4 +- .../RegisterSubscriptionsActionTest.php | 4 +- app-modules/squads/CONTEXT.md | 26 +-- .../Tools/TelescopeServiceProvider.php | 2 +- composer.json | 1 + composer.lock | 95 +++++++- config/he4rt.php | 1 - config/permission.php | 221 ++++++++++++++++++ database/seeders/BaseSeeder.php | 6 + 42 files changed, 856 insertions(+), 83 deletions(-) create mode 100644 app-modules/identity/database/migrations/2026_09_08_025342_create_permission_tables.php create mode 100644 app-modules/identity/database/seeders/RolesSeeder.php create mode 100644 app-modules/identity/docs/adr/0002-super-admin-via-spatie-permission.md create mode 100644 app-modules/identity/src/Authorization/Console/GrantSuperAdmin.php create mode 100644 app-modules/identity/src/Authorization/Enums/UserRole.php create mode 100644 app-modules/identity/tests/Feature/Authorization/GrantSuperAdminCommandTest.php create mode 100644 app-modules/identity/tests/Feature/Authorization/SuperAdminGateTest.php create mode 100644 app-modules/identity/tests/Unit/Authorization/UserRoleTest.php create mode 100644 config/permission.php diff --git a/app-modules/events/tests/Feature/EventResourceTest.php b/app-modules/events/tests/Feature/EventResourceTest.php index e785c8b98..e3e3104af 100644 --- a/app-modules/events/tests/Feature/EventResourceTest.php +++ b/app-modules/events/tests/Feature/EventResourceTest.php @@ -26,9 +26,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $admin = User::factory()->create(['username' => 'events-test-admin']); - - config(['he4rt.admins' => 'events-test-admin']); + $admin = User::factory()->superAdmin()->create(['username' => 'events-test-admin']); $this->actingAs($admin); Filament::setCurrentPanel(Filament::getPanel('admin')); diff --git a/app-modules/identity/database/factories/UserFactory.php b/app-modules/identity/database/factories/UserFactory.php index 41d491ae2..b5cfc9be5 100644 --- a/app-modules/identity/database/factories/UserFactory.php +++ b/app-modules/identity/database/factories/UserFactory.php @@ -4,9 +4,11 @@ namespace He4rt\Identity\Database\Factories; +use He4rt\Identity\Authorization\Enums\UserRole; use He4rt\Identity\User\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; +use Spatie\Permission\Models\Role; /** * @extends Factory @@ -26,4 +28,13 @@ public function definition(): array 'is_donator' => false, ]; } + + public function superAdmin(): static + { + return $this->afterCreating(function (User $user): void { + Role::findOrCreate(UserRole::SuperAdmin->value, UserRole::GUARD); + + $user->assignRole(UserRole::SuperAdmin); + }); + } } diff --git a/app-modules/identity/database/migrations/2026_09_08_025342_create_permission_tables.php b/app-modules/identity/database/migrations/2026_09_08_025342_create_permission_tables.php new file mode 100644 index 000000000..f30c437a9 --- /dev/null +++ b/app-modules/identity/database/migrations/2026_09_08_025342_create_permission_tables.php @@ -0,0 +1,111 @@ +bigIncrements('id'); + $table->string('name'); + $table->string('guard_name'); + $table->timestampsTz(); + + $table->unique(['name', 'guard_name']); + }); + + Schema::create($tableNames['roles'], function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('name'); + $table->string('guard_name'); + $table->timestampsTz(); + + $table->unique(['name', 'guard_name']); + }); + + Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission): void { + $table->unsignedBigInteger($pivotPermission); + + $table->string('model_type'); + $table->uuid($columnNames['model_morph_key']); + $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index'); + + $table->foreign($pivotPermission) + ->references('id') + ->on($tableNames['permissions']) + ->onDelete('cascade'); + + $table->primary( + [$pivotPermission, $columnNames['model_morph_key'], 'model_type'], + 'model_has_permissions_permission_model_type_primary', + ); + }); + + Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole): void { + $table->unsignedBigInteger($pivotRole); + + $table->string('model_type'); + $table->uuid($columnNames['model_morph_key']); + $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index'); + + $table->foreign($pivotRole) + ->references('id') + ->on($tableNames['roles']) + ->onDelete('cascade'); + + $table->primary( + [$pivotRole, $columnNames['model_morph_key'], 'model_type'], + 'model_has_roles_role_model_type_primary', + ); + }); + + Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission): void { + $table->unsignedBigInteger($pivotPermission); + $table->unsignedBigInteger($pivotRole); + + $table->foreign($pivotPermission) + ->references('id') + ->on($tableNames['permissions']) + ->onDelete('cascade'); + + $table->foreign($pivotRole) + ->references('id') + ->on($tableNames['roles']) + ->onDelete('cascade'); + + $table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary'); + }); + + resolve(PermissionRegistrar::class)->forgetCachedPermissions(); + } + + public function down(): void + { + $tableNames = config('permission.table_names'); + + throw_if(blank($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.'); + + Schema::drop($tableNames['role_has_permissions']); + Schema::drop($tableNames['model_has_roles']); + Schema::drop($tableNames['model_has_permissions']); + Schema::drop($tableNames['roles']); + Schema::drop($tableNames['permissions']); + } +}; diff --git a/app-modules/identity/database/seeders/RolesSeeder.php b/app-modules/identity/database/seeders/RolesSeeder.php new file mode 100644 index 000000000..0bab7e0ec --- /dev/null +++ b/app-modules/identity/database/seeders/RolesSeeder.php @@ -0,0 +1,22 @@ +forgetCachedPermissions(); + + foreach (UserRole::cases() as $role) { + Role::findOrCreate($role->value, UserRole::GUARD); + } + } +} diff --git a/app-modules/identity/docs/adr/0002-super-admin-via-spatie-permission.md b/app-modules/identity/docs/adr/0002-super-admin-via-spatie-permission.md new file mode 100644 index 000000000..b00ad876c --- /dev/null +++ b/app-modules/identity/docs/adr/0002-super-admin-via-spatie-permission.md @@ -0,0 +1,40 @@ +--- +type: adr +title: 'Super admin como role do spatie/laravel-permission' +module: identity +status: accepted +date: 2026-09-08 +author: danielhe4rt +--- + +# ADR-0002: Super admin como role do spatie/laravel-permission + +## Contexto + +O acesso ao painel `/admin` dependia de uma lista de usernames em `HE4RT_ADMINS_USERNAMES`, +lida por `User::isAdmin()`. Trocar um admin exigia deploy, e o dado ficava fora do banco, +invisível para quem opera o painel. + +## Decisão + +- O pacote `spatie/laravel-permission` passa a ser a única fonte de autorização. +- Existe uma única role, `super-admin` (guard `web`), enumerada em `UserRole`. Nenhuma + permission granular nesta fase: o painel inteiro é super admin ou nada. +- `Gate::before` em `IdentityServiceProvider` libera qualquer ability para quem tem a role e + devolve `null` para os demais, então policies futuras continuam funcionando. +- O papel é atribuído pelo próprio `UserResource` do painel admin. Um admin não altera os + próprios papéis, para não se trancar fora. +- O bootstrap em produção e a recuperação de lockout ficam no comando + `identity:grant-super-admin {username}`. +- Fora de produção o painel continua aberto a qualquer usuário autenticado, como antes. + +## Consequências + +- `model_has_roles.model_id` e `model_has_permissions.model_id` são `uuid`, porque `users.id` + é uuid. A migration vive no módulo identity, não na raiz, e não segue o stub do pacote ao pé + da letra. +- `model_type` grava `user`, por causa do `Relation::morphMap` já existente. +- `config('he4rt.admins')` e `User::isAdmin()` deixam de existir. Testes usam + `User::factory()->superAdmin()`. +- Novas roles entram como case em `UserRole` e no `RolesSeeder`, e aparecem no painel sem + mudança de UI. diff --git a/app-modules/identity/src/Authorization/Console/GrantSuperAdmin.php b/app-modules/identity/src/Authorization/Console/GrantSuperAdmin.php new file mode 100644 index 000000000..896ca7ebf --- /dev/null +++ b/app-modules/identity/src/Authorization/Console/GrantSuperAdmin.php @@ -0,0 +1,43 @@ +argument('username'); + + $user = User::query()->where('username', $username)->first(); + + if ($user === null) { + $this->error(sprintf('Usuário "%s" não encontrado.', $username)); + + return self::FAILURE; + } + + Role::findOrCreate(UserRole::SuperAdmin->value, UserRole::GUARD); + + $user->assignRole(UserRole::SuperAdmin); + + $this->info(sprintf('"%s" agora é %s.', $username, UserRole::SuperAdmin->getLabel())); + + return self::SUCCESS; + } +} diff --git a/app-modules/identity/src/Authorization/Enums/UserRole.php b/app-modules/identity/src/Authorization/Enums/UserRole.php new file mode 100644 index 000000000..02eb63415 --- /dev/null +++ b/app-modules/identity/src/Authorization/Enums/UserRole.php @@ -0,0 +1,60 @@ + 'Super admin', + }; + } + + /** + * @return array + */ + public function getColor(): array + { + return match ($this) { + self::SuperAdmin => Color::Red, + }; + } + + public function getDescription(): string + { + return match ($this) { + self::SuperAdmin => 'Acesso total ao painel admin. Passa por cima de qualquer verificação de permissão.', + }; + } + + public function getIcon(): Heroicon + { + return match ($this) { + self::SuperAdmin => Heroicon::OutlinedShieldCheck, + }; + } +} diff --git a/app-modules/identity/src/IdentityServiceProvider.php b/app-modules/identity/src/IdentityServiceProvider.php index af40eb289..64e6d6a1b 100644 --- a/app-modules/identity/src/IdentityServiceProvider.php +++ b/app-modules/identity/src/IdentityServiceProvider.php @@ -4,8 +4,10 @@ namespace He4rt\Identity; +use He4rt\Identity\Authorization\Console\GrantSuperAdmin; use He4rt\Identity\User\Models\User; use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; class IdentityServiceProvider extends ServiceProvider @@ -17,5 +19,11 @@ public function boot(): void Relation::morphMap([ 'user' => User::class, ]); + + Gate::before(fn (User $user, string $ability): ?bool => $user->isSuperAdmin() ? true : null); + + if ($this->app->runningInConsole()) { + $this->commands([GrantSuperAdmin::class]); + } } } diff --git a/app-modules/identity/src/User/Models/User.php b/app-modules/identity/src/User/Models/User.php index 6326ae2d3..da61c76ec 100644 --- a/app-modules/identity/src/User/Models/User.php +++ b/app-modules/identity/src/User/Models/User.php @@ -11,6 +11,7 @@ use Filament\Panel; use He4rt\Activity\Tracking\Concerns\HasInteractions; use He4rt\Gamification\Character\Models\Character; +use He4rt\Identity\Authorization\Enums\UserRole; use He4rt\Identity\Database\Factories\UserFactory; use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity; use He4rt\Identity\User\Concerns\HasProfileImages; @@ -22,6 +23,7 @@ use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Attributes\UseFactory; use Illuminate\Database\Eloquent\Casts\Attribute; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasOne; @@ -30,6 +32,8 @@ use Illuminate\Notifications\Notifiable; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; +use Spatie\Permission\Models\Role; +use Spatie\Permission\Traits\HasRoles; /** * @property string $id @@ -44,6 +48,7 @@ * @property CarbonInterface|null $created_at * @property CarbonInterface|null $updated_at * @property-read UserSituation $situation + * @property-read Collection $roles */ #[ObservedBy(classes: UserObserver::class)] #[UseFactory(factoryClass: UserFactory::class)] @@ -56,13 +61,14 @@ final class User extends Authenticatable implements FilamentUser, HasMedia, HasN use HasFactory; use HasInteractions; use HasProfileImages; + use HasRoles; use HasUuids; use InteractsWithMedia; use Notifiable; - public function isAdmin(): bool + public function isSuperAdmin(): bool { - return in_array($this->username, str(config('he4rt.admins'))->explode(',')->toArray(), strict: true); + return $this->hasRole(UserRole::SuperAdmin); } /** @@ -102,7 +108,7 @@ public function registerMediaCollections(): void public function canAccessPanel(Panel $panel): bool { return match ($panel->getId()) { - 'admin' => app()->isProduction() ? $this->isAdmin() : true, + 'admin' => app()->isProduction() ? $this->isSuperAdmin() : true, default => true }; } diff --git a/app-modules/identity/tests/Feature/Authorization/GrantSuperAdminCommandTest.php b/app-modules/identity/tests/Feature/Authorization/GrantSuperAdminCommandTest.php new file mode 100644 index 000000000..2dfa35a12 --- /dev/null +++ b/app-modules/identity/tests/Feature/Authorization/GrantSuperAdminCommandTest.php @@ -0,0 +1,31 @@ +create(['username' => 'danielhe4rt']); + + artisan('identity:grant-super-admin', ['username' => 'danielhe4rt']) + ->assertSuccessful(); + + expect($user->fresh()?->hasRole(UserRole::SuperAdmin))->toBeTrue(); +}); + +test('running twice does not duplicate the assignment', function (): void { + User::factory()->create(['username' => 'danielhe4rt']); + + artisan('identity:grant-super-admin', ['username' => 'danielhe4rt'])->assertSuccessful(); + artisan('identity:grant-super-admin', ['username' => 'danielhe4rt'])->assertSuccessful(); + + $this->assertDatabaseCount('model_has_roles', 1); +}); + +test('fails when the username does not exist', function (): void { + artisan('identity:grant-super-admin', ['username' => 'ninguem']) + ->assertFailed(); +}); diff --git a/app-modules/identity/tests/Feature/Authorization/SuperAdminGateTest.php b/app-modules/identity/tests/Feature/Authorization/SuperAdminGateTest.php new file mode 100644 index 000000000..413631898 --- /dev/null +++ b/app-modules/identity/tests/Feature/Authorization/SuperAdminGateTest.php @@ -0,0 +1,19 @@ +superAdmin()->create(); + + expect($user->isSuperAdmin())->toBeTrue() + ->and($user->can('anything-at-all'))->toBeTrue(); +}); + +test('user without role does not pass undefined abilities', function (): void { + $user = User::factory()->create(); + + expect($user->isSuperAdmin())->toBeFalse() + ->and($user->can('anything-at-all'))->toBeFalse(); +}); diff --git a/app-modules/identity/tests/Unit/Authorization/UserRoleTest.php b/app-modules/identity/tests/Unit/Authorization/UserRoleTest.php new file mode 100644 index 000000000..a2d7cedfa --- /dev/null +++ b/app-modules/identity/tests/Unit/Authorization/UserRoleTest.php @@ -0,0 +1,18 @@ +getLabel())->not->toBeEmpty() + ->and($role->getColor())->not->toBeEmpty() + ->and($role->getDescription())->not->toBeEmpty() + ->and($role->getIcon())->toBeInstanceOf(Heroicon::class); +})->with(UserRole::cases()); + +test('super admin is the red apex of the scale', function (): void { + expect(UserRole::SuperAdmin->value)->toBe('super-admin') + ->and(UserRole::GUARD)->toBe('web'); +}); diff --git a/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserForm.php b/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserForm.php index baa8fe26c..127ff2a29 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserForm.php +++ b/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserForm.php @@ -4,10 +4,14 @@ namespace He4rt\PanelAdmin\Filament\Resources\Users\Schemas; +use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; +use He4rt\Identity\Authorization\Enums\UserRole; +use He4rt\Identity\User\Models\User; +use Spatie\Permission\Models\Role; class UserForm { @@ -46,6 +50,37 @@ public static function configure(Schema $schema): Schema ->label('Apoiador') ->helperText('Marca manual de apoiador. Não afeta permissões.'), ]), + + Section::make('Papéis') + ->columnSpanFull() + ->columns(1) + ->description('Quem tem super admin passa por cima de qualquer verificação de permissão.') + ->schema([ + CheckboxList::make('roles') + ->label('Papéis') + ->relationship('roles', 'name') + ->getOptionLabelFromRecordUsing(fn (Role $record): string => UserRole::from($record->name)->getLabel()) + ->descriptions(self::roleDescriptions(...)) + ->disabled(self::isEditingSelf(...)) + ->helperText(fn (?User $record): ?string => self::isEditingSelf($record) ? 'Você não pode alterar os próprios papéis.' : null), + ]), ]); } + + private static function isEditingSelf(?User $record): bool + { + return $record?->is(auth()->user()) ?? false; + } + + /** + * @return array + */ + private static function roleDescriptions(): array + { + return Role::query() + ->where('guard_name', UserRole::GUARD) + ->get() + ->mapWithKeys(fn (Role $role): array => [(int) $role->getKey() => UserRole::from($role->name)->getDescription()]) + ->all(); + } } diff --git a/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserInfolist.php b/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserInfolist.php index ad94bdd71..b9be23416 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserInfolist.php +++ b/app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserInfolist.php @@ -9,6 +9,7 @@ use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; +use He4rt\Identity\Authorization\Enums\UserRole; use He4rt\Identity\User\Enums\UserSituation; use He4rt\Identity\User\Models\User; @@ -39,6 +40,13 @@ public static function configure(Schema $schema): Schema ->label('Apoiador') ->boolean(), + TextEntry::make('roles.name') + ->label('Papéis') + ->badge() + ->formatStateUsing(fn (string $state): string => UserRole::from($state)->getLabel()) + ->color(fn (string $state): array => UserRole::from($state)->getColor()) + ->placeholder('Nenhum'), + TextEntry::make('first_login_at') ->label('Primeiro login') ->dateTime('d/m/Y H:i') diff --git a/app-modules/panel-admin/src/Filament/Resources/Users/Tables/UsersTable.php b/app-modules/panel-admin/src/Filament/Resources/Users/Tables/UsersTable.php index cb1e3b2ed..ca7007c08 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Users/Tables/UsersTable.php +++ b/app-modules/panel-admin/src/Filament/Resources/Users/Tables/UsersTable.php @@ -15,10 +15,12 @@ use Filament\Tables\Filters\SelectFilter; use Filament\Tables\Filters\TernaryFilter; use Filament\Tables\Table; +use He4rt\Identity\Authorization\Enums\UserRole; use He4rt\Identity\User\Enums\UserSituation; use He4rt\Identity\User\Models\User; use He4rt\PanelAdmin\Moderation\Resources\ModerationCaseResource; use Illuminate\Database\Eloquent\Builder; +use Spatie\Permission\Models\Role; class UsersTable { @@ -44,6 +46,13 @@ public static function configure(Table $table): Table ->badge() ->state(fn (User $record): UserSituation => $record->situation), + TextColumn::make('roles.name') + ->label('Papéis') + ->badge() + ->formatStateUsing(fn (string $state): string => UserRole::from($state)->getLabel()) + ->color(fn (string $state): array => UserRole::from($state)->getColor()) + ->placeholder('—'), + TextColumn::make('suspended_until') ->label('Suspenso até') ->dateTime('d/m/Y H:i') @@ -94,6 +103,11 @@ public static function configure(Table $table): Table default => $query, }), + SelectFilter::make('roles') + ->label('Papel') + ->relationship('roles', 'name') + ->getOptionLabelFromRecordUsing(fn (Role $record): string => UserRole::from($record->name)->getLabel()), + TernaryFilter::make('is_donator') ->label('Apoiador'), diff --git a/app-modules/panel-admin/src/Filament/Resources/Users/UserResource.php b/app-modules/panel-admin/src/Filament/Resources/Users/UserResource.php index b20e1cdc4..4a0bc7687 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Users/UserResource.php +++ b/app-modules/panel-admin/src/Filament/Resources/Users/UserResource.php @@ -80,7 +80,7 @@ public static function getEloquentQuery(): Builder // subquery correlacionada (withCount) falha no Postgres por falta de // cast. O eager load compara por valor bindado e funciona. return parent::getEloquentQuery() - ->with(['profile', 'providers']); + ->with(['profile', 'providers', 'roles']); } /** diff --git a/app-modules/panel-admin/tests/Feature/AdminPanelAccessTest.php b/app-modules/panel-admin/tests/Feature/AdminPanelAccessTest.php index 30ccf7e8d..980140679 100644 --- a/app-modules/panel-admin/tests/Feature/AdminPanelAccessTest.php +++ b/app-modules/panel-admin/tests/Feature/AdminPanelAccessTest.php @@ -17,10 +17,8 @@ ->assertOk(); }); -test('authenticated admin can access admin panel', function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); +test('super admin can access admin panel', function (): void { + $user = User::factory()->superAdmin()->create(); $this ->actingAs($user) @@ -28,20 +26,18 @@ ->assertOk(); }); -test('admin user can access panel via canAccessPanel', function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); +test('super admin can access panel via canAccessPanel in production', function (): void { + $user = User::factory()->superAdmin()->create(); - config(['he4rt.admins' => 'danielhe4rt']); + app()->detectEnvironment(fn () => 'production'); $panel = Filament::getPanel('admin'); expect($user->canAccessPanel($panel))->toBeTrue(); }); -test('non-admin user cannot access admin panel in production', function (): void { - $user = User::factory()->create(['username' => 'regular-user']); - - config(['he4rt.admins' => 'danielhe4rt']); +test('user without role cannot access admin panel in production', function (): void { + $user = User::factory()->create(); app()->detectEnvironment(fn () => 'production'); @@ -49,3 +45,11 @@ expect($user->canAccessPanel($panel))->toBeFalse(); }); + +test('user without role can access admin panel outside production', function (): void { + $user = User::factory()->create(); + + $panel = Filament::getPanel('admin'); + + expect($user->canAccessPanel($panel))->toBeTrue(); +}); diff --git a/app-modules/panel-admin/tests/Feature/Albums/AlbumResourceTest.php b/app-modules/panel-admin/tests/Feature/Albums/AlbumResourceTest.php index 7893d0b83..53efaf613 100644 --- a/app-modules/panel-admin/tests/Feature/Albums/AlbumResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Albums/AlbumResourceTest.php @@ -18,14 +18,13 @@ beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); Storage::fake('public'); runMediaConversionsInline(); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); diff --git a/app-modules/panel-admin/tests/Feature/Contents/ContentEntryResourceTest.php b/app-modules/panel-admin/tests/Feature/Contents/ContentEntryResourceTest.php index a8b466efd..50923b13a 100644 --- a/app-modules/panel-admin/tests/Feature/Contents/ContentEntryResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Contents/ContentEntryResourceTest.php @@ -17,11 +17,10 @@ beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); diff --git a/app-modules/panel-admin/tests/Feature/Discord/DiscordClusterSmokeTest.php b/app-modules/panel-admin/tests/Feature/Discord/DiscordClusterSmokeTest.php index bb42ef818..78e26b3a4 100644 --- a/app-modules/panel-admin/tests/Feature/Discord/DiscordClusterSmokeTest.php +++ b/app-modules/panel-admin/tests/Feature/Discord/DiscordClusterSmokeTest.php @@ -30,9 +30,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/Github/GithubRepositoryResourceTest.php b/app-modules/panel-admin/tests/Feature/Github/GithubRepositoryResourceTest.php index b65b42340..76a9a157f 100644 --- a/app-modules/panel-admin/tests/Feature/Github/GithubRepositoryResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Github/GithubRepositoryResourceTest.php @@ -14,9 +14,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/Identity/ExternalIdentityResourceTest.php b/app-modules/panel-admin/tests/Feature/Identity/ExternalIdentityResourceTest.php index 2732bdaf3..895510ffd 100644 --- a/app-modules/panel-admin/tests/Feature/Identity/ExternalIdentityResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Identity/ExternalIdentityResourceTest.php @@ -12,11 +12,10 @@ beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); diff --git a/app-modules/panel-admin/tests/Feature/Identity/UserResourceTest.php b/app-modules/panel-admin/tests/Feature/Identity/UserResourceTest.php index 39e5cf92b..40452ab06 100644 --- a/app-modules/panel-admin/tests/Feature/Identity/UserResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Identity/UserResourceTest.php @@ -3,7 +3,9 @@ declare(strict_types=1); use Filament\Facades\Filament; +use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\TextInput; +use He4rt\Identity\Authorization\Enums\UserRole; use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity; use He4rt\Identity\User\Models\User; use He4rt\PanelAdmin\Filament\Resources\Users\Pages\EditUser; @@ -11,16 +13,16 @@ use He4rt\PanelAdmin\Filament\Resources\Users\RelationManagers\ProvidersRelationManager; use He4rt\PanelAdmin\Filament\Resources\Users\UserResource; use Illuminate\Support\Str; +use Spatie\Permission\Models\Role; use function Pest\Livewire\livewire; beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); @@ -123,3 +125,58 @@ ->assertOk() ->assertCanSeeTableRecords([$identity]); }); + +test('o form expõe os papéis como lista de checkbox', function (): void { + $other = User::factory()->create(); + + livewire(EditUser::class, ['record' => $other->getKey()]) + ->assertSchemaComponentExists('roles', checkComponentUsing: fn (CheckboxList $field): bool => !$field->isDisabled()); +}); + +test('salvar o form concede super admin a outro usuário', function (): void { + $other = User::factory()->create(); + $role = Role::findByName(UserRole::SuperAdmin->value, UserRole::GUARD); + + livewire(EditUser::class, ['record' => $other->getKey()]) + ->fillForm(['roles' => [$role->getKey()]]) + ->call('save') + ->assertHasNoFormErrors(); + + expect($other->fresh()?->hasRole(UserRole::SuperAdmin))->toBeTrue(); +}); + +test('salvar o form sem papéis revoga super admin de outro usuário', function (): void { + $other = User::factory()->superAdmin()->create(); + + livewire(EditUser::class, ['record' => $other->getKey()]) + ->fillForm(['roles' => []]) + ->call('save') + ->assertHasNoFormErrors(); + + expect($other->fresh()?->hasRole(UserRole::SuperAdmin))->toBeFalse(); +}); + +test('o admin não altera os próprios papéis', function (): void { + livewire(EditUser::class, ['record' => $this->admin->getKey()]) + ->assertSchemaComponentExists('roles', checkComponentUsing: fn (CheckboxList $field): bool => $field->isDisabled()) + ->fillForm(['roles' => []]) + ->call('save') + ->assertHasNoFormErrors(); + + expect($this->admin->fresh()?->hasRole(UserRole::SuperAdmin))->toBeTrue(); +}); + +test('a coluna de papéis existe na tabela', function (): void { + livewire(ListUsers::class)->loadTable()->assertTableColumnExists('roles.name'); +}); + +test('o filtro de papel separa super admin de usuário comum', function (): void { + $regular = User::factory()->create(); + $role = Role::findByName(UserRole::SuperAdmin->value, UserRole::GUARD); + + livewire(ListUsers::class) + ->loadTable() + ->filterTable('roles', $role->getKey()) + ->assertCanSeeTableRecords([$this->admin]) + ->assertCanNotSeeTableRecords([$regular]); +}); diff --git a/app-modules/panel-admin/tests/Feature/Marketing/ShortLinkResourceTest.php b/app-modules/panel-admin/tests/Feature/Marketing/ShortLinkResourceTest.php index abb768c0e..db62ee08f 100644 --- a/app-modules/panel-admin/tests/Feature/Marketing/ShortLinkResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Marketing/ShortLinkResourceTest.php @@ -47,11 +47,10 @@ function admin(): User beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->actingAs(User::factory()->create(['username' => 'danielhe4rt'])); + $this->actingAs(User::factory()->superAdmin()->create(['username' => 'danielhe4rt'])); Filament::setCurrentPanel(Filament::getPanel('admin')); }); diff --git a/app-modules/panel-admin/tests/Feature/Moderation/AppealQueueTest.php b/app-modules/panel-admin/tests/Feature/Moderation/AppealQueueTest.php index 43fbe57cb..13755f39c 100644 --- a/app-modules/panel-admin/tests/Feature/Moderation/AppealQueueTest.php +++ b/app-modules/panel-admin/tests/Feature/Moderation/AppealQueueTest.php @@ -12,9 +12,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $this->user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $this->user = User::factory()->superAdmin()->create(); $this->actingAs($this->user); diff --git a/app-modules/panel-admin/tests/Feature/Moderation/ModerationDashboardTest.php b/app-modules/panel-admin/tests/Feature/Moderation/ModerationDashboardTest.php index 85414ce26..9f3ae19cf 100644 --- a/app-modules/panel-admin/tests/Feature/Moderation/ModerationDashboardTest.php +++ b/app-modules/panel-admin/tests/Feature/Moderation/ModerationDashboardTest.php @@ -13,9 +13,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/Moderation/ModerationQueueTest.php b/app-modules/panel-admin/tests/Feature/Moderation/ModerationQueueTest.php index 7cdc6d319..1c5efaa54 100644 --- a/app-modules/panel-admin/tests/Feature/Moderation/ModerationQueueTest.php +++ b/app-modules/panel-admin/tests/Feature/Moderation/ModerationQueueTest.php @@ -10,9 +10,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $this->user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $this->user = User::factory()->superAdmin()->create(); $this->actingAs($this->user); diff --git a/app-modules/panel-admin/tests/Feature/Moderation/TestRuleActionTest.php b/app-modules/panel-admin/tests/Feature/Moderation/TestRuleActionTest.php index 9ee56ea15..787774646 100644 --- a/app-modules/panel-admin/tests/Feature/Moderation/TestRuleActionTest.php +++ b/app-modules/panel-admin/tests/Feature/Moderation/TestRuleActionTest.php @@ -10,9 +10,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/NavigationGroupsTest.php b/app-modules/panel-admin/tests/Feature/NavigationGroupsTest.php index 78d0ce515..e7ecb1b95 100644 --- a/app-modules/panel-admin/tests/Feature/NavigationGroupsTest.php +++ b/app-modules/panel-admin/tests/Feature/NavigationGroupsTest.php @@ -11,9 +11,7 @@ use function Pest\Laravel\actingAs; beforeEach(function (): void { - config(['he4rt.admins' => 'danielhe4rt']); - - actingAs(User::factory()->create(['username' => 'danielhe4rt'])); + actingAs(User::factory()->superAdmin()->create()); Filament::setCurrentPanel(Filament::getPanel('admin')); }); diff --git a/app-modules/panel-admin/tests/Feature/Profile/ProfileResourceTest.php b/app-modules/panel-admin/tests/Feature/Profile/ProfileResourceTest.php index dd67aae7b..e0a446803 100644 --- a/app-modules/panel-admin/tests/Feature/Profile/ProfileResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Profile/ProfileResourceTest.php @@ -20,11 +20,10 @@ beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); diff --git a/app-modules/panel-admin/tests/Feature/Profile/SkillResourceTest.php b/app-modules/panel-admin/tests/Feature/Profile/SkillResourceTest.php index d057914b6..9dffcb92c 100644 --- a/app-modules/panel-admin/tests/Feature/Profile/SkillResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Profile/SkillResourceTest.php @@ -18,11 +18,10 @@ beforeEach(function (): void { config([ - 'he4rt.admins' => 'danielhe4rt', 'app.display_timezone' => 'America/Sao_Paulo', ]); - $this->admin = User::factory()->create(['username' => 'danielhe4rt']); + $this->admin = User::factory()->superAdmin()->create(); $this->actingAs($this->admin); diff --git a/app-modules/panel-admin/tests/Feature/Retrospective/BuildDeckTest.php b/app-modules/panel-admin/tests/Feature/Retrospective/BuildDeckTest.php index 26d4e6151..52cfbe6d0 100644 --- a/app-modules/panel-admin/tests/Feature/Retrospective/BuildDeckTest.php +++ b/app-modules/panel-admin/tests/Feature/Retrospective/BuildDeckTest.php @@ -38,9 +38,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/Retrospective/RetrospectiveResourceTest.php b/app-modules/panel-admin/tests/Feature/Retrospective/RetrospectiveResourceTest.php index d7df87cb9..950032c2c 100644 --- a/app-modules/panel-admin/tests/Feature/Retrospective/RetrospectiveResourceTest.php +++ b/app-modules/panel-admin/tests/Feature/Retrospective/RetrospectiveResourceTest.php @@ -15,9 +15,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/panel-admin/tests/Feature/Twitch/ConnectTwitchActionTest.php b/app-modules/panel-admin/tests/Feature/Twitch/ConnectTwitchActionTest.php index 7d9039f92..fd0e6e7f6 100644 --- a/app-modules/panel-admin/tests/Feature/Twitch/ConnectTwitchActionTest.php +++ b/app-modules/panel-admin/tests/Feature/Twitch/ConnectTwitchActionTest.php @@ -11,9 +11,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $this->user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $this->user = User::factory()->superAdmin()->create(); $this->actingAs($this->user); diff --git a/app-modules/panel-admin/tests/Feature/Twitch/RegisterSubscriptionsActionTest.php b/app-modules/panel-admin/tests/Feature/Twitch/RegisterSubscriptionsActionTest.php index 695d269ad..b74705ede 100644 --- a/app-modules/panel-admin/tests/Feature/Twitch/RegisterSubscriptionsActionTest.php +++ b/app-modules/panel-admin/tests/Feature/Twitch/RegisterSubscriptionsActionTest.php @@ -9,9 +9,7 @@ use function Pest\Livewire\livewire; beforeEach(function (): void { - $user = User::factory()->create(['username' => 'danielhe4rt']); - - config(['he4rt.admins' => 'danielhe4rt']); + $user = User::factory()->superAdmin()->create(); $this->actingAs($user); diff --git a/app-modules/squads/CONTEXT.md b/app-modules/squads/CONTEXT.md index d7d7ae514..5f792b020 100644 --- a/app-modules/squads/CONTEXT.md +++ b/app-modules/squads/CONTEXT.md @@ -8,18 +8,18 @@ flow it actively conducts. ## Glossary -| Term | Definition | Not to be confused with | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| **Squad** | A tenant-scoped crew with a clear objective. Lifecycle `status`: `draft` → `active` → `inactive` → `archived`. Created by a super-admin (the bottom-up proposal/validation happens off-system). | A WhatsApp group (the informal precursor) — the Squad is the formalized record | -| **SquadMember** | A row in the `squad_members` pivot: one person's standing in one squad. Carries `role`, `joined_at`, `left_at`. | A community member generally — this is squad-scoped standing | -| **Role (in squad)** | The `squad_members.role` enum: `Captain` · `SubCaptain` · `Member` · `ExMember`. Confers power on the platform: Captain/Sub manage their own squad. | A governance role (super-admin) — that is platform-wide, config-driven | -| **Captain / SubCaptain** | The squad's leadership. They conduct their own squad on the platform: approve/reject candidacy, promote a sub, mark an `ExMember`. | The Head dos Squads (an off-system human role; in software it is the super-admin) | -| **ExMember** | A person who left (or was removed from) a squad. A role value, not a deletion. Does **not** count toward exclusivity. `left_at` dates the exit. | A `Member` on leave — there is no "paused membership" state | -| **Application (candidatura)** | An APTO person's request to join a squad (`squad_applications`, `pending`/`approved`/`rejected`). The captain decides; approval creates the membership in a transaction. | An onboarding (community/program entry) — that is upstream, in `onboarding` | -| **Exclusivity** | A person may hold at most one _active_ membership (role in `Captain`/`SubCaptain`/`Member`) across all squads. Enforced on join. | A hard unique DB constraint — `ExMember` rows are allowed to pile up | -| **Vacancy** | A squad with no active `Captain`. It is the **absence** of a Captain in the pivot, not a status of its own. | The `inactive` squad status (the whole squad is dormant) | -| **Super-admin** | Platform governance authority, sourced from `config('he4rt.admins')` via `User::isAdmin()`. Creates squads, sets captains, overrides any squad action. Stands in for the "Head/Gestão" roles. | A Captain — a Captain's power is scoped to their own squad | -| **APTO** | The gate this module consumes from `onboarding`: the person completed the `Squads` onboarding. Required to apply or to be in a squad. | An `active` Squad — APTO is about a person, not a squad | +| Term | Definition | Not to be confused with | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- | +| **Squad** | A tenant-scoped crew with a clear objective. Lifecycle `status`: `draft` → `active` → `inactive` → `archived`. Created by a super-admin (the bottom-up proposal/validation happens off-system). | A WhatsApp group (the informal precursor) — the Squad is the formalized record | +| **SquadMember** | A row in the `squad_members` pivot: one person's standing in one squad. Carries `role`, `joined_at`, `left_at`. | A community member generally — this is squad-scoped standing | +| **Role (in squad)** | The `squad_members.role` enum: `Captain` · `SubCaptain` · `Member` · `ExMember`. Confers power on the platform: Captain/Sub manage their own squad. | A governance role (super-admin) — that is platform-wide, config-driven | +| **Captain / SubCaptain** | The squad's leadership. They conduct their own squad on the platform: approve/reject candidacy, promote a sub, mark an `ExMember`. | The Head dos Squads (an off-system human role; in software it is the super-admin) | +| **ExMember** | A person who left (or was removed from) a squad. A role value, not a deletion. Does **not** count toward exclusivity. `left_at` dates the exit. | A `Member` on leave — there is no "paused membership" state | +| **Application (candidatura)** | An APTO person's request to join a squad (`squad_applications`, `pending`/`approved`/`rejected`). The captain decides; approval creates the membership in a transaction. | An onboarding (community/program entry) — that is upstream, in `onboarding` | +| **Exclusivity** | A person may hold at most one _active_ membership (role in `Captain`/`SubCaptain`/`Member`) across all squads. Enforced on join. | A hard unique DB constraint — `ExMember` rows are allowed to pile up | +| **Vacancy** | A squad with no active `Captain`. It is the **absence** of a Captain in the pivot, not a status of its own. | The `inactive` squad status (the whole squad is dormant) | +| **Super-admin** | Platform governance authority, sourced from the `super-admin` role via `User::isSuperAdmin()`. Creates squads, sets captains, overrides any squad action. Stands in for the "Head/Gestão" roles. | A Captain — a Captain's power is scoped to their own squad | +| **APTO** | The gate this module consumes from `onboarding`: the person completed the `Squads` onboarding. Required to apply or to be in a squad. | An `active` Squad — APTO is about a person, not a squad | ## What this module records vs. conducts @@ -74,7 +74,7 @@ src/ ## Dependencies - **Onboarding** — reads the `Squads`-completion gate (APTO). Never the reverse. -- **Identity** — users, tenants, and super-admin authority (`config('he4rt.admins')`). +- **Identity** — users, tenants, and super-admin authority (the `super-admin` role). - Presentation panels depend on this module, never the reverse. See `docs/adr/0001-governanca-como-registro.md`. diff --git a/app/Providers/Tools/TelescopeServiceProvider.php b/app/Providers/Tools/TelescopeServiceProvider.php index b59592bf2..1f6f3f480 100644 --- a/app/Providers/Tools/TelescopeServiceProvider.php +++ b/app/Providers/Tools/TelescopeServiceProvider.php @@ -43,7 +43,7 @@ public function canBoot(): bool */ protected function gate(): void { - Gate::define('viewTelescope', fn (User $user) => $user->isAdmin()); + Gate::define('viewTelescope', fn (User $user) => $user->isSuperAdmin()); } /** diff --git a/composer.json b/composer.json index b47a15c68..ebbcf3c1a 100644 --- a/composer.json +++ b/composer.json @@ -57,6 +57,7 @@ "saloonphp/saloon": "^4.0", "spatie/laravel-backup": "^10.3.1", "spatie/laravel-medialibrary": "^11.23.5", + "spatie/laravel-permission": "^8.3", "symfony/dom-crawler": "^8.1.1", "symfony/yaml": "^8.1.2" }, diff --git a/composer.lock b/composer.lock index 043266ee8..d8ddef772 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c727200d90be2502d5887fe983f97e3c", + "content-hash": "009c5778b3756483a525fc7625f0ad12", "packages": [ { "name": "anourvalar/eloquent-serialize", @@ -3967,10 +3967,11 @@ "dist": { "type": "path", "url": "app-modules/portal", - "reference": "c50d51f0b4816e44c79c5b3a086d5234c95eef9b" + "reference": "e3754724ddb4fac548013cd891231970a6f7204b" }, "require": { - "he4rt/contents": "^1.0.0" + "he4rt/contents": "^1.0.0", + "he4rt/events": "^1.0.0" }, "type": "library", "extra": { @@ -10768,6 +10769,94 @@ ], "time": "2026-05-19T14:06:37+00:00" }, + { + "name": "spatie/laravel-permission", + "version": "8.3.0", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-permission.git", + "reference": "60e8ed5b2fbf043c2264433fc2680c76b8b66aa6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-permission/zipball/60e8ed5b2fbf043c2264433fc2680c76b8b66aa6", + "reference": "60e8ed5b2fbf043c2264433fc2680c76b8b66aa6", + "shasum": "" + }, + "require": { + "illuminate/auth": "^12.0|^13.0", + "illuminate/container": "^12.0|^13.0", + "illuminate/contracts": "^12.0|^13.0", + "illuminate/database": "^12.0|^13.0", + "php": "^8.3", + "spatie/laravel-package-tools": "^1.0" + }, + "require-dev": { + "larastan/larastan": "^3.9", + "laravel/octane": "^2.0", + "laravel/passport": "^13.0", + "laravel/pint": "^1.0", + "orchestra/testbench": "^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0", + "pestphp/pest-plugin-laravel": "^3.0|^4.1", + "phpstan/phpstan": "^2.1" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Spatie\\Permission\\PermissionServiceProvider" + ] + }, + "branch-alias": { + "dev-main": "8.x-dev", + "dev-master": "8.x-dev" + } + }, + "autoload": { + "files": [ + "src/helpers.php" + ], + "psr-4": { + "Spatie\\Permission\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Freek Van der Herten", + "email": "freek@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "Permission handling for Laravel 12 and up", + "homepage": "https://github.com/spatie/laravel-permission", + "keywords": [ + "acl", + "laravel", + "permission", + "permissions", + "rbac", + "roles", + "security", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/laravel-permission/issues", + "source": "https://github.com/spatie/laravel-permission/tree/8.3.0" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2026-07-03T15:36:01+00:00" + }, { "name": "spatie/laravel-signal-aware-command", "version": "2.1.2", diff --git a/config/he4rt.php b/config/he4rt.php index df8674e9b..8edd028ed 100644 --- a/config/he4rt.php +++ b/config/he4rt.php @@ -5,7 +5,6 @@ use Illuminate\Support\Facades\Date; return [ - 'admins' => env('HE4RT_ADMINS_USERNAMES', 'danielhe4rt,kaster'), 'season' => [ 'id' => (int) env('HE4RT_SEASON_ID', 2), 'minimum_level_for_retro' => env('HE4RT_SEASON_MIN_LEVEL', 3), diff --git a/config/permission.php b/config/permission.php new file mode 100644 index 000000000..915d069a4 --- /dev/null +++ b/config/permission.php @@ -0,0 +1,221 @@ + [ + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * Eloquent model should be used to retrieve your permissions. Of course, it + * is often just the "Permission" model but you may use whatever you like. + * + * The model you want to use as a Permission model needs to implement the + * `Spatie\Permission\Contracts\Permission` contract. + */ + + 'permission' => Permission::class, + + /* + * When using the "HasRoles" trait from this package, we need to know which + * Eloquent model should be used to retrieve your roles. Of course, it + * is often just the "Role" model but you may use whatever you like. + * + * The model you want to use as a Role model needs to implement the + * `Spatie\Permission\Contracts\Role` contract. + */ + + 'role' => Role::class, + + /* + * When using the "Teams" feature from this package, we need to know which + * Eloquent model should be used to retrieve your teams. Of course, it + * is often just the "Team" model but you may use whatever you like. + */ + 'team' => null, + + /* + * When using the "HasModels" trait and passing raw IDs to syncModels, + * attachModels, or detachModels, this model class will be used to + * resolve those IDs. If null, defaults to the guard's model. + */ + 'default_model' => null, + ], + + 'table_names' => [ + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'roles' => 'roles', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your permissions. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'permissions' => 'permissions', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your models permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_permissions' => 'model_has_permissions', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your models roles. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_roles' => 'model_has_roles', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'role_has_permissions' => 'role_has_permissions', + ], + + 'column_names' => [ + /* + * Change this if you want to name the related pivots other than defaults + */ + 'role_pivot_key' => null, // default 'role_id', + 'permission_pivot_key' => null, // default 'permission_id', + + /* + * Change this if you want to name the related model primary key other than + * `model_id`. + * + * For example, this would be nice if your primary keys are all UUIDs. In + * that case, name this `model_uuid`. + */ + + 'model_morph_key' => 'model_id', + + /* + * Change this if you want to use the teams feature and your related model's + * foreign key is other than `team_id`. + */ + + 'team_foreign_key' => 'team_id', + ], + + /* + * When set to true, the method for checking permissions will be registered on the gate. + * Set this to false if you want to implement custom logic for checking permissions. + */ + + 'register_permission_check_method' => true, + + /* + * When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered + * this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated + * NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it. + */ + 'register_octane_reset_listener' => false, + + /* + * Events will fire when a role or permission is assigned/unassigned: + * \Spatie\Permission\Events\RoleAttachedEvent + * \Spatie\Permission\Events\RoleDetachedEvent + * \Spatie\Permission\Events\PermissionAttachedEvent + * \Spatie\Permission\Events\PermissionDetachedEvent + * + * To enable, set to true, and then create listeners to watch these events. + */ + 'events_enabled' => false, + + /* + * Teams Feature. + * When set to true the package implements teams using the 'team_foreign_key'. + * If you want the migrations to register the 'team_foreign_key', you must + * set this to true before doing the migration. + * If you already did the migration then you must make a new migration to also + * add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions' + * (view the latest version of this package's migration file) + */ + + 'teams' => false, + + /* + * The class to use to resolve the permissions team id + */ + 'team_resolver' => DefaultTeamResolver::class, + + /* + * Passport Client Credentials Grant + * When set to true the package will use Passports Client to check permissions + */ + + 'use_passport_client_credentials' => false, + + /* + * When set to true, the required permission names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_permission_in_exception' => false, + + /* + * When set to true, the required role names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_role_in_exception' => false, + + /* + * By default wildcard permission lookups are disabled. + * See documentation to understand supported syntax. + */ + + 'enable_wildcard_permission' => false, + + /* + * The class to use for interpreting wildcard permissions. + * If you need to modify delimiters, override the class and specify its name here. + */ + // 'wildcard_permission' => Spatie\Permission\WildcardPermission::class, + + /* Cache-specific settings */ + + 'cache' => [ + + /* + * By default all permissions are cached for 24 hours to speed up performance. + * When permissions or roles are updated the cache is flushed automatically. + */ + + 'expiration_time' => DateInterval::createFromDateString('24 hours'), + + /* + * The cache key used to store all permissions. + */ + + 'key' => 'spatie.permission.cache', + + /* + * You may optionally indicate a specific cache driver to use for permission and + * role caching using any of the `store` drivers listed in the cache.php config + * file. Using 'default' here means to use the `default` set in cache.php. + */ + + 'store' => 'default', + ], +]; diff --git a/database/seeders/BaseSeeder.php b/database/seeders/BaseSeeder.php index 798aaa28a..559000bea 100644 --- a/database/seeders/BaseSeeder.php +++ b/database/seeders/BaseSeeder.php @@ -8,6 +8,8 @@ use He4rt\Community\Meeting\Models\Meeting; use He4rt\Gamification\Character\Models\Character; use He4rt\Gamification\Season\Models\Season; +use He4rt\Identity\Authorization\Enums\UserRole; +use He4rt\Identity\Database\Seeders\RolesSeeder; use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity; use He4rt\Identity\User\Models\User; use Illuminate\Database\Seeder; @@ -17,6 +19,8 @@ class BaseSeeder extends Seeder { public function run(): void { + $this->call(RolesSeeder::class); + $admin = User::factory() ->create([ 'username' => 'danielhe4rt', @@ -25,6 +29,8 @@ public function run(): void 'password' => Hash::make('admin'), ]); + $admin->assignRole(UserRole::SuperAdmin); + Character::factory() ->recycle($admin) ->createOne();