12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- namespace App\Console\Commands;
- use App\Models\Permission;
- use App\Models\PermissionGroup;
- use App\Models\Role;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\Route;
- use Illuminate\Support\Str;
- class InitializeRoutePermission extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'lpc:initialize-route-permission';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'Initialize routing permissions';
- /**
- * Execute the console command.
- */
- public function handle()
- {
- $routes = Route::getRoutes();
- foreach ($routes as $route) {
- if (! $route->getName()) {
- continue;
- }
- if (!in_array('auth:sanctum', $route->middleware())) {
- continue;
- }
- $routeName = $route->getName();
- $groupName = explode('.', $routeName)[0] ?? 'default';
- $groupName = Str::of($groupName)->replace('-', ' ')->studly()->value();
- $groupMap[$groupName] = PermissionGroup::query()->firstOrCreate([
- 'name' => $groupName
- ]);
- $permissionGroup = $groupMap[$groupName];
- Permission::query()->firstOrCreate([
- 'name' => $route->getName(),
- 'guard_name' => 'api',
- ], [
- 'description' => $route->getName(),
- 'permission_group_id' => $permissionGroup->id,
- ]);
- }
- $superAdminRoleId = config("auth.super_admin_role_id");
- $superAdminRole = [
- 'id' => $superAdminRoleId,
- 'name' => 'admin',
- 'guard_name' => 'api',
- 'description' => '管理员权限'
- ];
- $role = Role::query()->firstOrCreate(['id' => $superAdminRoleId], $superAdminRole);
- $role?->syncPermissions(Permission::query()->pluck("name")->toArray());
- }
- }
|