use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Facades\DB;
+/**
+ * Joint permissions provide a pre-query "cached" table of view permissions for all core entity
+ * types for all roles in the system. This class generates out that table for different scenarios.
+ */
class JointPermissionBuilder
{
/**
- * @var array<string, array<int, Entity>>
+ * @var array<string, array<int, SimpleEntityData>>
*/
- protected $entityCache;
+ protected array $entityCache;
/**
- * Prepare the local entity cache and ensure it's empty.
- *
- * @param Entity[] $entities
+ * Re-generate all entity permission from scratch.
*/
- protected function readyEntityCache(array $entities = [])
+ public function rebuildForAll()
{
- $this->entityCache = [];
+ JointPermission::query()->truncate();
- foreach ($entities as $entity) {
- $class = get_class($entity);
+ // Get all roles (Should be the most limited dimension)
+ $roles = Role::query()->with('permissions')->get()->all();
- if (!isset($this->entityCache[$class])) {
- $this->entityCache[$class] = [];
- }
+ // Chunk through all books
+ $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
+ $this->buildJointPermissionsForBooks($books, $roles);
+ });
- $this->entityCache[$class][$entity->getRawAttribute('id')] = $entity;
- }
+ // Chunk through all bookshelves
+ Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
+ ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
+ $this->createManyJointPermissions($shelves->all(), $roles);
+ });
}
/**
- * Get a book via ID, Checks local cache.
+ * Rebuild the entity jointPermissions for a particular entity.
*/
- protected function getBook(int $bookId): ?Book
+ public function rebuildForEntity(Entity $entity)
{
- if ($this->entityCache[Book::class][$bookId] ?? false) {
- return $this->entityCache[Book::class][$bookId];
+ $entities = [$entity];
+ if ($entity instanceof Book) {
+ $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
+ $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
+
+ return;
}
- return Book::query()->withTrashed()->find($bookId);
- }
+ /** @var BookChild $entity */
+ if ($entity->book) {
+ $entities[] = $entity->book;
+ }
- /**
- * Get a chapter via ID, Checks local cache.
- */
- protected function getChapter(int $chapterId): ?Chapter
- {
- if ($this->entityCache[Chapter::class][$chapterId] ?? false) {
- return $this->entityCache[Chapter::class][$chapterId];
+ if ($entity instanceof Page && $entity->chapter_id) {
+ $entities[] = $entity->chapter;
}
- return Chapter::query()
- ->withTrashed()
- ->find($chapterId);
+ if ($entity instanceof Chapter) {
+ foreach ($entity->pages as $page) {
+ $entities[] = $page;
+ }
+ }
+
+ $this->buildJointPermissionsForEntities($entities);
}
/**
- * Re-generate all entity permission from scratch.
+ * Build the entity jointPermissions for a particular role.
*/
- public function buildJointPermissions()
+ public function rebuildForRole(Role $role)
{
- JointPermission::query()->truncate();
- $this->readyEntityCache();
-
- // Get all roles (Should be the most limited dimension)
- $roles = Role::query()->with('permissions')->get()->all();
+ $roles = [$role];
+ $role->jointPermissions()->delete();
+ $role->load('permissions');
// Chunk through all books
- $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
+ $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
$this->buildJointPermissionsForBooks($books, $roles);
});
// Chunk through all bookshelves
- Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by'])
- ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
- $this->buildJointPermissionsForShelves($shelves, $roles);
+ Bookshelf::query()->select(['id', 'owned_by'])
+ ->chunk(50, function ($shelves) use ($roles) {
+ $this->createManyJointPermissions($shelves->all(), $roles);
});
}
/**
- * Get a query for fetching a book with it's children.
+ * Prepare the local entity cache and ensure it's empty.
+ *
+ * @param SimpleEntityData[] $entities
+ */
+ protected function readyEntityCache(array $entities)
+ {
+ $this->entityCache = [];
+
+ foreach ($entities as $entity) {
+ if (!isset($this->entityCache[$entity->type])) {
+ $this->entityCache[$entity->type] = [];
+ }
+
+ $this->entityCache[$entity->type][$entity->id] = $entity;
+ }
+ }
+
+ /**
+ * Get a book via ID, Checks local cache.
+ */
+ protected function getBook(int $bookId): SimpleEntityData
+ {
+ return $this->entityCache['book'][$bookId];
+ }
+
+ /**
+ * Get a chapter via ID, Checks local cache.
+ */
+ protected function getChapter(int $chapterId): SimpleEntityData
+ {
+ return $this->entityCache['chapter'][$chapterId];
+ }
+
+ /**
+ * Get a query for fetching a book with its children.
*/
protected function bookFetchQuery(): Builder
{
return Book::query()->withTrashed()
- ->select(['id', 'restricted', 'owned_by'])->with([
+ ->select(['id', 'owned_by'])->with([
'chapters' => function ($query) {
- $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
+ $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
},
'pages' => function ($query) {
- $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
+ $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
},
]);
}
- /**
- * Build joint permissions for the given shelf and role combinations.
- *
- * @throws Throwable
- */
- protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false)
- {
- if ($deleteOld) {
- $this->deleteManyJointPermissionsForEntities($shelves->all());
- }
- $this->createManyJointPermissions($shelves->all(), $roles);
- }
-
/**
* Build joint permissions for the given book and role combinations.
- *
- * @throws Throwable
*/
protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
{
$this->createManyJointPermissions($entities->all(), $roles);
}
- /**
- * Rebuild the entity jointPermissions for a particular entity.
- *
- * @throws Throwable
- */
- public function buildJointPermissionsForEntity(Entity $entity)
- {
- $entities = [$entity];
- if ($entity instanceof Book) {
- $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
- $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
-
- return;
- }
-
- /** @var BookChild $entity */
- if ($entity->book) {
- $entities[] = $entity->book;
- }
-
- if ($entity instanceof Page && $entity->chapter_id) {
- $entities[] = $entity->chapter;
- }
-
- if ($entity instanceof Chapter) {
- foreach ($entity->pages as $page) {
- $entities[] = $page;
- }
- }
-
- $this->buildJointPermissionsForEntities($entities);
- }
-
/**
* Rebuild the entity jointPermissions for a collection of entities.
- *
- * @throws Throwable
*/
protected function buildJointPermissionsForEntities(array $entities)
{
$this->createManyJointPermissions($entities, $roles);
}
- /**
- * Build the entity jointPermissions for a particular role.
- */
- public function buildJointPermissionForRole(Role $role)
- {
- $roles = [$role];
- $role->jointPermissions()->delete();
-
- // Chunk through all books
- $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
- $this->buildJointPermissionsForBooks($books, $roles);
- });
-
- // Chunk through all bookshelves
- Bookshelf::query()->select(['id', 'restricted', 'owned_by'])
- ->chunk(50, function ($shelves) use ($roles) {
- $this->buildJointPermissionsForShelves($shelves, $roles);
- });
- }
-
/**
* Delete all the entity jointPermissions for a list of entities.
*
* @param Entity[] $entities
- *
- * @throws Throwable
*/
protected function deleteManyJointPermissionsForEntities(array $entities)
{
- $idsByType = $this->entitiesToTypeIdMap($entities);
+ $simpleEntities = $this->entitiesToSimpleEntities($entities);
+ $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
DB::transaction(function () use ($idsByType) {
foreach ($idsByType as $type => $ids) {
}
/**
- * Create & Save entity jointPermissions for many entities and roles.
- *
* @param Entity[] $entities
- * @param Role[] $roles
*
- * @throws Throwable
+ * @return SimpleEntityData[]
*/
- protected function createManyJointPermissions(array $entities, array $roles)
+ protected function entitiesToSimpleEntities(array $entities): array
{
- $this->readyEntityCache($entities);
- $jointPermissions = [];
+ $simpleEntities = [];
- // Create a mapping of entity restricted statuses
- $entityRestrictedMap = [];
foreach ($entities as $entity) {
- $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->getRawAttribute('id')] = boolval($entity->getRawAttribute('restricted'));
+ $attrs = $entity->getAttributes();
+ $simple = new SimpleEntityData();
+ $simple->id = $attrs['id'];
+ $simple->type = $entity->getMorphClass();
+ $simple->owned_by = $attrs['owned_by'] ?? 0;
+ $simple->book_id = $attrs['book_id'] ?? null;
+ $simple->chapter_id = $attrs['chapter_id'] ?? null;
+ $simpleEntities[] = $simple;
}
+ return $simpleEntities;
+ }
+
+ /**
+ * Create & Save entity jointPermissions for many entities and roles.
+ *
+ * @param Entity[] $originalEntities
+ * @param Role[] $roles
+ */
+ protected function createManyJointPermissions(array $originalEntities, array $roles)
+ {
+ $entities = $this->entitiesToSimpleEntities($originalEntities);
+ $this->readyEntityCache($entities);
+ $jointPermissions = [];
+
// Fetch related entity permissions
$permissions = $this->getEntityPermissionsForEntities($entities);
// Create a mapping of explicit entity permissions
$permissionMap = [];
foreach ($permissions as $permission) {
- $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
- $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
- $permissionMap[$key] = $isRestricted;
+ $key = $permission->entity_type . ':' . $permission->entity_id . ':' . $permission->role_id;
+ $permissionMap[$key] = $permission->view;
}
// Create a mapping of role permissions
// Create Joint Permission Data
foreach ($entities as $entity) {
foreach ($roles as $role) {
- foreach ($this->getActions($entity) as $action) {
- $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
- }
+ $jointPermissions[] = $this->createJointPermissionData(
+ $entity,
+ $role->getRawAttribute('id'),
+ $permissionMap,
+ $rolePermissionMap,
+ $role->system_name === 'admin'
+ );
}
}
/**
* From the given entity list, provide back a mapping of entity types to
* the ids of that given type. The type used is the DB morph class.
- * @param Entity[] $entities
+ *
+ * @param SimpleEntityData[] $entities
+ *
* @return array<string, int[]>
*/
protected function entitiesToTypeIdMap(array $entities): array
$idsByType = [];
foreach ($entities as $entity) {
- $type = $entity->getMorphClass();
-
- if (!isset($idsByType[$type])) {
- $idsByType[$type] = [];
+ if (!isset($idsByType[$entity->type])) {
+ $idsByType[$entity->type] = [];
}
- $idsByType[$type][] = $entity->getRawAttribute('id');
+ $idsByType[$entity->type][] = $entity->id;
}
return $idsByType;
}
/**
- * Get the entity permissions for all the given entities
- * @param Entity[] $entities
- * @return EloquentCollection
+ * Get the entity permissions for all the given entities.
+ *
+ * @param SimpleEntityData[] $entities
+ *
+ * @return EntityPermission[]
*/
- protected function getEntityPermissionsForEntities(array $entities)
+ protected function getEntityPermissionsForEntities(array $entities): array
{
$idsByType = $this->entitiesToTypeIdMap($entities);
- $permissionFetch = EntityPermission::query();
-
- foreach ($idsByType as $type => $ids) {
- $permissionFetch->orWhere(function (Builder $query) use ($type, $ids) {
- $query->where('restrictable_type', '=', $type)->whereIn('restrictable_id', $ids);
+ $permissionFetch = EntityPermission::query()
+ ->where(function (Builder $query) use ($idsByType) {
+ foreach ($idsByType as $type => $ids) {
+ $query->orWhere(function (Builder $query) use ($type, $ids) {
+ $query->where('entity_type', '=', $type)->whereIn('entity_id', $ids);
+ });
+ }
});
- }
- return $permissionFetch->get();
- }
-
- /**
- * Get the actions related to an entity.
- */
- protected function getActions(Entity $entity): array
- {
- $baseActions = ['view', 'update', 'delete'];
- if ($entity instanceof Chapter || $entity instanceof Book) {
- $baseActions[] = 'page-create';
- }
- if ($entity instanceof Book) {
- $baseActions[] = 'chapter-create';
- }
-
- return $baseActions;
+ return $permissionFetch->get()->all();
}
/**
* Create entity permission data for an entity and role
* for a particular action.
*/
- protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
+ protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
{
- $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
- $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
- $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
- $explodedAction = explode('-', $action);
- $restrictionAction = end($explodedAction);
-
- if ($role->system_name === 'admin') {
- return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
+ $permissionPrefix = $entity->type . '-view';
+ $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
+ $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
+
+ if ($isAdminRole) {
+ return $this->createJointPermissionDataArray($entity, $roleId, true, true);
}
- if ($entity->restricted) {
- $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
+ if ($this->entityPermissionsActiveForRole($permissionMap, $entity, $roleId)) {
+ $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
- return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
+ return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
}
- if ($entity instanceof Book || $entity instanceof Bookshelf) {
- return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
+ if ($entity->type === 'book' || $entity->type === 'bookshelf') {
+ return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
}
// For chapters and pages, Check if explicit permissions are set on the Book.
$book = $this->getBook($entity->book_id);
- $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
- $hasPermissiveAccessToParents = !$book->restricted;
+ $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
+ $hasPermissiveAccessToParents = !$this->entityPermissionsActiveForRole($permissionMap, $book, $roleId);
// For pages with a chapter, Check if explicit permissions are set on the Chapter
- if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
+ if ($entity->type === 'page' && $entity->chapter_id !== 0) {
$chapter = $this->getChapter($entity->chapter_id);
- $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
- if ($chapter->restricted) {
- $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
+ $chapterRestricted = $this->entityPermissionsActiveForRole($permissionMap, $chapter, $roleId);
+ $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapterRestricted;
+ if ($chapterRestricted) {
+ $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
}
}
return $this->createJointPermissionDataArray(
$entity,
- $role,
- $action,
+ $roleId,
($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
);
}
+ /**
+ * Check if entity permissions are defined within the given map, for the given entity and role.
+ * Checks for the default `role_id=0` backup option as a fallback.
+ */
+ protected function entityPermissionsActiveForRole(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
+ {
+ $keyPrefix = $entity->type . ':' . $entity->id . ':';
+ return isset($permissionMap[$keyPrefix . $roleId]) || isset($permissionMap[$keyPrefix . '0']);
+ }
+
/**
* Check for an active restriction in an entity map.
*/
- protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
+ protected function mapHasActiveRestriction(array $entityMap, SimpleEntityData $entity, int $roleId): bool
{
- $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
+ $roleKey = $entity->type . ':' . $entity->id . ':' . $roleId;
+ $defaultKey = $entity->type . ':' . $entity->id . ':0';
- return $entityMap[$key] ?? false;
+ return $entityMap[$roleKey] ?? $entityMap[$defaultKey] ?? false;
}
/**
* Create an array of data with the information of an entity jointPermissions.
* Used to build data for bulk insertion.
*/
- protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
+ protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
{
return [
- 'action' => $action,
- 'entity_id' => $entity->getRawAttribute('id'),
- 'entity_type' => $entity->getMorphClass(),
+ 'entity_id' => $entity->id,
+ 'entity_type' => $entity->type,
'has_permission' => $permissionAll,
'has_permission_own' => $permissionOwn,
- 'owned_by' => $entity->getRawAttribute('owned_by'),
- 'role_id' => $role->getRawAttribute('id'),
+ 'owned_by' => $entity->owned_by,
+ 'role_id' => $roleId,
];
}
-
-}
\ No newline at end of file
+}