3 namespace BookStack\Auth\Permissions;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use BookStack\Traits\HasOwner;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use InvalidArgumentException;
17 class PermissionApplicator
20 * Checks if an entity has a restriction set upon it.
22 * @param HasCreatorAndUpdater|HasOwner $ownable
24 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
26 $explodedPermission = explode('-', $permission);
27 $action = $explodedPermission[1] ?? $explodedPermission[0];
28 $user = $this->currentUser();
29 $userRoleIds = $this->getCurrentUserRoleIds();
31 $allRolePermission = $user->can($permission . '-all');
32 $ownRolePermission = $user->can($permission . '-own');
33 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
34 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
35 $isOwner = $user->id === $ownable->getAttribute($ownerField);
36 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
38 // Handle non entity specific jointPermissions
39 if (in_array($explodedPermission[0], $nonJointPermissions)) {
40 return $hasRolePermission;
43 $entityPermissions = $this->getApplicableEntityPermissions($ownable, $userRoleIds, $action);
44 if (is_null($entityPermissions)) {
45 return $hasRolePermission;
48 return count($entityPermissions) > 0;
52 * Get the permissions that are applicable for the given entity item.
53 * Returns null when no entity permissions apply otherwise entity permissions
54 * are active, even if the returned array is empty.
56 * @returns EntityPermission[]
58 protected function getApplicableEntityPermissions(Entity $entity, array $userRoleIds, string $action): ?array
61 if ($entity instanceof Page && $entity->chapter_id) {
62 $chain[] = $entity->chapter;
65 if ($entity instanceof Page || $entity instanceof Chapter) {
66 $chain[] = $entity->book;
69 foreach ($chain as $currentEntity) {
70 if ($currentEntity->restricted) {
71 return $currentEntity->permissions()
72 ->whereIn('role_id', $userRoleIds)
73 ->where('action', '=', $action)
83 * Checks if a user has the given permission for any items in the system.
84 * Can be passed an entity instance to filter on a specific type.
86 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
88 if (strpos($action, '-') !== false) {
89 throw new InvalidArgumentException("Action should be a simple entity permission action, not a role permission");
92 $permissionQuery = EntityPermission::query()
93 ->where('action', '=', $action)
94 ->whereIn('role_id', $this->getCurrentUserRoleIds());
96 if (!empty($entityClass)) {
97 /** @var Entity $entityInstance */
98 $entityInstance = app()->make($entityClass);
99 $permissionQuery = $permissionQuery->where('restrictable_type', '=', $entityInstance->getMorphClass());
102 $hasPermission = $permissionQuery->count() > 0;
104 return $hasPermission;
108 * Limited the given entity query so that the query will only
109 * return items that the user has view permission for.
111 public function restrictEntityQuery(Builder $query): Builder
113 return $query->where(function (Builder $parentQuery) {
114 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
115 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
116 // TODO - Delete line once only views
117 ->where('action', '=', 'view')
118 ->where(function (Builder $query) {
119 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
126 * Extend the given page query to ensure draft items are not visible
127 * unless created by the given user.
129 public function enforceDraftVisibilityOnQuery(Builder $query): Builder
131 return $query->where(function (Builder $query) {
132 $query->where('draft', '=', false)
133 ->orWhere(function (Builder $query) {
134 $query->where('draft', '=', true)
135 ->where('owned_by', '=', $this->currentUser()->id);
141 * Add restrictions for a generic entity.
143 public function enforceEntityRestrictions(Entity $entity, Builder $query): Builder
145 if ($entity instanceof Page) {
146 // Prevent drafts being visible to others.
147 $this->enforceDraftVisibilityOnQuery($query);
150 return $this->entityRestrictionQuery($query);
154 * The general query filter to remove all entities
155 * that the current user does not have access to.
157 protected function entityRestrictionQuery(Builder $query): Builder
159 $q = $query->where(function ($parentQuery) {
160 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
161 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
162 // TODO - Delete line once only views
163 ->where('action', '=', 'view')
164 ->where(function (Builder $query) {
165 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
174 * Filter items that have entities set as a polymorphic relation.
175 * For simplicity, this will not return results attached to draft pages.
176 * Draft pages should never really have related items though.
178 * @param Builder|QueryBuilder $query
180 public function filterRestrictedEntityRelations($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
182 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
183 $pageMorphClass = (new Page())->getMorphClass();
185 $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
186 /** @var Builder $permissionQuery */
187 $permissionQuery->select(['role_id'])->from('joint_permissions')
188 ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
189 ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
190 ->where('joint_permissions.action', '=', 'view')
191 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
192 ->where(function (QueryBuilder $query) {
193 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
195 })->where(function ($query) use ($tableDetails, $pageMorphClass) {
196 /** @var Builder $query */
197 $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
198 ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
199 $query->select('id')->from('pages')
200 ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
201 ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
202 ->where('pages.draft', '=', false);
210 * Add conditions to a query to filter the selection to related entities
211 * where view permissions are granted.
213 public function filterRelatedEntity(string $entityClass, Builder $query, string $tableName, string $entityIdColumn): Builder
215 $fullEntityIdColumn = $tableName . '.' . $entityIdColumn;
216 $instance = new $entityClass();
217 $morphClass = $instance->getMorphClass();
219 $existsQuery = function ($permissionQuery) use ($fullEntityIdColumn, $morphClass) {
220 /** @var Builder $permissionQuery */
221 $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
222 ->whereColumn('joint_permissions.entity_id', '=', $fullEntityIdColumn)
223 ->where('joint_permissions.entity_type', '=', $morphClass)
224 ->where('joint_permissions.action', '=', 'view')
225 ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
226 ->where(function (QueryBuilder $query) {
227 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
231 $q = $query->where(function ($query) use ($existsQuery, $fullEntityIdColumn) {
232 $query->whereExists($existsQuery)
233 ->orWhere($fullEntityIdColumn, '=', 0);
236 if ($instance instanceof Page) {
237 // Prevent visibility of non-owned draft pages
238 $q->whereExists(function (QueryBuilder $query) use ($fullEntityIdColumn) {
239 $query->select('id')->from('pages')
240 ->whereColumn('pages.id', '=', $fullEntityIdColumn)
241 ->where(function (QueryBuilder $query) {
242 $query->where('pages.draft', '=', false)
243 ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
252 * Add the query for checking the given user id has permission
253 * within the join_permissions table.
255 * @param QueryBuilder|Builder $query
257 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
259 $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
260 $query->where('joint_permissions.has_permission_own', '=', true)
261 ->where('joint_permissions.owned_by', '=', $userIdToCheck);
266 * Get the current user.
268 protected function currentUser(): User
274 * Get the roles for the current logged-in user.
278 protected function getCurrentUserRoleIds(): array
280 if (auth()->guest()) {
281 return [Role::getSystemRole('public')->id];
284 return $this->currentUser()->roles->pluck('id')->values()->all();