InitializeRoutePermission.php 2.0 KB

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