InitializeRoutePermission.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Permission;
  4. use App\Models\PermissionGroup;
  5. use App\Models\Role;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\Route;
  8. class InitializeRoutePermission extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'lpc:initialize-route-permission';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'Initialize routing permissions';
  22. /**
  23. * Execute the console command.
  24. */
  25. public function handle()
  26. {
  27. $routes = Route::getRoutes();
  28. $permissionGroup = PermissionGroup::query()->firstOrCreate([
  29. 'name' => 'default',
  30. ]);
  31. foreach ($routes as $route) {
  32. if (! $route->getName()) {
  33. continue;
  34. }
  35. if (!in_array('auth:sanctum', $route->middleware())) {
  36. continue;
  37. }
  38. Permission::query()->firstOrCreate([
  39. 'name' => $route->getName(),
  40. 'guard_name' => 'api',
  41. ], [
  42. 'description' => $route->getName(),
  43. 'permission_group_id' => $permissionGroup->id,
  44. ]);
  45. }
  46. $superAdminRoleId = config("auth.super_admin_role_id");
  47. $superAdminRole = [
  48. 'id' => $superAdminRoleId,
  49. 'name' => 'admin',
  50. 'guard_name' => 'api',
  51. 'description' => '管理员权限'
  52. ];
  53. $role = Role::query()->firstOrCreate(['id' => $superAdminRoleId], $superAdminRole);
  54. $role?->syncPermissions(Permission::query()->pluck("name")->toArray());
  55. }
  56. }