RestrictionService.php
17.1 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
<?php namespace BookStack\Services;
use BookStack\Book;
use BookStack\Chapter;
use BookStack\Entity;
use BookStack\EntityPermission;
use BookStack\Page;
use BookStack\Role;
use BookStack\User;
use Illuminate\Database\Eloquent\Collection;
class RestrictionService
{
protected $userRoles;
protected $isAdmin;
protected $currentAction;
protected $currentUser;
public $book;
public $chapter;
public $page;
protected $entityPermission;
protected $role;
/**
* RestrictionService constructor.
* @param EntityPermission $entityPermission
* @param Book $book
* @param Chapter $chapter
* @param Page $page
* @param Role $role
*/
public function __construct(EntityPermission $entityPermission, Book $book, Chapter $chapter, Page $page, Role $role)
{
$this->currentUser = auth()->user();
if ($this->currentUser === null) $this->currentUser = new User(['id' => 0]);
$this->userRoles = $this->currentUser ? $this->currentUser->roles->pluck('id') : [];
$this->isAdmin = $this->currentUser ? $this->currentUser->hasRole('admin') : false;
$this->entityPermission = $entityPermission;
$this->role = $role;
$this->book = $book;
$this->chapter = $chapter;
$this->page = $page;
}
/**
* Re-generate all entity permission from scratch.
*/
public function buildEntityPermissions()
{
$this->entityPermission->truncate();
// Get all roles (Should be the most limited dimension)
$roles = $this->role->load('permissions')->all();
// Chunk through all books
$this->book->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
// Chunk through all chapters
$this->chapter->with('book')->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
// Chunk through all pages
$this->page->with('book', 'chapter')->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
}
/**
* Create the entity permissions for a particular entity.
* @param Entity $entity
*/
public function buildEntityPermissionsForEntity(Entity $entity)
{
$roles = $this->role->load('permissions')->all();
$entities = collect([$entity]);
if ($entity->isA('book')) {
$entities = $entities->merge($entity->chapters);
$entities = $entities->merge($entity->pages);
} elseif ($entity->isA('chapter')) {
$entities = $entities->merge($entity->pages);
}
$this->deleteManyEntityPermissionsForEntities($entities);
$this->createManyEntityPermissions($entities, $roles);
}
/**
* Build the entity permissions for a particular role.
* @param Role $role
*/
public function buildEntityPermissionForRole(Role $role)
{
$roles = collect([$role]);
$this->deleteManyEntityPermissionsForRoles($roles);
// Chunk through all books
$this->book->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
// Chunk through all chapters
$this->chapter->with('book')->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
// Chunk through all pages
$this->page->with('book', 'chapter')->chunk(500, function ($books) use ($roles) {
$this->createManyEntityPermissions($books, $roles);
});
}
/**
* Delete the entity permissions attached to a particular role.
* @param Role $role
*/
public function deleteEntityPermissionsForRole(Role $role)
{
$this->deleteManyEntityPermissionsForRoles([$role]);
}
/**
* Delete all of the entity permissions for a list of entities.
* @param Role[] $roles
*/
protected function deleteManyEntityPermissionsForRoles($roles)
{
foreach ($roles as $role) {
$role->entityPermissions()->delete();
}
}
/**
* Delete the entity permissions for a particular entity.
* @param Entity $entity
*/
public function deleteEntityPermissionsForEntity(Entity $entity)
{
$this->deleteManyEntityPermissionsForEntities([$entity]);
}
/**
* Delete all of the entity permissions for a list of entities.
* @param Entity[] $entities
*/
protected function deleteManyEntityPermissionsForEntities($entities)
{
foreach ($entities as $entity) {
$entity->permissions()->delete();
}
}
/**
* Create & Save entity permissions for many entities and permissions.
* @param Collection $entities
* @param Collection $roles
*/
protected function createManyEntityPermissions($entities, $roles)
{
$entityPermissions = [];
foreach ($entities as $entity) {
foreach ($roles as $role) {
foreach ($this->getActions($entity) as $action) {
$entityPermissions[] = $this->createEntityPermissionData($entity, $role, $action);
}
}
}
$this->entityPermission->insert($entityPermissions);
}
/**
* Get the actions related to an entity.
* @param $entity
* @return array
*/
protected function getActions($entity)
{
$baseActions = ['view', 'update', 'delete'];
if ($entity->isA('chapter')) {
$baseActions[] = 'page-create';
} else if ($entity->isA('book')) {
$baseActions[] = 'page-create';
$baseActions[] = 'chapter-create';
}
return $baseActions;
}
/**
* Create entity permission data for an entity and role
* for a particular action.
* @param Entity $entity
* @param Role $role
* @param $action
* @return array
*/
protected function createEntityPermissionData(Entity $entity, Role $role, $action)
{
$permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
$roleHasPermission = $role->hasPermission($permissionPrefix . '-all');
$roleHasPermissionOwn = $role->hasPermission($permissionPrefix . '-own');
$explodedAction = explode('-', $action);
$restrictionAction = end($explodedAction);
if ($entity->isA('book')) {
if (!$entity->restricted) {
return $this->createEntityPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
} else {
$hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
return $this->createEntityPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
} elseif ($entity->isA('chapter')) {
if (!$entity->restricted) {
$hasExplicitAccessToBook = $entity->book->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToBook = !$entity->book->restricted;
return $this->createEntityPermissionDataArray($entity, $role, $action,
($hasExplicitAccessToBook || ($roleHasPermission && $hasPermissiveAccessToBook)),
($hasExplicitAccessToBook || ($roleHasPermissionOwn && $hasPermissiveAccessToBook)));
} else {
$hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
return $this->createEntityPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
} elseif ($entity->isA('page')) {
if (!$entity->restricted) {
$hasExplicitAccessToBook = $entity->book->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToBook = !$entity->book->restricted;
$hasExplicitAccessToChapter = $entity->chapter && $entity->chapter->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToChapter = $entity->chapter && !$entity->chapter->restricted;
$acknowledgeChapter = ($entity->chapter && $entity->chapter->restricted);
$hasExplicitAccessToParents = $acknowledgeChapter ? $hasExplicitAccessToChapter : $hasExplicitAccessToBook;
$hasPermissiveAccessToParents = $acknowledgeChapter ? $hasPermissiveAccessToChapter : $hasPermissiveAccessToBook;
return $this->createEntityPermissionDataArray($entity, $role, $action,
($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
);
} else {
$hasAccess = $entity->hasRestriction($role->id, $action);
return $this->createEntityPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
}
}
/**
* Create an array of data with the information of an entity permissions.
* Used to build data for bulk insertion.
* @param Entity $entity
* @param Role $role
* @param $action
* @param $permissionAll
* @param $permissionOwn
* @return array
*/
protected function createEntityPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
{
$entityClass = get_class($entity);
return [
'role_id' => $role->id,
'entity_id' => $entity->id,
'entity_type' => $entityClass,
'action' => $action,
'has_permission' => $permissionAll,
'has_permission_own' => $permissionOwn,
'created_by' => $entity->created_by
];
}
/**
* Checks if an entity has a restriction set upon it.
* @param Entity $entity
* @param $permission
* @return bool
*/
public function checkEntityUserAccess(Entity $entity, $permission)
{
if ($this->isAdmin) return true;
$explodedPermission = explode('-', $permission);
$baseQuery = $entity->where('id', '=', $entity->id);
$action = end($explodedPermission);
$this->currentAction = $action;
$nonEntityPermissions = ['restrictions'];
// Handle non entity specific permissions
if (in_array($explodedPermission[0], $nonEntityPermissions)) {
$allPermission = $this->currentUser && $this->currentUser->can($permission . '-all');
$ownPermission = $this->currentUser && $this->currentUser->can($permission . '-own');
$this->currentAction = 'view';
$isOwner = $this->currentUser && $this->currentUser->id === $entity->created_by;
return ($allPermission || ($isOwner && $ownPermission));
}
// Handle abnormal create permissions
if ($action === 'create') {
$this->currentAction = $permission;
}
return $this->entityRestrictionQuery($baseQuery)->count() > 0;
}
/**
* Check if an entity has restrictions set on itself or its
* parent tree.
* @param Entity $entity
* @param $action
* @return bool|mixed
*/
public function checkIfRestrictionsSet(Entity $entity, $action)
{
$this->currentAction = $action;
if ($entity->isA('page')) {
return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
} elseif ($entity->isA('chapter')) {
return $entity->restricted || $entity->book->restricted;
} elseif ($entity->isA('book')) {
return $entity->restricted;
}
}
/**
* The general query filter to remove all entities
* that the current user does not have access to.
* @param $query
* @return mixed
*/
protected function entityRestrictionQuery($query)
{
return $query->where(function ($parentQuery) {
$parentQuery->whereHas('permissions', function ($permissionQuery) {
$permissionQuery->whereIn('role_id', $this->userRoles)
->where('action', '=', $this->currentAction)
->where(function ($query) {
$query->where('has_permission', '=', true)
->orWhere(function ($query) {
$query->where('has_permission_own', '=', true)
->where('created_by', '=', $this->currentUser->id);
});
});
});
});
}
/**
* Add restrictions for a page query
* @param $query
* @param string $action
* @return mixed
*/
public function enforcePageRestrictions($query, $action = 'view')
{
// Prevent drafts being visible to others.
$query = $query->where(function ($query) {
$query->where('draft', '=', false);
if ($this->currentUser) {
$query->orWhere(function ($query) {
$query->where('draft', '=', true)->where('created_by', '=', $this->currentUser->id);
});
}
});
if ($this->isAdmin) return $query;
$this->currentAction = $action;
return $this->entityRestrictionQuery($query);
}
/**
* Add on permission restrictions to a chapter query.
* @param $query
* @param string $action
* @return mixed
*/
public function enforceChapterRestrictions($query, $action = 'view')
{
if ($this->isAdmin) return $query;
$this->currentAction = $action;
return $this->entityRestrictionQuery($query);
}
/**
* Add restrictions to a book query.
* @param $query
* @param string $action
* @return mixed
*/
public function enforceBookRestrictions($query, $action = 'view')
{
if ($this->isAdmin) return $query;
$this->currentAction = $action;
return $this->entityRestrictionQuery($query);
}
/**
* Filter items that have entities set a a polymorphic relation.
* @param $query
* @param string $tableName
* @param string $entityIdColumn
* @param string $entityTypeColumn
* @return mixed
*/
public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn)
{
if ($this->isAdmin) return $query;
$this->currentAction = 'view';
$tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
return $query->where(function ($query) use ($tableDetails) {
$query->whereExists(function ($permissionQuery) use (&$tableDetails) {
$permissionQuery->select('id')->from('entity_permissions')
->whereRaw('entity_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
->whereRaw('entity_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
->where('action', '=', $this->currentAction)
->whereIn('role_id', $this->userRoles)
->where(function ($query) {
$query->where('has_permission', '=', true)->orWhere(function ($query) {
$query->where('has_permission_own', '=', true)
->where('created_by', '=', $this->currentUser->id);
});
});
});
});
}
/**
* Filters pages that are a direct relation to another item.
* @param $query
* @param $tableName
* @param $entityIdColumn
* @return mixed
*/
public function filterRelatedPages($query, $tableName, $entityIdColumn)
{
if ($this->isAdmin) return $query;
$this->currentAction = 'view';
$tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
return $query->where(function ($query) use ($tableDetails) {
$query->where(function ($query) use (&$tableDetails) {
$query->whereExists(function ($permissionQuery) use (&$tableDetails) {
$permissionQuery->select('id')->from('entity_permissions')
->whereRaw('entity_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
->where('entity_type', '=', 'Bookstack\\Page')
->where('action', '=', $this->currentAction)
->whereIn('role_id', $this->userRoles)
->where(function ($query) {
$query->where('has_permission', '=', true)->orWhere(function ($query) {
$query->where('has_permission_own', '=', true)
->where('created_by', '=', $this->currentUser->id);
});
});
});
})->orWhere($tableDetails['entityIdColumn'], '=', 0);
});
}
}