Skip to content

feat(identity): super admin como role do spatie/laravel-permission - #555

Merged
danielhe4rt merged 1 commit into
4.xfrom
feat/single-rbac
Sep 8, 2026
Merged

danielhe4rt merged 1 commit into
4.xfrom
feat/single-rbac

Conversation

@danielhe4rt

Copy link
Copy Markdown
Contributor

Contexto

Hoje quem entra no /admin é decidido por uma lista de usernames no .env (HE4RT_ADMINS_USERNAMES). Pra dar acesso pra alguém novo, tem que fazer deploy. Pra tirar, também. E o dado fica invisível pra quem opera o painel.

Esse PR troca a flag pelo spatie/laravel-permission com uma única role: super-admin. Nada de permissão granular por enquanto. Ou você é super admin e vê tudo, ou não entra. O papel é atribuído dentro do próprio painel, na edição do usuário.

Se liga no fluxo:

  [login OAuth] ──► canAccessPanel('admin')
                        │
                        ├─ env != production ──────────────────► [acesso liberado]
                        │
                        └─ env == production ──► hasRole('super-admin')?
                                                     ├─ sim ──► [acesso liberado]
                                                     └─ não ──► [403]

Fora de produção o painel continua aberto pra qualquer usuário logado, igual era antes.

Alterações

  • identity: enum UserRole (case SuperAdmin, contratos Filament), trait HasRoles no User, isAdmin() vira isSuperAdmin(), Gate::before no IdentityServiceProvider liberando qualquer ability pra super admin e devolvendo null pros demais.
  • identity: migration das tabelas do Spatie dentro do módulo, com model_id em uuid (porque users.id é uuid) e timestamps Tz.
  • identity: comando identity:grant-super-admin {username} pra bootstrap em produção e saída de lockout. RolesSeeder e state User::factory()->superAdmin().
  • panel-admin: seção "Papéis" no form do UserResource com CheckboxList na relação, coluna e filtro de papel na tabela, badge no infolist. O admin não consegue mexer nos próprios papéis, pra ninguém se trancar fora.
  • Flag removida: config('he4rt.admins'), HE4RT_ADMINS_USERNAMES do .env/.env.example, referências no CONTEXT.md de squads. Telescope passa a usar isSuperAdmin().
  • Testes: 23 arquivos migrados pro factory state, AdminPanelAccessTest reescrito, 4 arquivos novos (enum, gate, comando, resource).
  • Docs: ADR 0002 no módulo identity.

Plano de Testes

  • vendor/bin/pint e vendor/bin/phpstan analyse limpos
  • pest --parallel app-modules/panel-admin/tests (232 passando)
  • pest --parallel app-modules/events/tests (155 passando)
  • pest --parallel app-modules/identity/tests (94 passando)
  • pest --parallel tests/Unit (6 passando)
  • php artisan migrate + identity:grant-super-admin danielhe4rt no ambiente local

Rollout em produção

php artisan migrate --force
php artisan identity:grant-super-admin danielhe4rt
php artisan identity:grant-super-admin kaster

Depois disso, remover HE4RT_ADMINS_USERNAMES do env. A janela entre o migrate e o primeiro grant é o único momento em que ninguém entra no /admin.


Evidências

Sem print por enquanto. A mudança visual é a seção "Papéis" na edição de usuário e a coluna/filtro de papel na listagem.

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()
@danielhe4rt
danielhe4rt requested a review from a team September 8, 2026 03:06
@danielhe4rt
danielhe4rt merged commit b16c74c into 4.x Sep 8, 2026
9 of 10 checks passed
@danielhe4rt
danielhe4rt deleted the feat/single-rbac branch September 8, 2026 03:17
@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Team

Run ID: 72a3ec39-41f6-4c57-afda-39796edd3e83

📥 Commits

Reviewing files that changed from the base of the PR and between bd302e7 and 9e8e919.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (41)
  • app-modules/events/tests/Feature/EventResourceTest.php
  • app-modules/identity/database/factories/UserFactory.php
  • app-modules/identity/database/migrations/2026_09_08_025342_create_permission_tables.php
  • app-modules/identity/database/seeders/RolesSeeder.php
  • app-modules/identity/docs/adr/0002-super-admin-via-spatie-permission.md
  • app-modules/identity/src/Authorization/Console/GrantSuperAdmin.php
  • app-modules/identity/src/Authorization/Enums/UserRole.php
  • app-modules/identity/src/IdentityServiceProvider.php
  • app-modules/identity/src/User/Models/User.php
  • app-modules/identity/tests/Feature/Authorization/GrantSuperAdminCommandTest.php
  • app-modules/identity/tests/Feature/Authorization/SuperAdminGateTest.php
  • app-modules/identity/tests/Unit/Authorization/UserRoleTest.php
  • app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserForm.php
  • app-modules/panel-admin/src/Filament/Resources/Users/Schemas/UserInfolist.php
  • app-modules/panel-admin/src/Filament/Resources/Users/Tables/UsersTable.php
  • app-modules/panel-admin/src/Filament/Resources/Users/UserResource.php
  • app-modules/panel-admin/tests/Feature/AdminPanelAccessTest.php
  • app-modules/panel-admin/tests/Feature/Albums/AlbumResourceTest.php
  • app-modules/panel-admin/tests/Feature/Contents/ContentEntryResourceTest.php
  • app-modules/panel-admin/tests/Feature/Discord/DiscordClusterSmokeTest.php
  • app-modules/panel-admin/tests/Feature/Github/GithubRepositoryResourceTest.php
  • app-modules/panel-admin/tests/Feature/Identity/ExternalIdentityResourceTest.php
  • app-modules/panel-admin/tests/Feature/Identity/UserResourceTest.php
  • app-modules/panel-admin/tests/Feature/Marketing/ShortLinkResourceTest.php
  • app-modules/panel-admin/tests/Feature/Moderation/AppealQueueTest.php
  • app-modules/panel-admin/tests/Feature/Moderation/ModerationDashboardTest.php
  • app-modules/panel-admin/tests/Feature/Moderation/ModerationQueueTest.php
  • app-modules/panel-admin/tests/Feature/Moderation/TestRuleActionTest.php
  • app-modules/panel-admin/tests/Feature/NavigationGroupsTest.php
  • app-modules/panel-admin/tests/Feature/Profile/ProfileResourceTest.php
  • app-modules/panel-admin/tests/Feature/Profile/SkillResourceTest.php
  • app-modules/panel-admin/tests/Feature/Retrospective/BuildDeckTest.php
  • app-modules/panel-admin/tests/Feature/Retrospective/RetrospectiveResourceTest.php
  • app-modules/panel-admin/tests/Feature/Twitch/ConnectTwitchActionTest.php
  • app-modules/panel-admin/tests/Feature/Twitch/RegisterSubscriptionsActionTest.php
  • app-modules/squads/CONTEXT.md
  • app/Providers/Tools/TelescopeServiceProvider.php
  • composer.json
  • config/he4rt.php
  • config/permission.php
  • database/seeders/BaseSeeder.php

📝 Walkthrough

Walkthrough

The change replaces username-based admin detection with Spatie’s super-admin role. It adds permission configuration, migrations, role seeding, factory support, a grant command, and a global gate override. The user resource can assign and display roles while preventing self-role changes. Existing admin-panel tests now use the role-based factory state, and authorization tests cover access, assignment, revocation, and command behavior.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants