Repository navigation
Expand file tree
/
Copy pathINTEGRATION_EXAMPLES.php
More file actions
493 lines (415 loc) · 16.8 KB
/
Copy pathINTEGRATION_EXAMPLES.php
File metadata and controls
493 lines (415 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<?php
/**
* Example Integration Guide for Dynamic Roles Package
*
* This file shows how to integrate the Dynamic Roles package
* into your Laravel application with practical examples.
*/
namespace App\Examples;
use Gunma\DynamicRoles\Facades\DynamicRoles;
use Gunma\DynamicRoles\Services\RolePermissionService;
use Gunma\DynamicRoles\Services\UrlPermissionService;
use Illuminate\Support\Facades\Route;
class DynamicRolesIntegration
{
/**
* Example 1: Basic Setup in AppServiceProvider
*/
public function bootInAppServiceProvider()
{
// In your AppServiceProvider::boot() method
// Register common API routes with permissions
$this->registerApiPermissions();
// Setup role hierarchy
$this->setupRoleHierarchy();
// Auto-discover routes in development
if (app()->environment('local')) {
DynamicRoles::autoDiscoverRoutes();
}
}
/**
* Example 2: Register API Permissions
*/
protected function registerApiPermissions()
{
$apiRoutes = [
// User management
['/api/users', 'GET', ['users.view'], 'List users'],
['/api/users', 'POST', ['users.create'], 'Create user'],
['/api/users/{id}', 'GET', ['users.view'], 'View user'],
['/api/users/{id}', 'PUT', ['users.edit'], 'Update user'],
['/api/users/{id}', 'DELETE', ['users.delete'], 'Delete user'],
// Product management
['/api/products', 'GET', ['products.view'], 'List products'],
['/api/products', 'POST', ['products.create'], 'Create product'],
['/api/products/{id}', 'PUT', ['products.edit'], 'Update product'],
['/api/products/{id}', 'DELETE', ['products.delete'], 'Delete product'],
// Order management
['/api/orders', 'GET', ['orders.view'], 'List orders'],
['/api/orders', 'POST', ['orders.create'], 'Create order'],
['/api/orders/{id}', 'PUT', ['orders.edit'], 'Update order'],
['/api/orders/{id}/cancel', 'POST', ['orders.cancel'], 'Cancel order'],
];
foreach ($apiRoutes as [$url, $method, $permissions, $description]) {
DynamicRoles::registerUrl($url, $method, $permissions, [
'description' => $description,
'category' => 'api',
'auto_discovered' => false,
]);
}
}
/**
* Example 3: Setup Role Hierarchy
*/
protected function setupRoleHierarchy()
{
$rolePermissionService = app(RolePermissionService::class);
$roleHierarchy = [
'super-admin' => [
'users.view', 'users.create', 'users.edit', 'users.delete',
'products.view', 'products.create', 'products.edit', 'products.delete',
'orders.view', 'orders.create', 'orders.edit', 'orders.cancel',
'admin.access', 'reports.view',
],
'admin' => [
'users.view', 'users.create', 'users.edit',
'products.view', 'products.create', 'products.edit',
'orders.view', 'orders.edit',
'admin.access',
],
'manager' => [
'products.view', 'products.edit',
'orders.view', 'orders.edit',
'users.view',
],
'employee' => [
'products.view',
'orders.view',
],
'customer' => [
'products.view',
'orders.view', 'orders.create',
],
];
foreach ($roleHierarchy as $roleName => $permissions) {
// Create role if it doesn't exist
try {
$rolePermissionService->createRole($roleName, $permissions);
} catch (\Exception $e) {
// Role might already exist, just assign permissions
$role = \Spatie\Permission\Models\Role::where('name', $roleName)->first();
if ($role) {
$rolePermissionService->assignPermissionsToRole($role, $permissions);
}
}
}
}
/**
* Example 4: Custom Middleware Usage in Routes
*/
public function registerProtectedRoutes()
{
// In your routes/api.php file
// Basic protection - uses URL-based permissions
Route::middleware(['auth:sanctum', 'dynamic.permission'])->group(function () {
Route::apiResource('users', \App\Http\Controllers\UserController::class);
Route::apiResource('products', \App\Http\Controllers\ProductController::class);
});
// Specific permission requirement
Route::middleware(['auth:sanctum', 'dynamic.permission:admin.access'])
->prefix('admin')
->group(function () {
Route::get('/dashboard', [\App\Http\Controllers\AdminController::class, 'dashboard']);
Route::get('/reports', [\App\Http\Controllers\AdminController::class, 'reports']);
});
// Role-based protection
Route::middleware(['auth:sanctum', 'dynamic.role:admin,manager'])
->group(function () {
Route::get('/management/stats', [\App\Http\Controllers\ManagementController::class, 'stats']);
});
}
/**
* Example 5: Controller Integration
*/
public function controllerExample()
{
// In your controllers, you can check permissions programmatically
class ProductController extends \Illuminate\Routing\Controller
{
protected $urlPermissionService;
public function __construct(UrlPermissionService $urlPermissionService)
{
$this->urlPermissionService = $urlPermissionService;
}
public function index(\Illuminate\Http\Request $request)
{
// Manual permission check
if (!$this->urlPermissionService->checkUrlPermission($request->user(), '/api/products', 'GET')) {
abort(403, 'Insufficient permissions');
}
// Your logic here
return response()->json(['products' => []]);
}
public function store(\Illuminate\Http\Request $request)
{
// The middleware already handles this, but you can add additional checks
$user = $request->user();
// Check if user can create premium products
if ($request->input('is_premium') && !$user->hasPermissionTo('products.create.premium')) {
return response()->json(['error' => 'Cannot create premium products'], 403);
}
// Your logic here
}
}
}
/**
* Example 6: Frontend API Integration (for Next.js)
*/
public function frontendIntegrationExample()
{
/*
// TypeScript interfaces for frontend
interface User {
id: number;
name: string;
email: string;
roles: string[];
permissions: string[];
}
interface PermissionCheck {
url: string;
method: string;
has_permission: boolean;
}
// Permission service for Next.js
class PermissionService {
private apiBase = '/api/dynamic-roles';
async checkPermission(url: string, method: string): Promise<boolean> {
try {
const response = await fetch(`${this.apiBase}/urls/check-permission`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.getToken()}`,
},
body: JSON.stringify({ url, method }),
});
const result = await response.json();
return result.data.has_permission;
} catch (error) {
console.error('Permission check failed:', error);
return false;
}
}
async getUserPermissions(userId: number): Promise<string[]> {
const response = await fetch(`${this.apiBase}/users/${userId}/permissions`, {
headers: {
'Authorization': `Bearer ${this.getToken()}`,
},
});
const result = await response.json();
return result.data.permissions;
}
private getToken(): string {
// Your token retrieval logic
return localStorage.getItem('auth_token') || '';
}
}
// React component example
function ProductManagement() {
const [canEdit, setCanEdit] = useState(false);
const [canDelete, setCanDelete] = useState(false);
const permissionService = new PermissionService();
useEffect(() => {
const checkPermissions = async () => {
const [editPermission, deletePermission] = await Promise.all([
permissionService.checkPermission('/api/products', 'PUT'),
permissionService.checkPermission('/api/products', 'DELETE'),
]);
setCanEdit(editPermission);
setCanDelete(deletePermission);
};
checkPermissions();
}, []);
return (
<div>
<h2>Products</h2>
{canEdit && <button>Edit Product</button>}
{canDelete && <button>Delete Product</button>}
</div>
);
}
*/
}
/**
* Example 7: Database Seeders for Initial Setup
*/
public function seederExample()
{
/*
// Create a seeder: php artisan make:seeder DynamicRolesSeeder
class DynamicRolesSeeder extends \Illuminate\Database\Seeder
{
public function run()
{
$rolePermissionService = app(RolePermissionService::class);
// Create basic permissions
$permissions = [
'users.view', 'users.create', 'users.edit', 'users.delete',
'products.view', 'products.create', 'products.edit', 'products.delete',
'orders.view', 'orders.create', 'orders.edit', 'orders.cancel',
'admin.access', 'reports.view',
];
foreach ($permissions as $permission) {
$rolePermissionService->createPermission($permission);
}
// Create roles with permissions
$rolePermissionService->createRole('super-admin', $permissions);
$rolePermissionService->createRole('admin', array_slice($permissions, 0, -2));
$rolePermissionService->createRole('user', ['products.view', 'orders.view', 'orders.create']);
// Create test users
$superAdmin = \App\Models\User::create([
'name' => 'Super Admin',
'email' => 'superadmin@example.com',
'password' => bcrypt('password'),
]);
$superAdmin->assignRole('super-admin');
$admin = \App\Models\User::create([
'name' => 'Admin User',
'email' => 'admin@example.com',
'password' => bcrypt('password'),
]);
$admin->assignRole('admin');
// Register URLs
DynamicRoles::autoDiscoverRoutes();
}
}
*/
}
/**
* Example 8: Event Listeners for Permission Changes
*/
public function eventListenerExample()
{
/*
// Create event listener for role assignments
class RoleAssignedListener
{
public function handle(\Spatie\Permission\Events\RoleAssigned $event)
{
// Clear user cache when role is assigned
app(\Gunma\DynamicRoles\Services\PermissionCacheService::class)
->clearUserCache($event->model->id);
// Log the change
\Log::info('Role assigned', [
'user_id' => $event->model->id,
'role' => $event->role->name,
]);
// Send notification to user
$event->model->notify(new RoleAssignedNotification($event->role));
}
}
// Register in EventServiceProvider
protected $listen = [
\Spatie\Permission\Events\RoleAssigned::class => [
RoleAssignedListener::class,
],
\Spatie\Permission\Events\PermissionAssigned::class => [
PermissionAssignedListener::class,
],
];
*/
}
/**
* Example 9: Custom Artisan Commands
*/
public function customCommandExample()
{
/*
// Create custom command: php artisan make:command SetupDynamicRoles
class SetupDynamicRoles extends \Illuminate\Console\Command
{
protected $signature = 'app:setup-dynamic-roles
{--environment=production : Environment to setup for}';
protected $description = 'Setup dynamic roles for the application';
public function handle()
{
$env = $this->option('environment');
$this->info("Setting up dynamic roles for {$env} environment...");
// Setup based on environment
if ($env === 'production') {
$this->setupProductionRoles();
} else {
$this->setupDevelopmentRoles();
}
// Auto-discover routes
$this->call('dynamic-roles:sync-permissions', ['--auto-discover' => true]);
$this->info('Dynamic roles setup completed!');
}
private function setupProductionRoles()
{
// Production-specific role setup
$this->info('Setting up production roles...');
// Your logic here
}
private function setupDevelopmentRoles()
{
// Development-specific role setup with test data
$this->info('Setting up development roles...');
// Your logic here
}
}
*/
}
/**
* Example 10: Testing Integration
*/
public function testingExample()
{
/*
// Feature test example
class DynamicRolesTest extends \Tests\TestCase
{
use \Illuminate\Foundation\Testing\RefreshDatabase;
public function test_user_with_permission_can_access_endpoint()
{
$user = \App\Models\User::factory()->create();
$user->givePermissionTo('products.view');
DynamicRoles::registerUrl('/api/products', 'GET', ['products.view']);
$response = $this->actingAs($user)
->getJson('/api/products');
$response->assertStatus(200);
}
public function test_user_without_permission_cannot_access_endpoint()
{
$user = \App\Models\User::factory()->create();
DynamicRoles::registerUrl('/api/admin', 'GET', ['admin.access']);
$response = $this->actingAs($user)
->getJson('/api/admin');
$response->assertStatus(403);
}
public function test_api_endpoints_work_correctly()
{
$admin = \App\Models\User::factory()->create();
$admin->assignRole('super-admin');
// Test create URL endpoint
$response = $this->actingAs($admin)
->postJson('/api/dynamic-roles/urls', [
'url' => '/api/test',
'method' => 'GET',
'permissions' => ['test.view'],
]);
$response->assertStatus(201);
// Test permission check endpoint
$response = $this->actingAs($admin)
->postJson('/api/dynamic-roles/urls/check-permission', [
'url' => '/api/test',
'method' => 'GET',
]);
$response->assertStatus(200)
->assertJsonPath('data.has_permission', true);
}
}
*/
}
}