|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Workbench\App\Http\Middleware; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Http\Request; |
| 7 | +use Illuminate\Support\Facades\Artisan; |
| 8 | +use Illuminate\Support\Facades\Auth; |
| 9 | +use Illuminate\Support\Facades\Cache; |
| 10 | +use Illuminate\Support\Facades\DB; |
| 11 | +use Illuminate\Support\Facades\Hash; |
| 12 | +use Illuminate\Support\Facades\Log; |
| 13 | +use Spatie\Permission\Models\Permission; |
| 14 | +use Spatie\Permission\Models\Role; |
| 15 | +use Spatie\Permission\PermissionRegistrar; |
| 16 | +use Workbench\App\Models\User; |
| 17 | + |
| 18 | +class WorkbenchBootstrap |
| 19 | +{ |
| 20 | + public function handle(Request $request, Closure $next) |
| 21 | + { |
| 22 | + if (config('app.env') === 'local' && ! Auth::guard('web')->check()) { |
| 23 | + $user = User::query()->first(); |
| 24 | + |
| 25 | + if (! $user) { |
| 26 | + try { |
| 27 | + $user = User::query()->firstOrCreate( |
| 28 | + |
| 29 | + [ |
| 30 | + 'name' => 'Admin User', |
| 31 | + 'password' => Hash::make('password'), |
| 32 | + 'email_verified_at' => now(), |
| 33 | + ], |
| 34 | + ); |
| 35 | + } catch (\Throwable $e) { |
| 36 | + Log::error('[Workbench] User creation failed', ['message' => $e->getMessage()]); |
| 37 | + // In case of a race/unique constraint, fetch the existing one |
| 38 | + $user = User:: query()-> where( 'email', '[email protected]')-> first(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if ($user) { |
| 43 | + $this->bootstrapPermissionsAndAssign($user); |
| 44 | + Auth::guard('web')->login($user); |
| 45 | + $request->session()->regenerate(); |
| 46 | + |
| 47 | + if ($request->is('admin/login')) { |
| 48 | + return redirect()->to('/admin'); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return $next($request); |
| 54 | + } |
| 55 | + |
| 56 | + private function bootstrapPermissionsAndAssign(User $user): void |
| 57 | + { |
| 58 | + // Use cache to prevent running this multiple times |
| 59 | + $cacheKey = 'workbench:permissions:bootstrapped'; |
| 60 | + |
| 61 | + if (Cache::has($cacheKey)) { |
| 62 | + // Just ensure user has roles if already bootstrapped |
| 63 | + $this->ensureUserHasRoles($user); |
| 64 | + |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + try { |
| 69 | + // Use lock to prevent concurrent execution |
| 70 | + Cache::lock('workbench:bootstrap-permissions', 30)->block(10, function () use ($user, $cacheKey) { |
| 71 | + // Double-check inside the lock |
| 72 | + if (Cache::has($cacheKey)) { |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + // Normalize guards first |
| 77 | + DB::table('permissions')->whereNull('guard_name')->orWhere('guard_name', '')->update(['guard_name' => 'web']); |
| 78 | + DB::table('roles')->whereNull('guard_name')->orWhere('guard_name', '')->update(['guard_name' => 'web']); |
| 79 | + |
| 80 | + // Generate Filament Shield permissions if none exist yet |
| 81 | + if (Permission::query()->count() === 0) { |
| 82 | + Artisan::call('shield:generate', [ |
| 83 | + '--all' => true, |
| 84 | + '--panel' => 'admin', |
| 85 | + ]); |
| 86 | + } |
| 87 | + |
| 88 | + // Reset caches/registrar to ensure guards are picked up |
| 89 | + Artisan::call('permission:cache-reset'); |
| 90 | + app(PermissionRegistrar::class)->forgetCachedPermissions(); |
| 91 | + |
| 92 | + // Ensure roles with correct guard |
| 93 | + $this->ensureRolesHaveCorrectGuard(); |
| 94 | + |
| 95 | + // Create roles |
| 96 | + $superAdmin = Role::firstOrCreate(['name' => 'super_admin', 'guard_name' => 'web']); |
| 97 | + $panelUser = Role::firstOrCreate(['name' => 'panel_user', 'guard_name' => 'web']); |
| 98 | + |
| 99 | + // Only assign permissions if the role doesn't already have them |
| 100 | + $this->assignPermissionsToRole($superAdmin); |
| 101 | + |
| 102 | + // Assign roles to user |
| 103 | + $this->ensureUserHasRoles($user); |
| 104 | + |
| 105 | + // Mark as bootstrapped (cache for 1 hour) |
| 106 | + Cache::put($cacheKey, true, 3600); |
| 107 | + }); |
| 108 | + } catch (\Throwable $e) { |
| 109 | + Log::error('[Workbench] Bootstrap permissions failed', ['message' => $e->getMessage()]); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private function ensureRolesHaveCorrectGuard(): void |
| 114 | + { |
| 115 | + $existingSuper = Role::where('name', 'super_admin')->first(); |
| 116 | + if ($existingSuper && $existingSuper->guard_name !== 'web') { |
| 117 | + $existingSuper->guard_name = 'web'; |
| 118 | + $existingSuper->save(); |
| 119 | + } |
| 120 | + |
| 121 | + $existingPanel = Role::where('name', 'panel_user')->first(); |
| 122 | + if ($existingPanel && $existingPanel->guard_name !== 'web') { |
| 123 | + $existingPanel->guard_name = 'web'; |
| 124 | + $existingPanel->save(); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + private function assignPermissionsToRole(Role $role): void |
| 129 | + { |
| 130 | + // Check if role already has permissions to avoid duplicate inserts |
| 131 | + if ($role->permissions()->count() > 0) { |
| 132 | + return; |
| 133 | + } |
| 134 | + |
| 135 | + $permissions = Permission::query()->where('guard_name', 'web')->get(); |
| 136 | + if ($permissions->isNotEmpty()) { |
| 137 | + // Use DB transaction to ensure atomicity |
| 138 | + DB::transaction(function () use ($role, $permissions) { |
| 139 | + // Clear existing permissions first to avoid duplicates |
| 140 | + $role->permissions()->detach(); |
| 141 | + |
| 142 | + // Batch insert to avoid individual constraint violations |
| 143 | + $pivotData = $permissions->map(function ($permission) use ($role) { |
| 144 | + return [ |
| 145 | + 'role_id' => $role->id, |
| 146 | + 'permission_id' => $permission->id, |
| 147 | + ]; |
| 148 | + })->toArray(); |
| 149 | + |
| 150 | + // Use insert ignore equivalent for SQLite |
| 151 | + foreach ($pivotData as $data) { |
| 152 | + DB::table('role_has_permissions') |
| 153 | + ->insertOrIgnore($data); |
| 154 | + } |
| 155 | + }); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + private function ensureUserHasRoles(User $user): void |
| 160 | + { |
| 161 | + $superAdmin = Role::where('name', 'super_admin')->where('guard_name', 'web')->first(); |
| 162 | + $panelUser = Role::where('name', 'panel_user')->where('guard_name', 'web')->first(); |
| 163 | + |
| 164 | + $rolesToAssign = collect([$superAdmin, $panelUser]) |
| 165 | + ->filter() |
| 166 | + ->pluck('name') |
| 167 | + ->toArray(); |
| 168 | + |
| 169 | + if (! empty($rolesToAssign)) { |
| 170 | + // Only sync if user doesn't already have these roles |
| 171 | + $existingRoles = $user->roles()->pluck('name')->toArray(); |
| 172 | + $missingRoles = array_diff($rolesToAssign, $existingRoles); |
| 173 | + |
| 174 | + if (! empty($missingRoles)) { |
| 175 | + $user->assignRole($missingRoles); |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | +} |
0 commit comments